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')
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'
my_var = 'hello world'
my_var
my_var
'hello world'
print(my_var)
print(my_var)
hello world
If you don't like it, just reassign it:
my_var = 'whatever!'
my_var = 'whatever!'
String concatenation:
To put to string sequences together, use a plus sign +
print('Hello World' + 'My name is Screwball')
print(my_var + ', Screwball!')
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)
type(my_var)
str
That's a string. Strings are declared using single or double quotes (pretty much interchangeable).
my_var2 = 1
print(type(my_var2))
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()
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
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."
my_var + ", it's me, Phil."
"hello world, it's me, Phil."
my_var2 + 5
my_var2 + 5
6
Operators:¶
Arithmetic pretty much behave as you would think:
+
, -
, *
, /
, as well as **
exponential, %
modulus, //
floor.
Comparison
==
equal, !=
not equal, >
, >=
, <
, <=
Logical
and
, or
, not
var1 = 1
var2 = 'Chainsaw'
var1 == 1 and var2 == 'screwdriver'
False
Bonus: +=
is very useful.
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
var1 = 2
if var1 > 1:
print('yes')
elif var1 < 3:
print('yes')
else:
print('no')
yes
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')
new_list = []
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]
my_list[0]
'a'
Now try on a string variable:
my_var[0]
my_var[3]
my_var[8]
my_var[-1]
print(my_var)
my_var[8]
hello world
'r'
Index slicing:
my_var[0:3]
First position is start, second position is one after you want it to stop...
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)
my_nums = [1,2,3,4,5]
for n in my_nums:
print(n)
1 2 3 4 5
for n in my_nums:
# try some stuff!
print(n)
2 4 6 8 10
my_nums
[1, 2, 3, 4, 5]
range(len(my_nums))
range(0, 5)
for i in range(len(my_nums)):
print(i, my_nums[i])
0 1 1 2 2 3 3 4 4 5
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
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)
num = 0
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
import time
Modules have lots of sub-modules (ahem... classes) that you can access:
time.time()
time.asctime()
'Thu Aug 1 15:36:00 2024'
You can also import only one class of a module like this:
from time import asctime
from time import asctime
asctime()
'Thu Aug 1 15:38:47 2024'
Challenge! Incorporate time.sleep()
into our while
loop to to count to ten in 10 seconds exactly:
num = 0
while num < 10:
time.sleep(1)
num += 1
print(num)
1 2 3 4 5 6 7 8 9 10