>>> print('Hello multiple worlds!')
Hello multiple worlds!
>>> 'Hello' == "Hello"
True
>>> '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'
>>> '{} {}'.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'
>>> 'abc'.upper()
'ABC'
>>> 'XYZ'.lower()
'xyz'
>>> ' Interesting text '.strip()
'Interesting text'
>>> 1 + 1
2
>>> 3.14 * 100
314.0
>>> 30 / 10
3.0
>>> 0.1 + 0.2
# internal representation of floats is not exact
0.30000000000000004
>>> 'JU' + 2602
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> 'JU{}'.format(2602)
JU2602
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)
>>> grades = ['Underkänt', 'Godkänt', 'Väl Godkänt']
>>> grades[1]
'Godkänt'
>>> grades[-2]
'Godkänt'
>>> grades[0]
'Underkänt'
>>> 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']
>>> 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']
>>> 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
>>> 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
>>> 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]
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]
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!
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!
>>> 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'}
>>> 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
>>> 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
>>> 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?
def
A function is some process that you can run by calling the function name.
>>> def hello():
>>> print('Greatings earthling!')
>>>
>>> hello()
Greatings earthling!
>>> def hello_there(name):
>>> print(f'Hello there {name}!, long time no see!')
>>>
>>> hello_there('Bobby')
Hello there Bobby!, long time no see!
>>> 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.
>>> 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
if
s, keep it simple and readableA module is just a file containing python code.
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)
Example squares.py
:
def nsq(n):
return [i ** 2 for i in range(1, n + 1)]
if __name__ == '__main__':
print(nsq(10))