Main

Python Conditional Statements

The following tutorial is an introduction to Python conditional statements using the IF command and comparison statements such as those shown below.

 Operator
 <   - less than
 <=  - less than or equal to
 >   - greater than
 >=  - greater than or equal to
 ==  - equal
 !=  - not equal to

Certain keywords such as AND, OR, and NOT can be used to combine, select, or reverse the outcome of conditional statements. These logical operations change the results based on input data.

 Function
 if  - execute code with true logical condition
 and - return True if both statements are True
 or  - return True if either statement is True
 not - return the opposite of the input True/False

The following video tutorial demonstrates logical operations with a number guessing game.

Number Guessing Game in Python

 from random import *
 answer = randint(0,100)
 correct = False
 while not(correct):
     guess = int(input("Guess a number: "))
     if guess < answer:
         print("Too low")
     elif guess > answer:
         print("Too high")
     else:
         print("Correct!")
         correct = True

comments powered by Disqus