Python, the Basics

Jon Reades

Variables

Variables Have Types…

Name Value Type
msg ‘Hello world’ type(msg)==str
answer 42 type(answer)==int
pi 3.14159 type(pi)==float
c complex(5,2) type(c)==complex
correct True type(correct)==bool

… But We Can Change That

Message starts as a string:

msg = '42'
type(msg) # str

But we can change it to an integer like this:

msg = int(msg)
type(msg) # change to int

And back to a string:

msg = str(msg)
type(msg) # back to str

And notice:

print(str(int('42'))) # string from int from string

…And They Are All Objects

One to remember for the session on objects and classes:

isinstance(msg,object)     # True
isinstance(answer,object)  # True
isinstance(pi,object)      # True
isinstance(c,object)       # True
isinstance(correct,object) # True

Variables Have Names…

Rules for variable names:

  • 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 may not complain, but strange things will happen when you run your code.

and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try

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 output information:

  1. string concatenation using +;
  2. string formatting using <str>.format(<variables>); and
  3. f-strings using f"{variable_1} some text {variable_n}".

There are pros and cons to each:

x = 24
y = '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, 5
x + y * 2         # == 20
(x + y) * 2       # == 30
x + y * 2 / 3     # == 13.3333333333334
x + y * (2/3)     # == 13.3333333333332
(x + y) * (2/3)   # == 10.0

And here’s a subtle one:

(x * y) ** 2/3    # == 833.333333333334
(x * y) ** (2/3)  # == 13.5720880829745

The full list is here.

Comparing Variables

For numeric variables comparisons are easy.

Operator Input Result
== 10 == 5 False
!= 10 != 5 True
<, <= 10 < 5 False
>, >= 10 > 5 True

Strings Are Different

But notice:

w, x, y, z = '4a','4a','365','42'
w == x  # True
w != y  # True
x > y   # True
x > z   # True

Why is 4a greater than both 365 and 42?

Danger, Will Robinson!

Notice the very subtle visual difference between = and ==!

x = 5
y = 10
x = y   # Probably a mistake: setting x to the value of y
x == y  # True, because x and z are now both set to 10

Remember this!

Common Mistakes

Here’s the output from some attempts at comparison:

x, y = '42', 42
x==y   # False
x>y    # An error!

This last line produces:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'

If we want to compare them then we’ll need to change their type:

x > str(y)   # False
int(x) <= y  # True
x > = str(y) # Also True

More Resources

Here are some links to videos on LinkedIn Learning that might help, and YouTube will undoubtedly have lots more options and styles of learning: