You are now adding new BitMon to the BitDex.
bitmon.txt file in append mode.
tips on how to complete the tasks.
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
2
1
0
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) # Waits 1 seconds
print("Hello")
sleep(1) # Waits 1 seconds
print("World")
Hello
World
The tuple data structure is an immutable list which means they cannot be changed while the program is running.
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.
string1 = "HELLO WORLD"
string2 = "hello world"
print(string1.isupper()) # Output: True
print(string2.isupper()) # Output: False
True
> False
As well as indexing individual characters in a string, you can also extract a substring by using slicing. Slicing allows you to specify a range of indices to extract a portion of the string.
Example 1
string = "Codefez"
print(f"{string[0:4]}")
Code
Example 2
string = "Codefez"
print(f"{string[4:7]}")
fez
The sort() function will sort a list of numbers from an array in ascending order.
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
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.
from time import sleep
text = "Hello, World!"
print(text) # Output: Hello World
text.replace("World", "Hello")
print(text) # Output: World Hello
Hello World
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.
My people are working on this!
The isdigit() string method will check if a variable is numeric and return a
True or False result.
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.
var1 = "1"
var2 = "one"
print(var1.isalpha())
print(var2.isalpha())
The choice function chooses a random item from a list
from random import choice
numbers_list = [1, 2, 3, 4]
print(choice(list))
3
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:
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.
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 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.
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.
import math
print(math.floor(1.7))
print(math.floor(0.3))
1
0
The math.ceil function will round a decimal number up to the nearest integer.
import math
print(math.ceil(1.7))
print(math.ceil(0.3))
2
1
This is an example of how we can write a custom function to colour our text in the Python console.
def coloured_text(colour, text):
cols = {
"black":"\033[30m",
"red":"\033[31m",
"green":"\033[32m",
"yellow":"\033[33m",
"blue":"\033[34m",
"magenta":"\033[35m",
"cyan":"\033[36m",
"white":"\033[37m",
"reset":"\033[0m",
}
col_code = cols.get(colour, cols["reset"])
return f"{col_code}{text}{cols['reset']}"
print(f"I am {coloured_text('blue', 'blue')}.")
print(coloured_text("red", "This text is red."))
I am blue.
This text is red.
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']
while
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
Escape codes let you represent special characters inside strings. The most common are \n (newline) and \t (tab).
# Newline example
print("Hello\nWorld")
# Tab example
print("Column1\tColumn2")
Hello World
Column1 Column2
Comparative operators compare values and return True or False. Common operators: >, <, ==, !=, >=, <=.
a = 5
b = 3
print(a > b) # True
print(a < b) # False
print(a == 5) # True
print(a != 4) # True
True
False
True
True
Python doesn't enforce constants, but by convention constants are named in UPPERCASE. Use them for values that shouldn't change.
PI = 3.14159
GRAVITY = 9.81
print(PI)
print(GRAVITY)
3.14159
9.81
List comprehensions provide a concise way to create lists from iterables. They are often shorter and faster than using loops.
# Squares of numbers 0-4
squares = [x*x for x in range(5)]
print(squares)
# Filtered comprehension
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
[0, 1, 4, 9, 16]
[0, 2, 4, 6, 8]
The timedelta object in Python is used to represent a duration or difference between two
dates or times. We can specify the duration in terms of days, seconds, microseconds, milliseconds, minutes, hours, and weeks.
It is commonly used for date and time arithmetic.
In the example below, you can see how long an operation takes to run by using the timedelta
object to calculate the difference between the start and end times.
import datetime
timestamp1 = datetime.datetime.now() # start time
# some code to run
for i in range(1000000):
pass
timestamp2 = datetime.datetime.now() # end time
duration = timestamp2 - timestamp1
print(f"Duration: {duration}")
Duration: 0:00:00.063358
This task took approximately 0.063 seconds to complete.