Flow Control - Branch Statements - Reference Answers

Assignment 1

Write a user login authentication program. For example, the username is “Albert” and the password is “1”. Ask the user to enter the username and password separately for authentication; if the user’s input is correct, show that the login succeeded, otherwise show that the username or password is wrong.

username = 'Albert'
password = '1'

username_input = input('please input your username>>:')
password_input = input('please input your password>>:')
if username == username_input and password == password_input:
    print('Login successfully')
else:
    print('username or password is invalid')

Approach:

image.png

Assignment 2

Write an age-guessing game for the user. Define the user’s age in advance; if the user’s guess is too high, give a “too high” hint; if the guess is too low, give a “too low” hint; otherwise the user has guessed correctly, and give a “correct” message as well.

age = 18
age_input = input('please input your age>>:')
age_input = int(age_input)
if age_input > age:
    print('too old')
elif age_input < age:
    print('too young')
else:
    print("you've got it")

Approach:

image.png