Chapter 1: Python Basics
Python data types:
● String: number of characters enclosed by quotation marks → ‘tomato’
● Integer: a number without decimals → 4
● Floats: a number which has decimals → 5.5
● None: absence of value
→ p rint(type(x)) → shows the datatype of the variable
Rules using data types together:
✓ Integer * float → 5 * 5.5
✓ String * integer → 2*tomato = tomatotomato
⌧ String + integer → ‘tomato’ + 4 = syntax error
⌧ String * float → 5.5 * tomato = syntax error
Variable: containers for storing data
x = ‘tomato’
print(x)
tomato
→ must start with a letter or underscore ( _ ). Can only contain A-z, 0-9, and _.
String methods:
x.title() → avatar becomes Avatar
x.upper() → avatar becomes AVATAR
x.lower () → AVATAR becomes avatar
x.islower () (or .isupper etc.) → True or False
x.find('a') → Finding the first occurance of a value inside a string → 0
Integer methods:
● for i in range(4): print(i)
= Printing each integer in a range of 0 - 4
0
1
2
3
Converting data types: x = int(age), x = str(age), x = float(age)
,Chapter 2: Flow Control
Boolean: only 2 values: True or False
Operators:
● Not: not True = False, not False = True.
● And: True and True = True, False and True = False, False and False = False
● Or: True or True = True, True or False = True, False or False = False
As a convention it is accepted that True=1, so True+2 = 3
Comparison operators (output True/False):
● == → equal to
● < → less than
● > → greater than
● != → not equal to
● <= → less than or equal to
● >= → greater than or equal to
Flow Control Statements
If .. Then Statements
if 200 >33:
print("b is greater than a")
else:
print("b is not greater than a")
Elif Statements
if 200 >33:
print("b is greater than a")
elif 200 = 33:
print("b is not a")
else:
print("b is not greater than a")
While Loops
Execute a set of statements as long as a condition is true. E.g. ‘Print number 1 till 5’
i = 1
while i < 6:
print(i)
i += 1
, For Loops
A for loop is used for iterating over a sequence. E.g. ‘Print each fruit in a fruit list’:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Range()
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
for i in range(0, 10, 2):
print(i
Break Loops
Break (while loop). E.g. ‘Print 1 till 3’
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Break (for loop). E.g. ‘Print apple till banana’.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Continue Loops
Continue (while loop). E.g. ‘Print 1, 2, 4, 5, 6’ (3 is missing from the loop)
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)