python

236319 Spring 2024, Prof. Lorenz


python

introduction

(based on the python tutorial)


comments

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."

numbers

2 + 2
50 - 5 * 6
(50 - 5 * 6) / 4
8 / 5  # division always returns a floating point number
17 // 3  # floor division discards the fractional part

the function type returns the type of an object

type(2)
type(1.5)
type(1 + 1j)  # complex numbers!

= is used for assignment

width = 20
height = 45
width * height

strings

'spam eggs'  # single quotes
'doesn\'t'  # use \' to escape the single quote...
"doesn't"  # ...or use double quotes instead
"""
a
multiline
string
"""

print

print("a string")
print(5)

string operations

5 * "na " + "batman!"
word = "Python"
word[4]
word[2:5]
len('supercalifragilisticexpialidocious')

strings are immutable

word[0] = "J"

lists

squares = [1, 4, 9, 16, 25]
squares
squares[0]
squares[-1]  # negative indices
squares[-3:]
squares + [36, 49, 64]
cubes = [1, 8, 27, 65, 125]  # something's wrong here
cubes[3] = 64  # replace the wrong value
cubes
cubes.append(6**3)
cubes