Your Basic Python

  • Part of JU2602
  • Mikko Hellsing, mikko@sumsum.se

What we will talk about today

  • Basic data types: strings, numbers
  • Variables -What are they and how to use them?
  • More advanced data types: lists, dictionaries
  • Control structures: if, for
  • Functions: def
  • If there is time: modules and example programs

How to write strings

>>> print('Hello my little friend!')
Hello my little friend!

>>> 'Hello' == "Hello"
True

How to index strings

>>> 'Karl Popper'[1]
'a'

>>> 'Guido Van Rossum'[0:3]
'Gui'

>>> 'Guido Van Rossum'[:3]
'Gui'

>>> 'Guido Van Rossum'[14:]
'um'

>>> 'Guido Van Rossum'[-2:]
'um'

String ranges

Concatenate strings

>>> '{} {}'.format('one', 'two')
'one two'

>>> '{0} {1} {0} {1} and so on...'.format('one', 'two')
'one two one two and so on...'

>>> 'a' + 'b' + 'c' + 'd' # You *can* do this too but...
'abcd'

Transform strings

>>> 'abc'.upper()
'ABC'

>>> 'XYZ'.lower()
'xyz'

>>> '  Interesting text      '.strip()
'Interesting text'

Calculate with numbers

>>> 1 + 1
2

>>> 3.14 * 100
314.0

>>> 30 / 10
3.0 

>>> 0.1 + 0.2
0.30000000000000004  # internal representation of floats is not exact

All together now

>>> 'JU' + 2602
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

>>> 'JU{}'.format(2602)
JU2602

Variables

Some naming rules/conventions

  1. Use lower case letters and underscore
  2. Be descriptive but not overly verbose
  3. Don't start with a number, infact avoid using numbers
  4. Using one letter variable names violates #2

Examples

drink = 'The green elevator'
first_name = 'Greta'
participants = 5034132
cards = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10, 'J', 'Q', 'K', 'A']
name_pat = re.complie('(w+) (w+)')
person = Human(conciousness=False)

Lists

Accessing elements

>>> grades = ['Underkänt', 'Godkänt', 'Väl Godkänt']
>>> grades[1]
'Godkänt'

>>> grades[-2]
'Godkänt'

>>> grades[0]
'Underkänt'

Append, pop & len

>>> currencies = ['SEK', 'NOK', 'DKK', 'EUR']
>>> currencies.append('PKK')
>>> currencies
['SEK', 'NOK', 'DKK', 'EUR', 'PKK']

# But PKK is not a currency
>>> currencies.pop()
'EUR'
>>> len(currencies)
4
>>> currencies
['SEK', 'NOK', 'DKK', 'EUR']

Extend, index & sort

>>> currencies.extend(['GBP', 'BTC'])
>>> currencies
['SEK', 'NOK', 'DKK', 'EUR', 'GBP', 'BTC']

>>> currencies[-2]
'GBP'

>>> currencies.remove('BTC')
>>> currencies
['SEK', 'NOK', 'DKK', 'EUR', 'GBP']

>>> currencies.sort()
>>> currencies
['DKK', 'EUR', 'GBP', 'NOK', 'SEK']

List iteration

>>> for cur in currencies:
>>>     print(cur)
DKK
EUR
GBP
NOK
SEK

>>> for i in [0, 1, 2]:
>>>     print(i, 'is less than', i + 1)
0 is less than 1
1 is less than 2
2 is less than 3

All together now

>>> trix = ['tailslide', 'boardslide', 'grind', 'boneless']
>>> 'ZERO {} TWO'.format(trix[-1][1:4].upper())
'ZERO ONE TWO'

>>> primes = [2, 11, 7, 13, 5]
>>> primes.append(3)
>>> primes.sort()
>>>
>>> for p in primes[2:-2]:
>>>     print(p)
5
7

One more thing...

>>> times_two = [x * 2 for x in [1, 2, 3]]
>>> times_two
[2, 4, 6]

# Using Python 3.6+ f-string
>>> [f'{c}ello' for c in ['H', 'Y', 'M']]
['Hello', 'Yello', 'Mello']

>>> [x * x for x in [1, 2, 3, 4, 5, 6, 7]]
[1, 4, 9, 16, 25, 36, 49]

>>> [x * x for x in range(1, 8)]
[1, 4, 9, 16, 25, 36, 49]

Tuples vs Lists

A tuple acts alot like a list but it is immutable, that means that it's contents cannot be changed, it can be redefined but not altered.

>>> salaries = [45000, 28000]
>>> salaries.append(33000)  # salaries = [45000, 28000, 33000]

