CMPT165-Conditions.docx

92 views3 pages

For unlimited access to Class Notes, a Class+ subscription is required.

Conditions
•An if statement can be used to make your program do different things under different
circumstances
•The main component of an if statement is a condition
E.g. age = raw_input("Enter your age:")
if age > 24:
print "You're old"
•A condition is a statement that can either be True or False
•When the condition in an if statement is True, the code indented below it will run
•If the condition is False, this code will not run
•Conditions always involve comparing a variable with a value or another variable
•The possible ways of comparing are
== (equals)
> (greater than)
>= (greater than or equal)
< (less than)
<= (less than or equal)
!= (does not equal)
E.g. age = raw_input("Enter your age:")
if age > 24:
print "You're old"
Output (user input in bold)
Enter your age:60
You're old
However,
Enter your age:7
You're old
Instead,
age = int(raw_input("Enter your age:"))
if age > 24:
print "You're old"
else:
print "You're young"
Here, we have an else statement
•An else statement says, "If the previous if statement was False, then run the code indented
below the else"
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$10 USD/m
Billed $120 USD annually
Homework Help
Class Notes
Textbook Notes
40 Verified Answers
Study Guides
1 Booster Class
Class+
$8 USD/m
Billed $96 USD annually
Homework Help
Class Notes
Textbook Notes
30 Verified Answers
Study Guides
1 Booster Class