They cannot start with a number: item3 is valid, 3items is not.
White space and symbols are not allowed, but _is allowed: my_variable is valid, my-variable, my$variable, and my variable are not.
Case matters: myVar is different from both myvar and MYVAR
Be consistent: my_var is more ‘Pythonic’, though myVar is also widely used; but don’t mix these!
Variable names should be long enough to be clear but not so long as to be impractical: bldg_height vs. bh vs. max_building_height_at_eaves.
…But Not All Words Are Allowed
Do not try to use any of these as variable names: Python will refuse with a SyntaxError.
False
None
True
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield
Python will let you reuse the names of built-in functions such as list, str, or sum, but then they stop working: after list = [1,2], calling list('abc') raises a TypeError.
Operators
Simple Operations on Variables
Let’s start with x=10 and y=5…
Operator
Input
Result
Sum
x + y
15
Difference
x - y
5
Product
x * y
50
Quotient
x / y
2.0
‘Floored’ Quotient
x // y
2
Remainder
x % y
0
Power
pow(x,y) or x**y
100000
Equality
x==y
False
Strings Are Different
When you do things with strings the answers can look a little different. Let’s start with x="Hello" and y="You" and z=2…
Operator
Input
Result
Sum
x + y
'HelloYou'
Difference
x - y
TypeError
Product
x * z
HelloHello
Equality
x==y
False
Using Strings to Output Information
Python has no fewer than three ways to output information:
string concatenation using +;
string formatting using <str>.format(<variables>); and
f-strings using f"{variable_1} some text {variable_n}".
There are pros and cons to each:
x =24y ='Something'print("The value of "+ y +" is "+str(x))print("The value of {0} is {1}".format(y, x))print(f"The value of {y} is {x}")
Operators Assemble!
Always pay attention to precedence:
x, y =10, 5x + y *2# == 20(x + y) *2# == 30x + y *2/3# == 13.3333333333334x + y * (2/3) # == 13.3333333333332(x + y) * (2/3) # == 10.0