Make sure you have followed all the relevant instructions for your computer here
Python is a program on your computer like many others, the program takes instructions in the form of code and executes the instructions to the best of the program's ability.
Some programming languages like C++ turn code into binary, ones and zeroes, which is called "compiling". But Python works in a different way. When you write code in Python, this is an input into the Python program, which has what is called an "interpreter" to turn your code into "machine code". You might hear Python being called an "Interpreted language" because of this.
The Python interpreter, or "shell", uses REPL logic. REPL stands for "Read/Evaluate/Print". You write code, the program reads the code, checks that everything is correct according to the specific syntax of Python and then prints and executes the commands.
You interact with the Python program directly when you execute, or "run", your code. You can do this with 1 line or 10,000.
To run Python in Jupyter Notebook, click on the block you want to run and press the "Run Cell" button (Looks like ">|") or press Shift+Enter. You can run any block with an In[ ]: to the left of it, these blocks are all for code.
In [ ]:
# Print a "Hello World!"
A variable is a reserved block of memory for the program to keep some information. This can be a number, a string (programming word for any words or characters) or many other types of "object". In Python, everything is a "object" and we will go onto more of what this means next week.
In Python you don't have to declare what kind of variable anything is, you just write the variable and the program works the rest out.
In [ ]:
# We use variables to assign easy names to any object
pi = 3.14159265359793238462643383279502884197169399375105
# pi is the VARIABLE NAME
# 3.14159... is the VARIABLE VALUE
# = is the "assignment operator" telling Python what the name "pi" is
# Is the name or the value of this variable easier to remember?
In [ ]:
# You can also inspect any object using id()
# id(pi)
# And use type() to find out what kind of Object the variable is
# type(pi)
Kinds of variable
In [ ]:
# Integer
a = 1
print(type(a))
print()
# Float (Integer or Decimal values)
b = 1.200
print(type(b))
print()
# String
c = 'Python'
print(type(c))
print()
# Complex (Real and Imaginary numbers, Python uses the j notation from EE)
d = 1+1j
print(type(d))
In [ ]:
# TODO
# Declare your own variable of any type and check the type
# END TODO
Multiple Assignments
In [ ]:
# All 3 variables have value 100
variable1 = variable2 = variable3 = 100
# Now you can check that variable1 is the same as variable2 using '=='
print(variable1 == variable2)
In [ ]:
# TODO
# Use the rules of multiple assignment to create multiple objects
# Now check they are equal
# END TODO
Case and Disallowed words
In [ ]:
# Python is case sensitive so
pi = 3.141
#and
PI = "Pumpkin"
# are completely different objects, you can see this when you print them
print(pi)
print(PI)
In [ ]:
# Some words in Python are reserved for program logic and cannot be used for variables
# TODO - Comment out these lines one by one and see if this block will still run
#if = 1.00
#elif = 'hello'
#and = 0.0001
# END TODO
A full list of reserved words in Python can be found here
In order to be able to understand and write your own Python, you can't just declare variables, you have to be able to manipulate the data you have to get what you want out. Maths and logic operators are the fundamentals of doing this.
Arithmetic and mathematical operators in Python
In [107]:
# First we declare some variables to play with
a = 100
b = 10
c = 99
d = 32
e = 2
# Addition
add_result = a + b
print("Addition")
print(add_result)
print()
# Subtraction
sub_result = a - b
print("Subtraction")
print(sub_result)
print()
# Multiplication
mult_result = c*d
print("Multiplication")
print(mult_result)
print()
# True Division, returns value with decimals
tdiv_result = c/b
print("True Division")
print(tdiv_result)
print()
# Floor Division, returns result with decimal value removed
rdiv_result = c//b
print("Floor Division")
print(rdiv_result)
print()
# Modulus (Remainder)
mod_result = a%c
print("Modulus Operator")
print(mod_result)
print()
# Exponent
exp_result = c**e
print("Exponential Operator")
print(exp_result)
print()
# Increment
e = e+1 # e is now 3
# A shorthand for this is
e+=1 #e is now 4
# You can do the same with minus (or decrement)
e-=1 # e is 3 again
# You can perform multiple operations on 1 line using brackets
poly_result = ((a+b)-c)//2
print("Multiple operations")
print(poly_result)
In [ ]:
# TODO - Declare two different integer variables and perform each Math operator on them both
# END TODO
Logic operators in Python, each logic operator statement returns True or False
In [ ]:
# We declare some variables to use
a = 100
b = 101
c = "hello"
d = "goodbye"
# Python also has the type Boolean for standard true and false
t = True
f = False
# Use == to evaluate if two objects have the same value
eq_result = a == b
print('TESTING EQUALITY')
print(eq_result)
print()
# Use != to test if two items are not equal
neq_result = a != b
print('TESTING INEQUALITY')
print(neq_result)
# Use > or < to test greater than or less than
gt_result = a > b
lt_result = a < b
print('TESTING > and <')
print(gt_result)
print(lt_result)
print()
# Use >= to test greater or equal to and <= to test less or equal
ge_result = a >= 100
le_result = b <= 200
print('TESTING >= and <=')
print(ge_result)
print(le_result)
print()
# You can chain logical operators together
chain_result = 100 < b <= 101
print('TESTING CHAINING')
print(chain_result)
# CLASS QUESTION
# Is this true or false?
# a == (b-(b%a))
In [ ]:
# TODO - 3 variables have been declared below,
# Use the questions asked to build logic statements and print the result
var1 = 100
var2 = 200
var3 = True
# Question - Is the difference between var2 and var1 equal to var1?
# Question - Is var1 greater than var2?
# Question - Is the answer to the previous question equal to var3?
# Question - Evaluate a chained logic operator by picking a number
# and testing if it is between var1 and var2
# END TODO
Logical operators
In [ ]:
t = True
f = False
t2 = 1
f2 = 0
num = 1000
# All non zero numbers in Python are equivalent to "True"
# See for yourself by uncommenting the next 2 lines
#print(bool(1))
#print(bool(0))
# You can AND variables together (only True if both True)
and_result1 = t and f
and_result2 = t and t2
print('AND')
print('t and f')
print(and_result1)
print('t and t2')
print(and_result2)
print()
# You can OR variables together (True if one is true)
or_result1 = t or f
or_result2 = f or f2
print('OR')
print('t or f')
print(or_result1)
print('f or f2')
print(or_result2)
print()
# You can negate any Boolean value with not
print("not")
print(not t)
print(not f2)
print()
# The "is" operator is similar to the == operator but works differently
print('is')
print('t is true')
print(t is True)
print('t2 is 1')
print(t2 is 1)
print('num is 1000')
print(num is 1000)
print('This is False because \"a is b\" is the same as \"id(a)==id(b)\"')
print(id(num))
print(id(1000))
print('Moral of the story - Always use == not \"is\" unless you know what you are doing!')
print()
# One last one - Membership
# You can test if a smaller string is inside a bigger string with "is"
s1 = "We are here to Python"
s2 = "Python"
print("Is s2 inside s1?")
print(s2 in s1)
#print("Does this work on integers?")
#print(1 in 100)
You will use both the Mathematical and Logical Operators extensively in your coding career, go over these ideas again until you are confident with them. The next section can be tricky if you are not comfortable with True and False.
An if
statement is type of logic statement which will cause a block of code to run ONLY if the statement is evaluated to True. An if statement is evaluated once and never returned to unless it is inside a loop
In [ ]:
# Test variable
boot = 'snake'
# The indented block of code will only run if the logic between the "if" and the colon is True
if 'snake' in boot:
print('There\'s a snake in my boot!')
if 'hippo' in boot:
print('Why is there a Hippo in my boot?')
while
is used like if
but for looping until something is False
. In this way you can repeat an action until a condition means you no longer need to repeat it
In [ ]:
x = 1
while x <= 5:
# This block executes when the while loop condition is True
print(x)
print('x is less or equal to 5')
x += 1
# This block only executes when the while loop condition is False
print(x)
print('x is too big for the while loop now')
for
is like while
and will loop until the for
condition is True
. for
loops are used to "iterate" over ranges of objects
In [ ]:
# You can use for to loop over every character in a string
word = 'London'
for letter in word:
print(letter)
print()
# You can also use for to loop over data structures such as lists (more on this later)
list1 = [1,2,3,4,5]
for number in list1:
print(number)
print()
# Finally you can use range() to create the same kind of number range as list1 easily
# The format of range is range(a,b) which starts on a and ends 1 before b
for number in range(1,5):
print(number)
Finally, we can return to the if
statement we learnt to look at what else we can do with it.
The elif
(shorthand for "else if") is a way to evaluate something else if the first if
was False
with another logic condition. The else
statement is a way to always make something else happen if the if
statement was False
.
In [ ]:
# We can use elif and else in our previous example
boot = 'snake'
if 'hippo' in boot: # First test if 'hippo' in 'boot'
print('Why is there a Hippo in my boot?')
elif 'snake' in boot: # If no 'hippo', test for 'snake'
print('No Hippo, but there is a snake!')
else: # Only happens if all ifs and elifs were False
print('No snakes or hippos in sight')
In [ ]:
# TODO - Final task
#Print each element of the fibonacci list (Hint: use for)
fib = [0,1,1,2,3,5,8,13,21]
for #SOMETHING in SOMETHING:
print(#SOMETHING)
print
# Use if to complete the logic statement
number_of_bananas = 5
if #SOMETHING IS TRUE:
print("We have bananas!")
else:
print("We have run out of bananas :(")
# Now change the number_of_bananas to 0 and see what happens
# Finish the while statement to print a message about whether it is legal to drive in the UK
# You must be older than 16 to hold a full driving licence in the UK
age = 22
while #SOMETHING IS TRUE:
print(age)
print('You are old enough to drive!')
age = age - 1
print(age)
print('You are too young to drive :(')
# END TODO
If you are interested in writing perfect looking Python, the developers of the language have what is called a "Style Guide" which you can read here