Jamie Starke bio photo

Jamie Starke

I develop for my career, but I also develop for fun, and whenever I think it can solve a problem I'm having. This has lead me to create side projects, such as Rental Map and BusTimes, among others.

Consulting Newsletter Email Twitter Facebook Google+ LinkedIn Github Stackoverflow More

Here are 3 examples of using if statements in python.

This first example takes 1 variable, and checks it against 3 different conditions. Specifically, it checks if the input is negative, positive or 0.

# 1 - Take some input
number = input("Give me a number: ")
# 2 - the number is negative
if number < 0:
    print "This number is negative"
elif number > 0:
    print "This number is positive"
    print "This number is zero"

This second example takes 1 variable, that is an hour of the day in 24 hour clock, and describes if it is morning, noon, afternoon, evening, night, or midnight.

# get us some input
hour = input("Give us an hour in 24-hour clock: ")
if hour == 12:
    print "It's noon"
elif hour == 0 or hour == 24:
    print "It's midnight"
# morning
elif hour > 0 and hour < 12:
    print "It's morning"
# night
elif hour >= 19 and hour < 24:
    print "It's night"
# afternoon
elif hour > 12 and hour < 17:
    print "it's afternoon"
# evening
elif hour >= 17 and hour < 19:
    print "it's evening"
    print "Not a valid hour"

This third example takes in 2 different variables, and says which one is bigger, or if they are the same.

# take a number
number1 = input("Give me a number: ")
# take another number
number2 = input("give me another number: ")
if number1 > number2:
    print "1st is bigger then 2nd"
elif number1 < number2:
    print "2nd is bigger than 1st"
    print "your numbers are the same"