Python Summary

Patrick Bucher

1 Basics

1.1 Printing

Print text with variables to the screen:

#!/usr/bin/python3

name = 'Patrick'
year = 1987

# concatenation (and explicit conversion)
print("I'm " + name + ", I was born in " + str(year) + ".")

# multiple parameters to print
print(name, ", was born in ", year, ".", sep = '')

# classic format strings
print("Was %s really born in %d?" % (name, year))

# new format string syntax
print(f"Yes, {name} was indeed born in {year}.")

# string's format method
fmt = "Certainly there was another {} born in {}."
print(fmt.format(name, year))

# additional parameters to print
print("Name", name, sep=': ', end='\n')
print("Born", year, sep=': ', end='\n')

# triple quote strings can contain line breaks, tabs etc.
print("""
    Hi, my name is %s.
    I was born in %d.
    """
    % (name, year))

Output:

I'm Patrick, I was born in 1987.
Patrick, was born in 1987.
Was Patrick really born in 1987?
Yes, Patrick was indeed born in 1987.
Certainly there was another Patrick born in 1987.
Name: Patrick
Born: 1987

    Hi, my name is Patrick.
    I was born in 1987.
    

1.2 Strings

Basic string methods:

#!/usr/bin/python3

print('new planet discovered'.title())
print('SHOUTING IS BAD FOR YOU'.lower())
print('this should be in capitals'.upper())

a = 'too much       '
b = '     space     '
c = '         is bad'
print(a.rstrip(), b.strip(), c.lstrip())

Output:

New Planet Discovered
shouting is bad for you
THIS SHOULD BE IN CAPITALS
too much space is bad

2 Lists

2.1 List Basics

Create a list, add and remove items:

#!/usr/bin/python3

animals = ['dog', 'cat', 'horse']
print('animals:', animals)

print('first animal:', animals[0])
print('last animal:', animals[-1])

animals[0] = 'donkey' # ['donkey', 'cat', 'horse']
animals.insert(2, 'pig') # ['donkey', 'cat', 'pig', 'horse']
print('more animals:', animals)

del animals[3] # ['donkey', 'cat', 'pig']
print('remaining animals:', animals)

last_animal = animals.pop() # ['donkey', 'cat']
print('last animal:', last_animal)
print('other animals:', animals)

other_animal = animals.pop(0) # ['cat']
print('other animal:', other_animal)

animals.remove('cat') # []

animals = ['cow', 'pig', 'cow']
print('duplicate:', animals)
animals.remove('cow') # ['pig', 'cow']
print('only first removed:', animals)

Output:

animals: ['dog', 'cat', 'horse']
first animal: dog
last animal: horse
more animals: ['donkey', 'cat', 'pig', 'horse']
remaining animals: ['donkey', 'cat', 'pig']
last animal: pig
other animals: ['donkey', 'cat']
other animal: donkey
duplicate: ['cow', 'pig', 'cow']
only first removed: ['pig', 'cow']

3 Miscellaneous

Get input from the command line:

#!/usr/bin/python3

name = input("What's your name? ")
year = input("In what year have you been born? ")

print(f"{name} was born in {year}.")

Output (and Input):

What's your name? Patrick
In what year have you been born? 1987
Patrick was born in 1987.