Python Basics¶

We definitely can't teach you everything in a day, but hopefully we can get you going in the right direction.

In this notebook we'll cover:

  • Variables
  • Common data types
  • Indexing
  • Control flow
  • Logical operators
  • lists
  • iterating with for and while loops
  • importing other libraries

Let's get started!¶

The All Important print function:

print('hello world')
In [1]:
print('hello world')
hello world

In this example, hello world is a text string aka string.

We told Python to print it using the print() function.

In Python, a function is some "command" followed by input parameter(s) in parentheses... :
someFunction(input) or someFunction(input1,input2). print() is a function.

You can—and should—write your own functions, but that's slightly out of scope for today. If you're a beginner, for today think of a function as some pre-written code you can use that completes some task.


Variables¶

You declare variables with an equals sign =

my_var = 'hello world'
In [8]:
my_var = 'hello world'
my_var
In [9]:
my_var
Out[9]:
'hello world'
print(my_var)
In [10]:
print(my_var)
hello world

If you don't like it, just reassign it:

my_var = 'whatever!'
In [1]:
my_var = 'whatever!'

String concatenation:

To put to string sequences together, use a plus sign +

print('Hello World' + 'My name is Screwball')
In [ ]:
 
print(my_var + ', Screwball!')
In [2]:
print(my_var + ', Screwball!')
whatever!, Screwball!

A variable can be anything.


Data types¶

There are several data types and structures. Today, we'll concern ourselves with the most used:

  • String (text)
  • Integer (numbers)
  • Float (also numbers)
  • List (a list of values)
  • Tuple (kind of like a list)
  • Dictionary (key and value pairs)

These and others are built into Python. There are many more that can be imported with other libraries (more on that later).

You can find out what type you're working with using the type() function:

type(my_var)
In [95]:
type(my_var)
Out[95]:
str

That's a string. Strings are declared using single or double quotes (pretty much interchangeable).

my_var2 = 1

print(type(my_var2))
In [14]:
my_var2 = 1

print(type(my_var2))
<class 'int'>

Just some useful string methods:

len() .split() .replace() .lower() .upper() .startswith() .strip() .find()

More.

Try a few:

my_var.upper()
In [79]:
my_var = 'hello world '

print(my_var.replace('world','you filthy animal!'))
hello you filthy animal! 

Can we mix data types?

my_var + my_var2
In [16]:
my_var2 + my_var
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[16], line 1
----> 1 my_var2 + my_var

TypeError: unsupported operand type(s) for +: 'int' and 'str'
my_var + ", it's me."
In [18]:
my_var + ", it's me, Phil."
Out[18]:
"hello world, it's me, Phil."
my_var2 + 5
In [20]:
my_var2 + 5
Out[20]:
6

Operators:¶

There are many.

Arithmetic pretty much behave as you would think:
+, -, *, /, as well as ** exponential, % modulus, // floor.

Comparison
== equal, != not equal, >, >=, <, <=

Logical
and, or, not

In [52]:
var1 = 1
var2 = 'Chainsaw'

var1 == 1 and var2 == 'screwdriver'
Out[52]:
False

Bonus: += is very useful.

In [ ]:
 
In [ ]:
 

Control Flow:¶

Use if, else, and elif to control the flow of your process.

var1 = 1

if var1 == 1: # boolean check if value equals 1
    print('yes') # print yes if True 
else:
    print('no') # print no if False
In [94]:
var1 = 2

if var1 > 1:
    print('yes')

elif var1 < 3:
    print('yes')

else:
    print('no')
yes

Lists:¶

You create lists using brackets: []

my_list = ['a','b','c'] 

print(my_list)
In [22]:
my_list = ['a','b','c']

print(my_list)
['a', 'b', 'c']

The .append() list method is very useful for populating lists:

Create an empty list:

new_list = []

Then use append to add new items:

new_list.append('item1')
In [102]:
new_list = []
In [105]:
new_list.append('thingy32')

print(new_list)
['thingy', 'thingy2', 'thingy32']

Indexing!¶

Is very important! Rule number 1: Python indexing begins at zero.

You also use brackets to access indexing.

Try these:

my_list[0]

my_list[1]

my_list[3]
In [26]:
my_list[0]
Out[26]:
'a'

Now try on a string variable:

my_var[0]

my_var[3]

my_var[8]

my_var[-1]
In [28]:
print(my_var)

my_var[8]
hello world
Out[28]:
'r'

Index slicing:

my_var[0:3]

First position is start, second position is one after you want it to stop...

In [40]:
print('what the ' + my_var[0:4]+'?')
what the hell?

Iteration¶

One of the main reasons people learn to code is to make a computer do repetitive things. This is where looping comes into play.

There are two types of loops:

  • for loops repeat a set number of types.
  • while loops repeat until a condition is met.

for loops:

my_nums = [1,2,3,4,5]

for n in my_nums:
    print(n)
In [2]:
my_nums = [1,2,3,4,5]
In [7]:
for n in my_nums:
    print(n)
1
2
3
4
5
In [8]:
for n in my_nums:
    # try some stuff!
    
    print(n)
2
4
6
8
10
In [13]:
my_nums
Out[13]:
[1, 2, 3, 4, 5]
In [10]:
range(len(my_nums))
Out[10]:
range(0, 5)
In [12]:
for i in range(len(my_nums)):
    print(i, my_nums[i])
0 1
1 2
2 3
3 4
4 5
In [14]:
for i in range(len(my_nums)):
    my_nums[i] += 2
print(my_nums) 
[3, 4, 5, 6, 7]

Challenge! Usering the .append() method, loop over the my_nums list and populate a new list with these values: [2,4,6,8,10]

Bonus: make the list values string types

In [ ]:
new_list = []

for n in my_nums:
    # put your code here

while loops:

Repeat a process while a condition is True.

num = 0
while num < 10:
    num = num + 1
    print(num)
In [118]:
num = 0
In [120]:
num = 0

while num < 10:
    num = num + 1
    print(num)
1
2
3
4
5
6
7
8
9
10

Imports¶

There are thousands of libraries (aka packages aka modules) that you can load. Some come with your standard Python installation, while others you can easily install into your Python environment.

Let's import a module:

import time
In [116]:
import time

Modules have lots of sub-modules (ahem... classes) that you can access:

time.time()
In [138]:
time.asctime()
Out[138]:
'Thu Aug  1 15:36:00 2024'

You can also import only one class of a module like this:

from time import asctime
In [140]:
from time import asctime
In [142]:
asctime()
Out[142]:
'Thu Aug  1 15:38:47 2024'

Challenge! Incorporate time.sleep() into our while loop to to count to ten in 10 seconds exactly:

In [146]:
num = 0

while num < 10:
    time.sleep(1)
    num += 1
    print(num)
    
1
2
3
4
5
6
7
8
9
10
In [ ]: