Syntactic Sugar
Jake Shoudy
Nov 18, 2022
CSCI 110 - Lecture 33
Announcements
HW10
Last assignment
Classes and sorting
Due Monday November 21st at 11:59pm
Final Exam Date!
Tuesday 11/29 during normal lab hours
Final Exam Topics
Binary <-> Base 10
Data types
Operators (arithmetic, comparison, logical)
Variables
if / elif / else
while loops
Strings (length, index, slice)
Functions
For Loops
Will include short answer & coding questions
Lists
2D Lists
Big O
Sets
Dictionaries
Nested Dictionaries
Scope
Pass by Reference vs Pass by Value
Classes
Sorting
Reminder: NO CLASS NEXT WEEK
Cancelling class on Monday and Tuesday
Wednesday - Friday are school holidays
There will be a Kahoot review session on Monday the 28th
Practice Test!
I will release a practice test next week (goal is by Wednesday)
Take it on your own time over the following weekend and use it to study!!
Recap
Recursion
Recursion
Mystery Function
def mystery(num):
if num == 1:
return 1
else:
return num * mystery(num - 1)
Thinking recursively
mystery(5) = 5 * mystery(4)
4 * mystery(3)
3 * mystery(2)
2 * mystery(1)
Thinking recursively
mystery(5) = 5 * mystery(4)
4 * mystery(3)
3 * mystery(2)
2 * 1
Thinking recursively
mystery(5) = 5 * mystery(4)
4 * mystery(3)
3 * 2
Thinking recursively
mystery(5) = 5 * mystery(4)
4 * 6
Thinking recursively
mystery(5) = 5 * 24
Thinking recursively
mystery(5) = 120
Factorial!
def factorial(num):
if num == 1:
return 1
else:
return num * mystery(num - 1)
Base case
Recursive case
Recursive art!
Syntactic Sugar
Language Expressiveness
Think about human languages. There are some words that can’t be translated into English.
Schadenfreude
Schaden - freude
harm - joy
A German word meaning “A feeling of enjoyment that comes from seeing or hearing about the troubles of other people”
Programming languages are the same - some languages have concise ways to express ideas that are harder to express in other languages.
“Syntactic Sugar”
Syntactic Sugar isn’t an official coding term, but you’ll hear it used to describe types of constructs in coding languages that are pleasing.
It refers to any kind of syntax that makes the code “sweeter” for human use, whether for reading or writing the code.
Python is known for providing lots of “syntactic sugar”, and sometimes you’ll hear people describe using this syntactic sugar in Python as writing “Pythonic” code”
“Syntactic Sugar”
None of the new ideas from this lecture will enable you to do something you couldn’t do before.
They will just make some idea easier to implement than you could without them.
Boolean “zen”
Working with booleans
This code works!
def is_smaller(a, b): if a < b == True: return True elif a >= b == True: return False |
Working with booleans
Better!
def is_smaller(a, b): if a < b: return True else: return False |
Boolean “zen”
Best!
def is_smaller(a, b): return a < b |
Ternary Operator
Ternary Operator
The ternary operator (meaning “having three parts”) is an expression that will evaluate to one of two values, based on what the condition inside evaluates to.
<val1> if <condition> else <val2> |
Ternary Operator
Without Ternary Operator
def generate_ticket(speed_over): if speed_over < 10: ticket = 0 else: ticket = 100 print("Pay $" + str(ticket)) |
def generate_ticket(speed_over): ticket = 0 if speed_over < 10 else 100 print("Pay $" + str(ticket)) |
With Ternary Operator
You can use the ternary operator to simplify your code in situations where both cases in the conditional just set a value to a variable.
List Comprehensions
Motivation - Creating Sequences
Make me a list of the powers of 2 from 1 to 10.
The way we already know: use a range, use `**` to exponentiate, add to list
4 lines seems like a lot of lines...
powers_of_two = [] for i in range(1, 11): result = 2 ** i powers_of_two.append(result) print(powers_of_two) |
List Comprehensions
We can use the list comprehension construct to quickly and easily generate a list involving iteration over an existing sequence.
The syntax is designed to read like English: "Compute the expression for each element in the sequence (if the conditional is true for that element)."
[<expression> for <element> in <sequence> if <conditional>] |
The conditional part is optional
List Comprehension
Using list comprehension to generate the first 10 powers of two...
powers_of_two = [2 ** i for i in range(1, 11)] |
List Comprehension Examples
Let’s look at a more complicated example:
This list comprehension will:
lst = [i**2 for i in [1, 2, 3, 4] if i % 2 == 0] |
Expression
Sequence
Conditional
Element Variable name
List Comprehension Examples
Without List Comprehension
With List Comprehension
lst = [] for i in [1, 2, 3, 4]: if i % 2 == 0: lst.append(i**2) |
lst = [i**2 for i in [1, 2, 3, 4] if i % 2 == 0] |
List Comprehension Examples
Filter a list of number down to just positive numbers
It’s a one-line function!
def filter_positives(nums): return [x for x in nums if x > 0] |
List Comprehension Examples
Can do this for sequence of any type! For example, getting a list of all capital letters.
word = "fisk" res = [char.upper() for char in word] print(res) |
>> ['F', 'I', 'S', 'K']
List Comprehensions
Be careful! List comprehensions are a powerful but dangerous tool, because they can get very complicated and are harder to read and debug.
For example, what does this list comprehension do? So hard to read!
Just because you can do something with a list comprehension doesn’t mean you should do it with a list comprehension.
[y for x in text if len(x)>3 for y in x] |
Important Note
Iterable Unpacking
Iterables
An iterable is anything that you can iterate over. You’ve been using them all along, this is just a name to describe any of:
Iterable Unpacking
It is a common pattern to want to assign values in an iterable to individual variables.
Iterable unpacking lets you do this in a prettier way.
coordinates = [10, 23] x = coordinates[0] y = coordinates[1] # Using iterable unpacking x, y = coordinates |
Returning Multiple Values
Note that you can use this to return multiple values from a function!
def min_and_max(nums): min_num = nums[0] max_num = nums[0] for num in nums: if num > max_num: max_num = num if num < min_num: min_num = num return min_num, max_num nums = [4, 2, 10, 6, -1, 3] mini, maxi = min_and_max(nums) |
Dictionary Comprehensions
Dictionary Comprehensions
Very similar to List Comprehensions, we can use Dictionary Comprehension syntax to make creating dictionaries based on an iterable easier.
The syntax is designed to read like English: "Compute the key expression and associated value expression for each element in the sequence (if some conditional is true)."
{<key expression>:<value expression> for <element> in <sequence> if <conditional>} |
The conditional part is optional
Dictionary Comprehension Examples
powers_of_2 = {i:2**i for i in range(5)} print(powers_of_2) |
>> {0: 1, 1: 2, 2: 4, 3: 8, 4}
Filtering Dictionaries with Comprehensions
The `.items()` function of a dictionary returns a list of key, value tuples in the dictionary.
grades = {"Alex": 90, "Sarah": 95, "Andre": 87} print(grades.items()) |
>> [('Alex', 90), ('Sarah', 95), ('Andre', 87)]
Filtering Dictionaries with Comprehensions
Combining this with iterable unpacking, we can access both the key and value of a dictionary inside a dictionary comprehension.
For example, to filter a dictionary down to just the keys/values where the key starts with an A:
grades = {"Alex": 90, "Sarah": 95, "Andre": 87} a_grades = {k:v for k,v in grades.items() if k[0] == "A"} print(a_grades) |
>> {'Alex': 90, 'Andre': 87}
Conclusion
You all have learned SO MUCH
Binary <-> Base 10
Data types
Operators (arithmetic, comparison, logical)
Variables
if / elif / else
while loops
Strings (length, index, slice)
Functions
For Loops
Lists
2D Lists
Mutability
Images
Big O
Sets
Dictionaries
Nested Dictionaries
Scope
Pass by Reference vs Pass by Value
Classes
Sorting
Recursion
Terminal
Unit testing and Integration Testing
What’s next?
csci110.org will stay up forever. Reference the website/slides to review material as needed, or share with friends who want to learn to code.
Decide whether to take take more CS classes. I encourage you all to learn more CS, but I know not everyone has the time or desire...that said, it is a fun field to study and fantastic field to get a job in.
If you will take more CS classes...
Bias for learning concepts over languages. To that end, where the option exists, I advise you take classes in a wider array of languages, as each language exposes you to new concepts.
Make sure to try a systems class (operating systems or networking), a theory class (algorithms), and a machine learning class to know a bit about each subfield.
If you’re at all interested in software engineering, security, systems, computer architecture, and most anything else within Computer Science:
For those of you only interested in data science, mathematical modeling, etc...
If you aren’t taking more CS classes...
Go forth into your field armed with the problem solving techniques you’ve learned in this class. You may find that CS will be very useful in your field in the next 5-10 years, and you’ll be prepared.
Remember that you can always come back and learn more in the future. For self-paced CS courses, I recommend the following:
Practice!
Whether you’re planning on interviewing for software engineering internships/jobs or just want more coding practice here are a couple of resources:
* Wide range of difficulty here so don’t get discouraged :) Most questions are labeled with difficulty. Start with just the “easy” problems
Reach Out!
As you navigate your time in college, and start your careers after graduating, stay in touch. Let me know how things are going, ask for advice on classes to take, or topics to learn, or tutorials to follow.
Talk to me or any Fisk TAs while we’re here, csci110.org/staff.
THANK YOU!