Python 2: Conditions

Learning Goals:

 

By the end of this lesson you should be able to:

1.     Describe how tab is used to define blocks in Python

2.     Set up an if-statement

3.     Use a variety of conditional operators (<,>,==..)

 

 

Conditions

For a programming language to be useful it needs to be able to compare values and act on the result.   The most common structure for this is the “if-Statement”.

 

If something is true do this

 

Examples: 

if(4>2):

print(‘4 big!’)

 

print(‘All Done’)

if(4!=4):

  print('hi')

else:

  print('bye')

 

print(‘All Done’)

 

Note 1:  To tell Python what you want to do in the ‘true’ case you need to hit tab once on each line.  This is one of the features that sets Python apart  from other languages, it forces you to have perfect form.  

 

 

Operators:

> 

Greater Than

>=

Greater Than or Equal to

< 

Less than

<=

Less than or Equal to

==

Equals

!=

Not Equals

 

 You can also link conditions together using the key words ‘and’ and ‘or’.

 

 For Example:

if(a > 5 and a < 10):

    print (‘a is between 5 and 10!)

if(a == 5 or a == 10):

    print (‘a is either 5 or 10!)

 

 

Programs

Save each program in you unit 1 folder as a text document called A2Px where x is the program number.  Then copy and paste it into the python interpreter.   Use the # symbol in include your name and the program code at the top of your script.

 

Ex:  #Tony Demello A1P1

 

Program 1 – Positive, Negative or Zero

Write a program that prompts the user to enter an integer.  Tell the user whether it is positive, negative or zero.  Hint: Positive numbers are >0

 

Program 2 – Password  

Prompt the user to enter a user name and password. Check them against a user name and password in your program to tell them whether access is granted or denied.

 

Program 3- Average Score Mark II

Prompt the user to enter 5 scores between 0 and 100.  Calculate the average and display the result.   With an appropriate comment in these  ranges:

 

Less than 50

Between 50 and 65

Between 65 and 80

Between 80 and 90

Over 90

 

 

 

 

Show Mr.Kurz all 3 programs when you are finished.