Python: Reference

A quick reference guide for the Python3 programming language

Print & input

Printing to terminal

print("Hello world!")

msg = "Hello world!"
print(msg)

greeting = "Hello "
name = "Mr Baumgarten
print(greeting+name)

Inputs

name = input("What is your name?")
print("Hello, "+name)

Print using string .format() substitution

title = "Mr"
name = "Baumgarten
print("Hello {} {}".format(title, familyName)

If you comma-seperate multiple variables for a print() function, you can modify how they are concatenated together with the sep="" and end="" parameters.

print("Hello","world!",sep="+") # will print "Hello+world!"
  • Use end="" to override the trailing linefeed character.

Numeric variables

Warning: Python is case-sensitive when it comes to variable names. Upper case "X" is treated as a different name to lower case "x". This is important to remember as one of the most common mistakes students make is changing the spelling of their variable names and wondering why it doesn't work.

Python will implicitly determine if a numeric variable should be an integer or float based on the contents of the value assigned.

i = 3     # Integer
f = 3.0   # Float

Numeric operations

print( 2 + 2 )       # Addition of integers
print( 1.5 + 2.25 )  # Addition of floats
print( 7 – 2 )       # Subtraction
print( 3 * 4 )       # Multiplication
print( 13 / 5 )	     # Floating point division
print( 13 // 5 )     # Integer division
print( 13 % 5 )      # Modulus (remainder)
print( 4 ** 2 ) 	   # Exponent (ie: 4 squared)

Comparison operations

a == b				# equal
a != b				# not equal
a > b				# greater than
a >= b				# greater than or equal to
a < b				# less than
a <= b				# less than or equal to
a == 0 and b == 0		# both are true
a == 0 or b == 0		# either is true

The following also exist for strings and lists

print( "h" in "hello" )   # True
print( "z" in "hello" )   # False
print( "z" not in "hello" )   # True

Casting/converting between datatypes

Converting a string to an integer

s = input("Type an integer:")
i = int(s)             ## i is an integer you can perform calculations on
print( 2 * i )

Converting a string to a float

s = input("Type a floating point number:")
f = float(s)           ## f is a float you can perform calculations on
print( 2 * f )

Converting a number to a string

a = 4
s = str(a)
print("Your number is " + s)

Example:

number_text = input("Type an integer:")
number = int( number_text )
answer = number * 2
answer_text = str( answer )
print("Double your number is: "+answer_text)

Finding the datatype

i = 123
type(i)      # Will print <type 'int'>

Checking the datatype

if type(i) is int:
   print("it is an integer")

If / elif / else

sister_age = 15
brother_age = 15
if sister_age > brother_age:
   print("Sister is older")
elif sister_age == brother_age:
   print("Ages are the same! They might be twins!")
else:
   print("Brother is older")

For loop over a range

for num in range(...):
   print(num)

where the range() command behaves as follows:

  • range(5) – will generate the sequence 0,1,2,3,4
  • range(3,10) – will generate the sequence 3,4,5,6,7,8,9
  • range(-4) – will generate an empty sequence (counting up from 0 to -4 results in nothing)
  • range(-4,0) – will generate the sequence -4,-3,-2,-1
  • range(0,10,2) – will generate the sequence 0,2,4,6,8
  • range(0,-4,-1) – will generate the sequence 0,-1,-2,-3

Strings

Declaring a string

s = "To infinity and beyond!"

Searching a string

name = "Luke Skywalker"
if " " is in name:
   space = name.index(" ")
   print( "The space appears at position:",space )

Length of a string

s = "To infinity and beyond!"
l = len(s)
print(l)		## 23

Get parts of a string

s = "To infinity and beyond!"
print( s[4:5] )	    # will print 'n'
print( s[3:11] )    # 'infinity' ... from 3 up to but not including 11
print( s[:5] )      # 'To in' ... from 0 up to but not including 5
print( s[5:] )      # 'finity and beyond!' ... from 5 to the end
print( s[-5:] )     # 'yond!' ... last 5 characters

Replacing parts of a string

s = "To infinity and beyond!"
print( s.replace(" ", "+") )   # To+infinity+and+beyond!

Counting occurances within a string

s = "To infinity and beyond!"
print( s.count("i") )		 ## 3

Changing case of text

s.lower()			## to infinity and beyond!
s.upper()			## TO INFINITY AND BEYOND!
s.title()			## To Infinity And Beyond!
s.swapcase()			## tO INFINITY AND BEYOND!

Query content of a string

if s.isnumeric():		## does it contain only numbers?
if s.isalpha():		## does it contain only letters?
if s.islower():		## is it all lowercase?
if s.isupper():		## is it all uppercase?
if s.istitle():		## is it all title case?
if s.isspace():		## is it all spaces?

Padding a string

s.ljust(30)		## "To infinity and beyond!       "
s.rjust(30)		## "       To infinity and beyond!"

While loops

print("I will count from 1 to 10")
num = 1
while num <= 10:
   print( num )
   num = num + 1
print("The end!")

Lists (arrays)

Declaring:

empty  = []
primes = [1,2,3,5,7,11,13,17,19,23,29]
days   = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]

Get / set elements

print( days[2] )			## Tuesday
days[2] = "Chewsday"		## Replaces Tuesday with Chewsday
days.append("Baumgarday")	## Adds an eighth day

Like strings, the square brackets can retrieve a subset of the list. All the different variations that work with strings will work with lists.

weekdays = days[ 1:6 ]
weekdays = days[ 1:-1 ]

Looping over a list method #1

for day in days:
   print( day )

Looping over a list method #2

for daynum in range(len(days)):
   print(days[1])

Other list functionality

print( len(days) )
print( min(primes) )
print( max(primes) )
print( days.index("Monday") )
print( days.count("Monday") )
print( "Sunday" in days )
print( "Sunday" not in days )

Converting a string to a list:

s = "Hello how are you?"
l = s.split(" ") 
print(l)

Convert a list of strings to a merged string:

daysAsString = ", ".join(days)
print(daysAsString)

List generator: A short cut method of creating a simple list

newlist = [expression for variable in sequence]

For example, instead of this…

nums = []
for i in range(5):
   nums.append( i*10 )

You can use this…

nums = [i*10 for i in range(5)]

Read/write text files

def read_file(filename):
    data = []
    with open(filename, "r") as f:
        for line in f:
            data.append(line.replace("\n", ""))
    return data

def write_file(filename, data):
    if isinstance(data, list):
        with open(filename, "w") as w:
            for datum in data:
                w.write(datum + "\n")
    elif isinstance(data, str):
        with open(filename, "w") as w:
            w.write(data + "\n")
    else:
        raise NameError("Unknown data format passed to write_file")


starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]

