Worksheets to help with learning coding concepts through repetition
You need to ctrl + p these babies out! Click on the text bubbles for the file
for range() len()
The .count() function will count how many times a certain value appears within a string.
.count()
sentence = input("Enter your sentence: ") e_count = sentence.count("e") print("There are", e_count, "e's!")
Enter your sentence: Hello there
There are 3 e's!
There are some golden rules when assigning
print
=
==
score = 0 name = "codefez"
if you assign a value to a variable name that already exists, you will simply re-assign the original variable a new value. This will result in losing the value that was originally held.
score = 0 print(score) score = 1 print(score)
0
1
Assigning variables can take up several lines! We can reduce the amount of required lines by assigning multiple variables on one line.
name, age, wears_glasses = "Joshua", 23, True print(name, age, wears_glasses)
Joshua 23 True
print() is a Python function for displaying text on the screen. Anything between the parenthesis is printed on the screen. However! Python can only handle one datatype at a time. (see casting or f-strings 1 for more info) You can print any datatype.
print()
print("Hello world!") print(2+2) # calculates a result!
Hello World! 4
Python can only handle one type of data at a time. Casting must be used in order to combine a second datatype. str() converts data into a string datatype int() converts data into a integer datatype float() converts data into a real/float datatype
str()
int()
float()
data_a = "Jessica" data_b = 35 print(data_a + " is " + str(data_b) + " years old")
Jessica is 35 years old
a for loop allows us to iterate a list of instructions for a specified number of times.
for
for i in range(3): print("hi")
hi hi hi
The i represents a local variable. Imagine that the i stands for iteration.
i
The i can be replaced by another name such as x or word or name.
x
word
name
The only rule here is to not name the local variable with a variable already used in your code or one that is a reservered word such as print or for.
for number in range(3): print(number)
0 1 2
The len() evaluates how big an object is.
len()
In this case of a string, this is how many characters.
text = "fez" len_of_text = len(text) print(len_of_text)
3
In the case of a list, it is how many elements there are in the list.
myList = ["fez", "code"] len_of_list = len(myList) print(len_of_list)
2
range()
The range() function is often used in a for loop. It specifies between which number of times the for instructions should repeat.
for i in range(3): print(i)
The range() function can also be given arguments specifying the number to start and end the range count.
for i in range(5,8): print(i)
5 6 7
The input() function can also be used to collect user responses as either integers or numbers with decimals.
input()
once the input is collected from the user, it is then cast into either a integer or a float (a number with decimals).
# This is an input for whole number (integer) age = int(input("Enter your age")) # This is an input for a floating point # number (with decimals) shoe_size = float(input("Enter your shoe size"))
Enter your age
14
Enter your shoe size
8.5
The input() function pauses when executing the line of code for the user to enter an input.
The input must be stored in a variable.
age = input("How old are you?\n>")
How old are you?
" "
The in operator checks if a character from a string or an element is in a list.
in
items = ["carrot","tomato","lettuce"] if "tomato" in items: print("List includes fruit") else: print("No fruit in list")
List includes fruit
The not in operators checks if a character from a string or an element is NOT in a list.
not in
items = ["carrot","tomato","lettuce"] if "tomato" not in items: print("No fruit in list") else: print("fruit in list")
fruit in list
The if function selects code for execution if a condition is met. If it is not met, the instruction nested under the else block is executed.
if
x = 10 if x > 5: print("x is greater than 5") else: print("x is less than or equal to 5")
x is greater than 5
The elif operand will execute the block of code if a given condition is met and doesn't meet the first condition.
elif
x = 2 if x > 5: print("x is greater than 5") elif x > 2: print("x is greater than or equal to 2") else: print("x is less than 2")
x is greater than or equal to 2
Ternary operators allow you to execute an if/else statement on one line.
x = int(input(" ")) print("x is equal to 4.") if x==4 else print("x is not equal to 4")
The # symbol creates a line that is ignored by Python. This is called a comment and can be used to describe the purpose of a block of code for clarity later.
#
# The line below asks for a user's age age = int(input("What's your age?"))
What's your age?
Multiple comment lines can also be achieved by using either 3 single or 3 double quotes
"""The line below asks for a user's age """ age = int(input("What's your age?")) '''The line above asks for a user's age '''
The lower() function converts all alphanumeric characters into lowercase
lower()
name = "CodeFez" print(name.lower())
codefez
The upper() function converts all alphanumeric characters into uppercase
upper()
name = "CodeFez" print(name.upper())
CODEFEZ
The while loop keeps running until a certain condition is met. You can replace the printing and incrementing with any code you want.
while
# The counter can help escape a loop counter = 1 while counter <= 5: print(counter) # Increment the counter counter += 1
1 2 3 4 5
The open() function will take a filepath as an argument to open a file. There are 2 methods to opening a file. Both methods will assign the open file to a variable. Notice the 2 examples below have 2 arguments. The filename and then the access mode.
open()
# The open file is assigned to a variable file = open("filename.txt", "r") # Opened files should also be closed. file.close()
""" with this method, there is no need to close the file. """ with open("filename.txt", "r") as file: # add instructions here
Files should be opened with an access mode.
The read() function reads the contents of an opened file. The example is set up as if the file is called names.txt with 3 names.
read()
file = open("names.txt", "r") data = file.readlines() file.close() print(data)
['Alice\n', 'Barbara\n', 'Chelsea']
file = open("names.txt", "r") data = file.readlines() file.close() print(data) for name in range(0, len(data)): data[name] = data[name].rstrip("\n") print(data)
['Alice', 'Barbara', 'Chelsea']
The random.randint(x,y) function will generate a random number from x to y.
random.randint(x,y)
import random x=random.randint(3,7) print(x) print("This could be 3, 4, 5, 6 or 7.")
6
This could be 3, 4, 5, 6 or 7.
The write() function writes a line to a file.
write()
Method 1
with open("filename.txt", "a") as file: content = "A line of text.\n" file.write(content)
file = open("filename.txt", "a") content = "A line of text.\n" file.write(content) file.close()
The quit() function will end the program.
quit()
print("Hello") quit() print("world")
Hello
The index() method will find the position of the first occurance of an item in a list. Sometimes it's easier to find the position using a for loop and not the index method. See 2nd example.
index()
First Example
items = ["apple", "banana", "kiwi"] pos = items.index("banana") print(f"position of banana is {pos}.")
position of banana is 1.
Second Example
items = ["apple", "banana", "kiwi"] target = "banana" for pos in range(0, len(items)): if target == fruit[pos]: print(f"position of {target} is {pos}.")
The split() method will seperate items in a string.
split()
string = "Superman,Clark Kent,can fly,super strength" print(string) name,alias,power1,power2 = split(",") print(f"{name} is also known as {alias} and has the powers {power1} and {power2}.")
Superman,Clark Kent,can fly,super strength
Superman is also known as Clark Kent and has the powers can fly and super strength.
The append() method is used to add data to a list.
append()
items = ["carrot","tomato"] items.append("lettuce") print(items)
["carrot","tomato","lettuce"]
The pop() method will remove an item from a list. By default with no argument, it will remove the last time in the list. With an argument, it will remove the index item of the number given.
pop()
Without an argument
veg = ["carrot","tomato","lettuce"] veg.pop() print(veg)
["carrot","tomato"]
With an argument
veg = ["carrot","tomato","lettuce"] veg.pop(1) print(veg)
["carrot","lettuce"]
Rounding is used to display a numerical value to it's nearest integer. For example 5.3 can be rounded to 5 or 3.333333333333 can be rounded to 3.33 by default the round() method will round to 2 decimal places unless specified.
# Rounding to the nearest integer with no decimal places. print(round(10/3,0)) # we can also use the int function to remove the decimal point. print(int(round(10/3,0))) # Rounding to 2 decimal places print(round(10/3,2))
3.0
3.33
Python uses operators to perform mathematical operations.
print(2+2) # Addition print(3-2) # Subtraction print(2*2) # Multiplication print(5+2) # Division
4
2.5
To perform integer and remainder divisions, Python uses the div (//) and mod (%) operators.
//
%
# integer division (//) only returns a whole number print(5//2) # Remainder division (%) returns the remainder of a division print(5%2) # 2 remainders of 0.5 --> so 1 in total print(4%2) # --> 0 print(11%3) # --> 2
f-strings are a simple way to concatenate strings, integers and other datatypes into a string of text. Python automatically formats the datatype to string. Curley brackets are used to interpolate variables into a string.
name = "Alice" age = 17 print(f"{name} was just {age} years old")
Alice was just 17 years old
To be able to use sleep you need to from time import sleep. Then, using the function sleep(1), you can specify the amount of seconds within the parentheses ().
from time import sleep
sleep(1)
()
from time import sleep sleep(1) # Waits 1 seconds print("Hello") sleep(1) # Waits 1 seconds print("World")
World
The tuple data structure is an immutable list which means they cannot be changed while the program is running.
tuple
animals = ("cat", "dog", "mouse") # defining the tuple print(animals[0]) # prints the first item in the tuple from 0 animals.append("rabbit")
cat
AttributeError: 'tuple' object has no attribute 'append'
The input() function can also be used a decimal integer. For example, inputting a number as a float and then printing it will print it as a decimal value.
x = float(input("Enter a number")) print(x)
Enter a number 51 51.0
The islower() and isupper() string methods returns a True or False result if all charcaters in a string are either all lower or uppercase.
islower
isupper
True
False
string1 = "HELLO WORLD" string2 = "hello world" print(string1.isupper()) # Output: True print(string2.isupper()) # Output: False
True > False
The sort() function will sort a list of numbers from an array in ascending order.
sort()
numbers = [4, 2, 9, 1] numbers.sort() print(numbers)
[1, 2, 4, 9]
To clear the screen, you first need to import os then using os.system('clear') you will successfully clear it. For demonstration purposes, I have also used a sleep function which you can find in the cheatsheet also.
import os
os.system('clear')
import os from time import sleep print("Hello World") # Prints 'Hello World' sleep(1) # Waits for 1 second os.system('clear') # Clears screen
Hello World
The replace() function can be used to replace all occurrences of a specific substring within a string with a new substring.
replace()
from time import sleep text = "Hello, World!" print(text) # Output: Hello World text.replace("World", "Hello") print(text) # Output: World Hello
Hello Hello
Lists are used to store multiple items in a single variable. Using square brackets[ ] with an assigned variable name allows us to create a list. Lists can contain all datatypes such as integer, boolean, string and float.
[ ]
mixed_list = [True, False, 'Hello', 'World', 1, 34, 2.4, 4.5] print(mixed_list)
[True, False, 'Hello', 'World', 1, 34, 2.4, 4.5]
This modal is lost. check back later to see if we've found it.
The isdigit() string method will check if a variable is numeric and return a True or False result.
isdigit()
var1 = "1" var2 = "one" print(var1.isdigit()) print(var2.isdigit())
The isalpha() string method will check if a variable is alphanumeric and return a True or False result.
isalpha()
var1 = "1" var2 = "one" print(var1.isalpha()) print(var2.isalpha())
The choice function chooses a random item from a list
choice
from random import choice numbers_list = [1, 2, 3, 4] print(choice(list))
A try-except block is used to handle exceptions, which are errors that occur during the execution of a program. This block lets you manage these errors gracefully without crashing your program.
The try block contains the code that might raise an exception. The except block contains the code to execute if an error occurs.
try
except
try: with open("users.txt", 'r') as file: content = file.read() # more code to do something with the file here except FileNotFoundError: print(f"Error: The file '{users.txt}' was not found.")
Another example
try: age = int(input("Enter your age: ")) print(f"Great! You are {age} years old.") except ValueError: print("Error: Please enter a valid number.")
Enter your age:
E3
Error: Please enter a valid number.
The random.sample function will generate x random values from list.
random.sample
import random myList=[1,2,3,4,5,6,7,8,9,10] x=random.sample(myList,3) print(x) print("These will be 3 numbers from 1-10, unordered.")
[9,3,7]
These will be 3 numbers from 1-10.
The def keyword is used to define a function or procedure. A procedure performs a task but doesn’t return a value. Instead, it might print to the screen or modify a file.
def
return
def print_receipt(items, prices): print("Receipt:") for i in range(0, len(items)): print(f"{items[i]}: £{prices[i]}") print("Thank you for shopping.\nPlease come again!") items = ["Apples", "Bananas", "Cherries"] prices = [2.5, 1.2, 3.0] print_receipt(items, prices)
Receipt: Apples: £2.5 Bananas: £1.2 Cherries: £3.0 Thank you for shopping Please come again!
The def keyword is used to define a function or procedure. A function typically returns a value after performing a task. This functions takes a list of item prices and returns the total_price after working out the tax to be added.
total_price
def calculate_total_price(prices, tax_rate): total = sum(prices) * (1 + tax_rate) return total prices = [10.0, 20.0, 30.0] # List of item prices tax_rate = 0.2 total_price = calculate_total_price(prices, tax_rate) print(f"The total price is: £{total_price:.2f}")
The total price is: £72.00
The math.floor function will round a decimal number down to the nearest integer.
math.floor
import math print(math.floor(1.7)) print(math.floor(0.3))
The math.ceil function will round a decimal number up to the nearest integer.
math.ceil
import math print(math.ceil(1.7)) print(math.ceil(0.3))
Lists are used to store multiple items in a single variable. A 2D array is when each item in a list is another list which contains it's own items.
grid = [ ["x","o","x"], ["o","x","o"], ["x","o","x"] ] for r in grid: print(r)
['x', 'o', 'x'] ['o', 'x', 'o'] ['x', 'o', 'x']
We can use while loops as a form of input validation. For example, we can provide a list of possible answers that the user must use from in order to progress further.
possible_answers = ["y","yes","n","no"] answer = "" print("Do you wear a fez?") while answer.lower() not in possible_answers: answer = input("Enter a valid answer (Y,Yes,N,No)\n") print("answer acknowledged")
Do you wear a fez? nope Enter a valid answer (Y,Yes,N,No) yup Enter a valid answer (Y,Yes,N,No) Y answer acknowledged