If Statements

The most important feature in any programming language is how it expresses conditionals. You rarely have a program which does the same exact series of instructions every time, especially if it processes input. Even the most basic programs need to be able to make choices, and execute a different series of instructions if certain conditions are met.

Reading: Chapter 3

Read Chapter 3 in the online textbook up until you reach "Catching Exceptions".

Today in Class

We will discuss and learn about:

You should be able to understand these two programs.

You should try them here!

name = input("Well hi what is your name? ")
howlong = len(name)

if howlong > 8:
      print("Wow that's a long name!")
      if howlong > 12:
             print("Umm, you might want to shorten that.")

if howlong < 4:
     print("I like short names.")

print("Nice to meet you, " + name)	
    num = input("Enter an integer: ")
num = int(num)   # remember why we need this? 
      
if num % 2 == 0:
      print("Even number!")
else:
      print("Odd number!")
      num = input("Can you give me an even one? ")
      num = int(num)
      if num % 2 == 1:
           print("...guess not")

And introducing the split() function!

# Expects the user to type in the format "9:45 PM"
fulltime = input('What time is it? ')
# This takes "8:55 PM" and splits it at the space character into two values ("8:55" and "PM").      
hourmin,ampm = fulltime.split()

# This takes "8:55" and splits it on the colon into two values ("8" and "55").      
hour,minute = hourmin.split(':')

if ampm == 'PM':
  hour = int(hour) + 12

print("Military time: " + str(hour) + minute)