Module 2 • Introduction to Python
=, which works from right to left.
Python evaluates the expression on the right side of = first, then stores the result in the variable on the left.
x = 10 # Store 10 in x y = x + 5 # Evaluate x + 5 (15), store in y x = x + 1 # Evaluate x + 1 (11), store back in x
if, for, class, etc.)snake_case= (assignment) with == (comparison). In Python, x = 5 means "assign 5 to x." The expression x == 5 means "is x equal to 5?" and returns a Boolean.
int) are whole numbers. Floats (float) have decimal points.
Know each operator and what it returns:
+ addition, - subtraction, * multiplication/ division (always returns float!)// integer division (rounds down to whole number)% modulo (gives the remainder)** exponentiation/) always returns a float, even for 10 / 2 = 5.0. Use // if you want an integer result.
()**# Convert total minutes to hours and minutes total_minutes = 135 hours = total_minutes // 60 # 2 minutes = total_minutes % 60 # 15 # Check if a number is even number % 2 == 0 # True if even
"Hello" + " " + "World" produces "Hello World""Go! " * 3 produces "Go! Go! Go! "len("Python") returns 6"Python"[0] returns "P" (zero-based!)\n = newline, \t = tab\\ = literal backslash\' = single quote, \" = double quote"Age: " + 25 causes a TypeError. Fix it with "Age: " + str(25).
True and False (capitalized). Every value in Python is either "truthy" or "falsy."
int() -- converts to integer (truncates decimals, does NOT round)float() -- converts to floatstr() -- converts to stringbool() -- converts to Booleantype() -- checks the type (does not convert)0 and 0.0 (zero)"" (empty string)NoneFalsebool("0") is True because "0" is a non-empty string. The character "0" is still content. Only "" is falsy.
Q1: What value does x hold after: x = 10; x += 5; x *= 2?
A: 30 (10 + 5 = 15, then 15 * 2 = 30)
Q2: What is 17 // 3 and 17 % 3?
A: 5 and 2 (17 = 5*3 + 2)
Q3: What does type(10 / 5) return?
A: <class 'float'> -- division always returns a float (even 10/5 = 2.0)
Q4: How do you convert "3.14" to an integer?
A: int(float("3.14")) -- convert to float first, then to int. Direct int("3.14") causes a ValueError.
Q5: Which of these are falsy: 0, "hello", "", None, "False", -1?
A: 0, "", and None are falsy. "hello", "False" (non-empty string!), and -1 (non-zero number) are truthy.
Q6: What is len("Hi\nBye")?
A: 6 -- \n counts as one character: H-i-\n-B-y-e = 6
=True or False+%)int() does)