>>> salaries = (45000, 28000)
>>> salaries.append(33000) # Not allowed, will generate error.

>>> [s * 12  for s in salaries]
[540000, 336000]

Let's try it out

Programming using if should match your intuition pretty well.

>>> if True:
>>>     print('Amazing')
Amazing

>>> if len('Lionel') == len('Hello'):
>>>     print('It is not me you are looking for.')
>>> else:
>>>     print('Is it me you are looking for?')
Is it me you are looking for?

If elif else

>>> if 1 == 3:
>>>     print('Wow!')
>>> elif 1 == 2:
>>>     print('Wow!')
>>> else:
>>>     print('Boring.')
Boring.

>>> if 1 != 3 and 2019 > 2018:
>>>     print('You enlighten me!')
You enlighten me!

Nested if & lists

>>> stuff = ['Paper', 'Pen', 'Eraser', 'TV']
>>> if 'Laptop' in stuff:
>>>     print('You will be successful!')
>>> else:
>>>     if 'Pen' in stuff and 'Paper' in stuff:
>>>         print('Evolution, ever heard of that?')
>>>     else:
>>>         print("It's not like you are the future but ok.")
>>>     print('You are bound for unsuccess!')
Evolution, ever heard of that?
You are bound for unsuccess!

Dictionaries

>>> colours = {'C': 'Cyan', 'M': 'Magenta', 'Y': 'Yellow', 'K': 'Key'}
>>> colours['Y']
'Yellow'

>>> colours['R'] = 'Red'
>>> colours.update({'G': 'Green', 'B': 'Blue'})
>>> colours
{'C': 'Cyan', 'M': 'Magenta', 'Y': 'Yellow', 'K': 'Key', 'R': 'Red',
 'G': 'Green', 'B': 'Blue'} # In Python 3.6+ the insertion order preserved.

Popping and iterating

>>> ages = {'pope': 82, 'trump': 72, 'merkel': 65}
>>> ages.pop('trump')
72
>>> for name, age in ages.items():
>>>     print(f'{name}: {age}')
pope: 82
merkel: 65

Keys n' values

>>> food = {'p': 'Potato', 't': 'Tomato'}
>>> food.keys()
dict_keys(['p', 't'])

>>> for k in food.keys():
>>>     print(k)
p
t

>>> for v in food.values():
>>>     print(v)
Potato
Tomato

All together now!

>>> junk_food = {
>>>   'burgers': ['normal', 'cheese', 'veggie'],
>>>   'fries': ['normal', 'large'],
>>>   'drinks': ['soft', 'milkshake'],
>>> }

>>> for btype in junk_food['burgers']:
>>>     print(f'Who wants a {btype} burger?')
Who wants a normal burger?
Who wants a cheese burger?
Who wants a veggie burger?

Functions

Define a function with def

A function is some process that you can run by calling the function name.

>>> def hello():
>>>     print('Hello my little friend!')
>>>
>>> hello()
Hello my litte friend!

>>> def hello_there(name):
>>>     print(f'Hello there {name}!, long time no see!')
>>>
>>> hello_there('Bobby')
Hello there Bobby!, long time no see!

Default arguments

>>> def diagnose(name, disease='a cold'):
>>>     """Rigorous diagnostic procedure is performed here"""
>>>     print(f'{name} has {disease}')
>>> 
>>> diagnose('Fardosa')
Fardosa has a cold

>>> diagnose('Bob', 'N.P.D.')
Bob has N.P.D.

Returning values

>>> def is_even(x):
>>>     """Checks if a number is even"""
>>>     return x % 2 == 0
>>>     
>>> for x in range(6):
>>>     if is_even(x):
>>>         print(f'{x} is an even number')
0 is an even number
2 is an even number
4 is an even number

Some good ideas on functions

  • Make each function have one responsability
  • Don't write long functions, keep them under ~50loc
  • Include a docstring
  • Don't nest too many ifs, keep it simple and readable
  • Use the same naming rules as for variables

What is a module?

A module is just a file containing python code.

Example module cat

The file cat.py is a module. It imports a module: random, defines 2 functions: cat_name and cat_life and defines one constant: CATIQ.

import random

CATIQ = 34 

def cat_name():
    return random.choice(['Maja', 'Sigge', 'Selma', 'Nisse'])

def cat_life():
    return random.normalvariate(10, 5)

Module with main program

Example squares.py:

def nsq(n):
    return [i ** 2 for i in range(1, n + 1)]


if __name__ == '__main__':
     print(nsq(10))