Python essentials to get you started
Contents
Python essentials to get you started#
This notebook is designed to familiarize you with some basic programming constructs before the start of actual instruction. If you’ve coded before, this will show you how stuff you already know are implemented in the Python programming language. If you’ve never coded before, you’ll probably be a bit confused. Don’t worry! The class hasn’t started yet!
Variable types and assignments#
Variables are the building blocks of programs. You tell a compute what to do largely by maniulating the values of variables. Variables come in different types such as string
, integer
, boolean
, and float
. Because Python is what’s called a dynamically typed language, you don’t have to declare the type of variable before assigning a value to it. For example, let’s look at these 6 (very badly named) variables.
var_1 = "five"
var_2 = 5
var_3 = "5"
var_4 = 5.0
var_5 = True
var_6 = "True"
Now let’s print them out
print('var_1 = ',var_1)
print('var_2 = ',var_2)
print('var_3 = ',var_3)
print('var_4 = ',var_4)
print('var_5 = ',var_5)
print('var_6 = ',var_6)
var_1 = five
var_2 = 5
var_3 = 5
var_4 = 5.0
var_5 = True
var_6 = True
Now let’s print out the types of variables these are:
print('var_1 = ',type(var_1))
print('var_2 = ',type(var_2))
print('var_3 = ',type(var_3))
print('var_4 = ',type(var_4))
print('var_5 = ',type(var_5))
print('var_6 = ',type(var_6))
var_1 = <class 'str'>
var_2 = <class 'int'>
var_3 = <class 'str'>
var_4 = <class 'float'>
var_5 = <class 'bool'>
var_6 = <class 'str'>
Notice that var_2
and var_3
have exactly the same printed value (5). var_5
and var_6
also have the same value (True). In both cases, however, they are of different types, e.g., var_2
is an integer while var_3
is a string; var_5
is a boolean while var_6
is a string.
Does this matter? Yes it does! Have a look at what happens when we try to add 3 to var_2
vs. var_3
print("Adding 3 to var_2 gets us ", var_2+3)
print("Adding 3 to var_3 gets us ", var_3+3)
Adding 3 to var_2 gets us 8
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/glupyan/gitRepos/psych750.github.io/notebooks/python_basics.ipynb Cell 10 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/glupyan/gitRepos/psych750.github.io/notebooks/python_basics.ipynb#X12sZmlsZQ%3D%3D?line=0'>1</a> print("Adding 3 to var_2 gets us ", var_2+3)
----> <a href='vscode-notebook-cell:/Users/glupyan/gitRepos/psych750.github.io/notebooks/python_basics.ipynb#X12sZmlsZQ%3D%3D?line=1'>2</a> print("Adding 3 to var_3 gets us ", var_3+3)
TypeError: can only concatenate str (not "int") to str
The first one is 8 because. 5+3=8.
The second one throws a TypeError because you tried to combine two types (a string and an integer) in a way that could not be resolved. The string ‘5’ + the integer 3 is not defined. Computers are literal-minded. Just because something looks like the number 5 doesn’t make it a five!
Note
You will be seeing a lot of error messages like the one above. Don’t let them intimidate you. Generally, the very last line will tell you what kind of error it is (in this case, a TypeError meaning that something went wrong when combining different variable types). The text above tells you where in your code the error is coming from.
Now have a look at this. Try to predict what happens before looking at the output
print(var_3+'3')
53
What happened here?! The Python interpreter was asked to add the string ‘3’ to the string ‘5’. A human is cognizant that these are numbers, but the Python interpreter doesn’t care. To it, these are just text strings. What’s a reasonable thing to do when asked to add two strings? Python defines string addition as concatenation, i.e.,string1a+string2=string1string2
. That’s why we get 52
(which is itself a string!!) as the answer.
So, in the context of numbers (integers and floats) +
is arithmetic addition. In the context of strings, it’s concatenation. This is called operator overloading
Now let’s try this one. Let’s multiply var_2
and var_3
by 3. What do you think will happen?
print(var_2*3)
print(var_3*3)
15
555
A bit more about printing#
Although printing is not something we’ll be doing much of as an end in itself, it’s massively useful for debugging your code, i.e., for knowing what a value of vertain variables is at a certain point in your code. We’ll talk more about this when we discuss debugging.
When you print, Python will try to convert what you are printing to a string. But if you try to print several different data types or combine the printing of strings and variables – both of which is something you’ll be doing a lot of when debugging – it gets cumbersome. Observe:
Simple enough:
name = "George's dog"
But what about this?
name = "George"
print(name+"'s "+"dog")
George's dog
Yuck… that’s a lot of quotes and figuring out where the spaces should go.
Python 3 provides a bit of “syntactic sugar” for printing combinations of raw strings and variables of different types:
name = "George"
print(f"{name}'s dog")
George's dog
To use so-called f strings (f stands for formatted) just encase the variables in curly-braces and write out the regular text part of the string as normal. Read more about these f-strings here
Lists and for
loops#
A data structure you’ll be using a whole lot in Python is a list. For those coming from other programming languages, lists are largely the same as arrays, although Python lists can mix different types of variables. For example:
a_list = [1, '1', 'two', 'three', 4]
print(a_list)
print(a_list[0], 'is a', type(a_list[0]))
[1, '1', 'two', 'three', 4]
1 is a <class 'int'>
A common way of iterating through lists is by using a for
loop.
animals = ['dog', 'cat', 'pig']
for animal in animals:
print(animal)
dog
cat
pig
A common use of for
loops is to do something a certain number of times. For example, let’s print the first 10 integers, beginning from 0:
for cur_num in range(10):
print(cur_num)
0
1
2
3
4
5
6
7
8
9
What happened here?
range()
generated a list of numbers in the specified range, beginning from 0. Then for
iterates through those numbers, printing the value of each.
You don’t have to start at 0. Pass a starting number to range()
like so.
for cur_num in range (5,10):
print(cur_num)
5
6
7
8
9
Note
Technically range() returns a range object
which is a “lazy iterable” and is executed only later, when we try to access its values. This is different from Python 2 where range()
returns a regular list.
What about counting by 2s or counting down? Simple
for cur_num in range(0,10,2):
print(cur_num)
0
2
4
6
8
for cur_num in range(10,0,-1):
print(cur_num)
10
9
8
7
6
5
4
3
2
1
Tip
If all you need to do is to execute some command a certain number of times, there’s a Python convention to use _
as a throwaway index variable, for example, let’s generate 5 random integers between 1-10:
import random
for _ in range(25):
print(random.randrange(1,10+1))
A while
loop#
Another kind of loop we’ll use is a while
loop. We use this to iterate until a condition is met (i.e., something that’s false
becomes true
), or a condition is no longer met (i.e., something that’s true
becomes false
).
another_num=5
while another_num>0:
print(f"I'm a {another_num} and I'm greater than 0!")
another_num -= 1
I'm a 5 and I'm less than or equal to 5!
I'm a 4 and I'm less than or equal to 5!
I'm a 3 and I'm less than or equal to 5!
I'm a 2 and I'm less than or equal to 5!
I'm a 1 and I'm less than or equal to 5!
What happened here?
The first line of the while loop evaluates the truth value of another_num being greater than 0. As long as both of these conditions are met, we execute the loop. On each iteration, we decrease the value of another_num by 1 until it’s no longer greater than 0 at which point the while loop exits.
s = ""
while len(s)<10:
s+="z"
print(s)
z
zz
zzz
zzzz
zzzzz
zzzzzz
zzzzzzz
zzzzzzzz
zzzzzzzzz
zzzzzzzzzz
Note
+=
is shorthand for add and self-assign, i.e.,
s+=”z” is equivalent to s = s+”z”
Primer on conditionals (if
statements)#
my_num = 5
if my_num == 5:
print("it's a 5!")
else:
print("it's not a 5!")
it's a 5!
if 5<2:
print('yes indeed')
elif 10<2:
print('this is true too!')
Predict what each of these statements will return. Then check.
my_num = '5'
if my_num == 5:
print("it's a 5!")
else:
print("it's not a 5!")
it's not a 5!
print('s'==True)
False
print(1==True)
True
print (0==True)
False
print (True==False)
False
print ((True or False)==True)
True
Let’s end with a weird one…
if print==True or print==False:
print('all is good')
else:
print('uh oh')
uh oh
print(type(print))
print(print==True)
print(print==False)
<class 'builtin_function_or_method'>
False
False