write_file("starwars.txt", starwars)

from_file = read_file("starwars.txt")

for item in from_file:
    print(item)

Dictionaries

Create an empty dictionary (see adding below to add items to an empty dictionary)

person = { }

Creating a dictionary with initial data

person = {"givenName" : "Paul", "familyName" : "Baumgarten"}

Getting elements from the dictionary

print( person["givenName"] )
print( person["familyName"] )

Adding / modifying elements in the dictionary

person["email"] = "pbaumgarten@isl.ch"
person["website"] = "https://pbaumgarten.com"

Remove an element from the dictionary

del person["website"]

Loop through all the elements of the dictionary

for key,val in person.items():
  print("field "+key+" has value "+val)

JSON

Reading

import json

with open("countries.json", "r") as f:
    data = json.load(f)
    for item in data:
        print(item)

Writing

import json

with open("countries.json", "w") as f:
    json.dump(f, data)

Functions

Simple functions (in the same python file)

def area_of_circle(radius):
    PI = 3.1415
    area = 2 * PI * radius ** 2
    return area

def circumference_of_circle(radius):
    PI = 3.1415
    circ = 2 * PI * radius
    return circ

r = int(input("What is the radius of your circle?"))
answer = area_of_circle(r)
print("The area of your circle is: ",answer)
answer = circumference_of_circle(r)
print("The circumference of your circle is: ",answer)

Using a function from a seperate file:

For the file, cirles.py:

def area_of_circle(radius):
    PI = 3.1415
    area = 2 * PI * radius ** 2
    return area

def circumference_of_circle(radius):
    PI = 3.1415
    circ = 2 * PI * radius
    return circ

There are two ways you can import.

Method 1:

from circles import *
r = int(input("What is the radius of your circle?"))
answer = area_of_circle(r)
print("The area of your circle is: ",answer)
answer = circumference_of_circle(r)
print("The circumference of your circle is: ",answer)

Method 2:

import circles
r = int(input("What is the radius of your circle?"))
answer = circles.area_of_circle(r)
print("The area of your circle is: ",answer)
answer = circles.circumference_of_circle(r)
print("The circumference of your circle is: ",answer)

Naming parameters, optional parameters, default parameters

def greetings( given_name, family_name="Smith" ):
    if family_name:
        print("Hello "+given_name+" "+family_name)
    else:
        print("Hello "+given_name)

The following are all valid ways of calling the function from your main file

greetings("Jane", "Doe")
greetings("Jane")
greetings( given_name="Jane" )
greetings( given_name="Jane", family_name="Doe" )

Classes

For a file person.py:

class Person():

    def __init__(self, given_name, family_name, email=None):
        self.given_name = given_name
        self.family_name = family_name
        if email:
            self.email = email
            self.email_provided = True
        else:
            self.email_provided = False

    def set_email(self, email):
        self.email = email
        self.email_provided = True

    def get_name(self):
        return(self.given_name+" "+self.family_name)

    def get_email(self):
        if self.email_provided:
            return self.email
        else:
            return ""

And a second, main file, using it:

import person

me = person.Person("Paul", "Baumgarten", "pbaumgarten@isl.ch")

print("Your email is: " + me.get_email())
print("Your full name is: " + me.get_name())

Modules