Learning Python with Keen (Session 2)

Life
Python
Author

Chen Tang

Published

January 21, 2023

Happy Lunar New Year! Keen’s Python learning journey was put on hold because both he and myself got really busy in Fall 2022 (including a lot of gaming 🤣). Now it’s time to resume!

Session 2: Working with Control Flows

If statements

age = 5

if age < 7:
  print("You are younger than me!")
You are younger than me!

if…elif…else

name = "Keen"

if name == "Kelan":
  print("Hi Kelan!")
elif name == "Keen":
  print("Hi Keen!")
else:
  print("I don't know you...")
Hi Keen!

Exercise: Guess my number

my_number = 67

# guess = input("Please enter a number between 1-100: ")
# guess = int(guess)
guess = 70

if guess == my_number:
  print("You're right!")
elif guess > my_number:
  print("Too large!")
else:
  print("Too small!")
Too large!

Let’s improve this by checking whether the guess is out of range. This can be done by nesting the above if statements into another if statement.

number = 18 # the answer

# guess = input("Please enter a number between 1-100: ")
# guess = int(guess)
guess = 200

if guess > 100 or guess < 1:
  print('Your number is out of the desired range.')
else:
  if guess == number:
    print("You're right!")
  elif guess > number:
    print("Too large!")
  else:
    print("Too small!")
Your number is out of the desired range.

Alright, now it works better. But this code only allows a single guess. We will improve this when we learn how to do loops.