s = input ("Input a String: ")
length = len(s)
print ('The length of the string is ', length,
', the first character ', s[0], ', and the last character ', s[-1])Notes S-08/Python 5: Sequences and conditionals
TOOD: include visualization of IBAN
Use the exercises to move from sequences to conditional logic, while keeping the stated homework decisions.
Slide 88 — Creating strings
Single and double quotation marks both create strings and allow the other kind of quote to appear inside a value.
var1 = 'Hello World!'
var2 = "Python Programming"
x = 'abc'
type(x)
y = '"A quotation!"'
print(y)Slide 90 — Slicing strings
The two complementary slices reconstruct the original string.
s = 'Don Quijote'
s[:6] + s[6:]Slides 91–92 — Strings and IBAN
Assign exercise 3 as homework.
- Write a Python program to calculate the length of a string you type in. Furthermore, it should output the first and the last character.
In-class exercise ../materials/session_08/String1.py
- Write a Python program to insert a string in the middle of a string.
In-class exercise ../materials/session_08/String2.py
s = input ("Input a String: ")
half = len(s)//2
s1 = input("String to insert: ")
s_new = s[:half] + s1 + s[half:]
print ('The new string is ' + s_new)- Write a program that at first asks for two strings…
Homework solution ../materials/session_08/String3.py
s1 = input("Enter the first string: ")
s2 = input("Enter the second string: ")
s = s1 + " " + s2
print(s)
print(len(s))
print(s[1])
print(s[4])
print(s[6])
print(s[-4:])
# if length of the string is odd
mid = len(s)//2 + 1
print(s[mid-2:mid+1])
# if length of the string is even
mid = len(s)//2
print(s[mid-2:mid+2])
print("E" in s)
print("el" in s)- The International Bank Account Number (IBAN) is a standardized international numbering system developed to identify bank accounts across national borders….
In-class exercise ../materials/session_08/IBAN.py
an = input('Enter the account number: ')
bc = input('Enter the bank code: ')
cc = input('Enter the county code as a number (e.g. 1314 for DE): ')
base_string = bc + an + cc + '00'
base_number = int(base_string)
validation_number = 98 - base_number%97
print(validation_number)Include a visualization of the IBAN procedure.
Slide 93 — Creating lists
Lists may contain different data types and may themselves contain other lists.
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
list4 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]Slide 94 — Prepare a list for slicing
This list is used for the indexing and slicing examples shown on the slide.
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Slide 97 — List operations
- Perform the following list operations:
In-class exercise ../materials/session_08/Listexercise1.py
cars = ['Audi', 'VW', 'BMW', 'Honda', 'Mercedes']
print(cars[2:4])
print('A great car manufacturer is ' + cars[0] + '.')
cars.append('Volvo')
len(cars)
cars.index('Honda')
cars.remove('Honda')
print(cars[-1])- Write a program that creates an empty list named x at first.
- Assign exercise 2 as homework.
x = []
n = int(input("Enter the first number: "))
x.append(n)
n = int(input("Enter the second number: "))
x.append(n)
n = int(input("Enter the third number: "))
x.append(n)
n = int(input("Enter the fourth number: "))
x.append(n)
print(x)
x.insert(0, x[0]+x[1]+x[2]+x[3])
print(x)
x.reverse()
print(x)
x.remove(2)
print(min(x))
print(max(x))
print(x[-2:])Slide 98 — Creating and slicing tuples
- Cover tuples briefly; use
df.shapeas an example.
Indexing and slicing are similar for tuples and lists.
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5)
tuple3 = ("a", "b", "c", "d")
tuple4 = ((1, 2, 3, 4), (5, 6, 7, 8))
tuple1[1]
tuple2[2:4]
tuple4[1][2:4]Slide 99 — Mutable lists and immutable tuples
The final line intentionally raises TypeError: 'tuple' object does not support item assignment because tuples are immutable.
mylist = [1, 2, 3, 4]
mytupel = (1, 2, 3, 4)
print(mylist)
print(mytupel)
mylist[2] = 5
print(mylist)
mytupel[2] = 5☕ Break — 10 minutes
Slide 104 — Conditional statements
Assign suitable values to x, y, and time before running the relevant examples.
if x < 1:
print("x smaller than 1")if x < 1:
print("x smaller than 1")
else:
print("x is bigger than or equal to 1")if x < 1:
print("x smaller than 1")
elif x == 1:
print("x is equal to 1")
else:
print("x is bigger than 1")# Swap x and y if y < x
print(x, y)
if y < x:
temp = x
x = y
y = temp
print(x, y)if time >= 11 and time <= 13:
print("It is noon!")The final condition can also use a chained comparison:
if 11 <= time <= 13:
print("It is noon!")Slides 105–107 — Conditional logic
PR: exercises 3, 5, 6, 7: homework (for the tutorial).
- Write a program to determine if a number entered is odd or even.
In-class exercise ../materials/session_08/OddEven.py
i = int(input("Insert a number: "))
if i%2==0:
print("The number is even!")
else:
print("The number is odd!")- Write a program that calculates a discount based on the purchase amount.
In-class exercise ../materials/session_08/Discount.py
amount = float(input("Input the purchase amount: "))
if amount >= 100:
discount = 20
elif amount >= 50:
discount = 10
else:
discount = 0
print("Discount: " + str(discount) + "%");- Extend the program which calculates the annual payment of an annuity loan by a rating parameter.
amount = float(input("Enter the amount: "))
interestrate = float(input("Enter the interest rate (in %): "))
interestrate = interestrate/100.0
duration = int(input("Enter the duration (in years): "))
rating = input("Enter the rating (a, b or c): ")
if(rating == "b"):
interestrate = interestrate * 1.1
elif(rating == "c"):
interestrate = interestrate * 1.2
annualpayment = amount * (((1 + interestrate) ** duration * interestrate) / ((1 + interestrate) ** duration - 1))
print("The annual payment is ", annualpayment)- Write a program that simulates a dice game.
Explain exercise 4 in class, emphasizing the importance of whether code is inside or outside an if block.
In-class exercise ../materials/session_08/dicegame1.py
import random
stake = int(input('How much money would you like to invest? '))
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
if dice1 == dice2:
print("You have won!!! It's a double", dice1)
payout = stake * dice1
print("You get", payout, "Euro!")
else:
print("Unfortunately they lost!!! The throw brought", dice1, "and", dice2)- Write a program to convert temperatures between celsius and fahrenheit.
In-class exercise ../materials/session_08/Temperature.py
type = input("Specify the temperature type, you enter (f or c): ")
temp = int(input("Input the temperature you like to convert : "))
if type == "f":
result = (9 * temp) / 5 + 32
print("The temperature is", result, "degrees.")
elif type == "c":
result = (temp - 32) * 5 / 9
print("The temperature is", result, "degrees.")
else:
print("Input proper type.")- Write a program to calculate the grades A-F based on the final percentage score:
Homework ../materials/session_08/Grade.py
score = int(input("Input a score (in %): "))
if score<50:
grade = "F"
elif score<59:
grade = "E"
elif score<69.5:
grade = "D"
elif score<80:
grade = "C"
elif score<90.5:
grade = "B"
else:
grade = "A"
print("The grade is: ", grade)- Write a program to calculate income tax (T) and net income for any taxable income (X)
Homework ../materials/session_08/Tax.py
x = float(input("Enter the taxable income: "))
if x < 11604:
t = 0
if 11604 < x <= 17005:
y = (x - 11604) / 10000
t = (922.98 * y + 1400) * y
if 17005 < x <= 66760:
z = (x - 17005) / 10000
t = (181.19 * z + 2397) * z + 1025.38
if 66760 < x <= 277825:
t = 0.42 * x - 10602.13
if 277825 < x:
t = 0.45 * x - 18936.88
ni = x - t
print("The tax to pay is ", t)
print("The net income is ", ni)Summary and announcements
Take notes on improvements and common questions during the session and add them to feedback.qmd afterwards.