000 Python Basics Reference
000 Python Basics Reference
md 1/7/2020
print("Hello world!")
val = 12
print( f"With leading spaces to make it 4 characters wide is {val:4}" ) # prints ' 12'
print( f"With leading zeros to make it 4 characters wide is {val:04}" ) # prints '0012'
val = 3.14
print( f"To 2 decimal places is {val:.2f}" ) # prints '3.14'
print( f"To 5 decimal places is {val:.5f}" ) # prints '3.14000'
print( f"With spaces to make it 8 characters wide with 3 decimal places is {val:8.3f}" )
print( f"With zeros to make it 8 characters wide with 3 decimal places is {val:08.3f}" )
1 / 12
000-python-basics-reference.md 1/7/2020
Numbers
Python has two types of numbers: integers and floats. Integers are "whole numbers" without decimals,
floats are the name given to numbers that contain decimals.
To get the result of a mathematical calculation, put the equation on the right of an equal sign, and the
variable you wish the answer saved in on the left of the equal sign.
Arithmetic
a = 100
b = 6
c = a + b # addition ... c == 106
c = a - b # subtraction ... c == 94
c = a * b # multiplication ... c == 400
c = a / b # division ... c == 16.66667
c = a // b # integer division ... c == 16 (how many times does 6 go into 100)
c = a % b # modulus remainder ... c == 4 (ie: remainder of 100 divided by 6)
c = a ** b # exponent ... c == 1000000000000 (ie: 10^6)
import math # add this line to the top of your program for the math functions to work
Example: How long is the hypotenuse of a triangle if the adjacent side is 20, and the angle is 45
degrees?
import math
adjacent = 20.0
angle = 45.0
hypotenuse = adjacent / math.cos( math.radians( angle ))
print(hypotenuse) # prints 28.284...
Converting
2 / 12
000-python-basics-reference.md 1/7/2020
Strings
Assign a text string a value
mytext = "Hello"
Searching strings
Get substrings
String positions start from 0. That is, the first letter is position 0, the second letter is position 1
and so forth.
When asking for a range of characters, Python will give you a substring that includes the starting
position number, but not including the end position number.
Changing strings
3 / 12
000-python-basics-reference.md 1/7/2020
If statements
An "if" statement defines code that will run if the answer to a question is True. To ask a question,
have Python to compare two or more values to see if they obey a rule. Examples of comparisions we
can ask...
We can also join multiple queries together using the and or or key words such as...
Remember:
Use a double equal sign to compare two values! A single equal is used to set the value rather
than ask if they are a match.
End your "question" with a colon and indent the code to run when the comparison is True.
The if statement will keep asking questions of the various elif until it finds one that is True.
After one item is True, it will skip the rest of the options available.
4 / 12
000-python-basics-reference.md 1/7/2020
While loops
The while loop works very similar to the if statement. Any question you can ask of an if statement
can be used in a while loop. The difference being that so long as something is True, it will keep
running the same indented section of code. An example:
Another example...
import random
secret = random.randint(1,99) # generate a random number between 1 and 99
guess = int(input("Guess my secret number between 1 and 99: "))
while guess != secret:
if guess > secret:
guess = int(input("Too high. Guess again: "))
elif guess < secret:
guess = int(input("Too low. Guess again: "))
print("Correct!")
For loops
You can also use a for-loop when you know the number of iterations you wish to loop in advance.
You can also specify a starting number other than zero. For instance
You can even specify that it counts downwards, or using an interval different to one by specifying a
third parameter to the range() function.
5 / 12
000-python-basics-reference.md 1/7/2020
Example lists:
Lists have many of the same features of strings (which is really just a list of characters) to query them
and get sub-parts from.
6 / 12
000-python-basics-reference.md 1/7/2020
Defining functions
A function allows us to define a block of code as our own Python command to use. One useful
purpose of this is it allows you to reuse code without having to continually copy-and-paste it. This then
means you can also modify/improve it by only editing it once. Very useful.
Use the def keyword to define a new function, provide the name you wish to assign, and then
parenthesis and a colon. Indent the code to include in the function and then end the intendation when
the function specific code ends.
# Create a function...
def a_useless_function():
print("This is a fairly useless function")
You can provide parameters to functions so their behaviour can be customised each time. A simple
example...
7 / 12
000-python-basics-reference.md 1/7/2020
Files
Read entire file as a string
r for reading
w for writing (erasing it if it exist)
a for appending (add to file without erasing previous content)
Remember
The with statement will close the file when you unindent
.splitlines() behaves like .split("\n")
For greater predictability, cast everything to strings before writing to files
8 / 12
000-python-basics-reference.md 1/7/2020
Exceptions
Generic try/except
Warning the generic exception catch is bad practice and hides bugs. Any unintentional error in
your code (such as a mis-spelling) could cause an exception that results in hours of frustration to
diagnose.
try:
denominator = int(input("Please enter a number: "))
result = 100 / denominator
print(f"100 divided by {denominator} is {result}")
except:
print("I can't do that!")
try:
denominator = int(input("Please enter a number: "))
result = 100 / denominator
print(f"100 divided by {denominator} is {result}")
except ValueError:
print("That wasn't a number")
except ZeroDivisionError:
print("I can't divide by zero")
x = 10
if x > 5:
raise ValueError("Not allowed to have a number greater than 5")
9 / 12
000-python-basics-reference.md 1/7/2020
10 / 12
000-python-basics-reference.md 1/7/2020
11 / 12
000-python-basics-reference.md 1/7/2020
Dictionaries
Convert a dictionary/list structure into a JSON string (useful for saving to a file)
import json
# Save it to a file
with open("person.txt", "w") as f:
f.write( json_text )
Convert a JSON string into a dictionary/list structure (usefil for loading from a file)
import json
12 / 12