Difference between revisions of "Selection - Python"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "=What is Selection= Selection is a key construct that exists in any programming language, and each language has a specific implementation but they are all relatively the same....")
 
(If Statement in Python)
Line 12: Line 12:
 
     line 3
 
     line 3
 
     line 4
 
     line 4
 +
 +
=Comparison Operators=
 +
The condition in the if statement must equate to true or false, so comparison operators are required. In python the comparison operators are:
 +
 +
[[File:Python comparison operators.gif|600px]]
 +
 +
=Example=
 +
The if...else statement can be used to make a decision:
 +
 +
<syntaxhighlight lang=python>
 +
age =  input("Please enter your age:")
 +
if age>=18 :
 +
    print("You are old enough to drink")
 +
else :
 +
    print("you are not old enough to drink")
 +
</syntaxhighlight>

Revision as of 12:38, 20 June 2018

What is Selection

Selection is a key construct that exists in any programming language, and each language has a specific implementation but they are all relatively the same.The other key constructions are sequence (ie program runs in order) and iteration (loops).

If Statement in Python

Use the command ‘if’ followed by a condition & the colon ‘:’, The condition should equate to true or false. Instead of using brackets, in python you indent the code to run if true. Each line with the same indent will be run if true. The else can also be used followed by a colon ‘:’ and again the code to run in the else should be indented:

if true:
    line 1
    line 2
else:
    line 3
    line 4

Comparison Operators

The condition in the if statement must equate to true or false, so comparison operators are required. In python the comparison operators are:

Python comparison operators.gif

Example

The if...else statement can be used to make a decision:

age =  input("Please enter your age:")
if age>=18 :
     print("You are old enough to drink")
else :
     print("you are not old enough to drink")