Skip to content

If statements

Related course:

If statements

A program sometimes may have to make choices.  These choices can execute different code depending on certain condition. In Python the if statement is used for conditional execution.

The if statement may be combined with certain operator such as equality (==), greater than (>=), smaller than (<=) and not equal (!=). Conditions may be combined using the keywords or and and.

Type the program below and run it.

#!/usr/bin/env python3

gender = input("Gender? ")
if gender == "male" or gender == "Male":
    print("Your cat is male")
else:
    print("Your cat is female")

age = int(input("Age of your cat? "))
if age < 5:
    print("Your cat is young.")
else:
    print("Your cat is adult.")

What you see on success

Exercise

Do these exercises:

1. Make a program that asks the number between 1 and 10. 
If the number is out of range the program should display "invalid number".
2. Make a program that asks a password. 

Once completed continue with the next exercise.

Answers

Keyboard input
For Loops
Published inUncategorized

4 Comments

  1. Leonardo Leonardo

    Hi !
    I’m getting this error to your solution in exercise #2
    ideas?; thanks !

    Traceback (most recent call last):
    File “C:/Users/Leonardo/Desktop/Python/hello.py”, line 2, in
    if num > 1 and num ‘ not supported between instances of ‘str’ and ‘int’

  2. Haydn Haydn

    I’m getting an error ‘>’ not supported between instances of str and int. ?

  3. Anonymous Anonymous

    This works for me:
    num = int(input(“Give me a number))

Leave a Reply