Script execution
""" When you type a statement, the interpreter executes it
"""
n = 17 # stmt
print(n) # stmt
"""
17
"""
Assigments in python
""" An assignment creates a variable and gives it value
"""
n = 17
n = n + 24
# You can assign multiple variables in one line
a, b, c = 1, 2, 3
# Output variables
print(n)
print(a, b, c)
""" A variable must be assigned before use
"""
y = 0
y = y + 1
assert y == 1 # pass
# Variable not assigned before use
try:
z = z + 1
except NameError:
print('Variable z not defined')
""" In Python it is legal to reassign a variable
An assignment can make two variables equal, but not permanent
"""
x = 5
x = 7
assert x == 7 # pass
assert x != 5 # pass
a = 1
b = 1
assert a == b # pass
a = 2
assert a != b # pass
"""
41
1 2 3
Variable z not defined
"""
Conditional statement
""" Conditional statement
We can check condtions and change the behavior
"""
n = 20
if n % 10 == 0:
print("n is divisible by 10")
elif n % 10 > 0:
print("n is not divisible by 10")
else:
pass
# Conditional expression (more concisely)
a = 0
msg = "positive" if a >= 0 else "negative"
print("a is", msg)
# Conditional expressions are very useful within lambda expressions
func = lambda x: 'even' if x % 2 == 0 else 'odd'
print(func(2))
print(func(3))
While statement
""" While statement
The syntax is similar to a function definition.
"""
def countdown(n):
while(n > 0):
print(n)
n = n -1
countdown(5)
User input
""" Sometimes you want to take input from user until they type quit
"""
while True:
line = input('> ')
if (line == 'quit'):
break
print(line)
print('Done')
Multiline string
""" Split a single statemenbt on multple lines with `backslash` \
"""
print("Hello " + \
"World")
"""
Hello World
"""
Last update: 17 days ago
Questions and answers:
Multiple assignments in one line are permitted.
- a) a,b = 1,2
- b) false
In Python it is legal to reassign a variable.
- a) true
- b) false
An assignment make two variables equal.
- a) true
- b) true, but not permanent
Which one includes a conditional expression?
- a) myfunction = lambda x: 'even' if x % 2 == 0 else 'odd'
- b) if n % 10 == 0: print('divisible by 10')