Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
50 views

4 - Programming Companion Python-If Satements

Uploaded by

Vedant Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

4 - Programming Companion Python-If Satements

Uploaded by

Vedant Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Objective 4:

Understand how to use selection statements


In this objective you learn how to make different parts of your program run depending on the value of
variables.

Tasks
1. Try entering the following commands and see what happens:

#Using selection statements to check variables


#Ask user for the number
number = int(input("Enter a number 1-3:"))
#Check the value of the number
if number == 1: print("Number one")
if number == 2: print("Number two")
if number == 3: print("Number three")

== allows you to check if a variable equals a value.

2. Try entering the following commands and run the program three times with the test data:
6, 51 and 70.

Pay careful attention to the indentation with tabs, these are not spaces.

#Works out whether a candidate passed or failed


score = int(input("Enter score:"))
if score > 40:
TAB print("You passed")
else:
TAB print("You failed")

Note how the program only executes instructions if the condition is true i.e. the score is more than
40, and how it is possible to use an else statement to run an alternative set of commands if the
condition is false.

3. Change the program so that you have to score over 50 to pass.


4. Try entering the following commands and run the program three times with the test
data:
6 & 4, 51 & 51.

#Returns whether two numbers are the same


num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
if num1 != num2:
print("The numbers are not the same")

else:
print("The numbers are the same")

Note != means does not equal.

5. Try entering the following commands and run the program three times with the test data:
1, 3, 5.

#Using logic operators


choice = input("Enter a number 1-3: ")
if choice > "0" and choice < "3":
print("Valid input")
else:
print("Invalid input")

Note how ‘and’ can be used to check if both conditions are true. You can also use ‘or’ if only one
condition needs to be true and ‘not’ as an alternative to does not equal.

Note how the number was input as a string, not an integer, yet greater than and less than operators
still work to check if the input was between 1 and 2. That’s because the ASCII value of the character is
being checked, not the actual number. This approach is helpful as it prevents the program crashing if a
character is input instead of a number.
6. Try entering the following commands and see what happens:

#Using case selection


#Ask user for the number
print("1. Add numbers")
print("2. Subtract numbers")
print("3. Quit")

choice=input("Enter your choice: ")


#Multiple branches depending on selection
if choice == "1":
print("Add numbers chosen")
elif choice == "2":
print("Subtract numbers chosen")
elif choice == "3":
print("Quit chosen")

Note how it is possible to use elif to have multiple branches rather than just true or false.
Objective 4: Key learning points
How to use selection statements
• Checking the value of a variable and executing instructions depending on the outcome of the check
is known as a selection.
• The instructions that are executed as a result of a selection is known as a program branch.
• The logical checking of a variable against another value is known as a condition.
• Elif commands can be used instead of multiple if statements.
• Code for each program branch must be indented.
• It is good practice to comment a selection to explain its purpose.
• One ‘If’ can be placed inside another ‘If’, this is known as nesting.

Objective 4: Key words


If… else: …
Example code: If (x>0 and x<5) or x=10:

else:

x is the variable being checked. Multiple variables can be checked in one condition. Use brackets to
express order of priority. In the example code, x must be between 0 and 5 or equal to 10 for the condition
to be true. Else is optional and is used to branch if the condition is false. All program branches must be
indented.

Logical operators that can be used in conditions include:

== equals < less than and both conditions must be true


!= does not equal <= less than or equal to or one condition must be true
> greater than not condition is not true
>= greater than or equal to

elif
Example code: if x == 3:

elif x < 3:

elif x >= 10 and x <= 20:

else:

x is the variable being checked. elif is used as an alternative to multiple if statements.


Objective 4: Challenges
Under age challenge
Difficulty:  G

Write a program that asks for your age. If you are over 18 it outputs the message, “Over 18”, otherwise it
outputs, “Under 18”.

Water temperature challenge


Difficulty:  G

Write a program that reads in the temperature of water in a container in Centigrade and displays a
message stating whether the water is frozen (zero or below), boiling (100 or greater) or neither.

Vocational grade challenge


Difficulty:  G

Write a program that allows you to enter a test mark out of 100.
The program outputs “FAIL” for a score less than 40, “PASS” for a score of 40 or more, “MERIT” for a score
of 60 or more and “DISTINCTION” for a score of 80 or more.

Extended visual dice challenge


Difficulty:  G

Write a program that asks for a number and outputs that number as a graphical dice. E.g.

oooooooooooo
o o
o # o
o # o
o # o
o o
oooooooooooo
Greatest number challenge
Difficulty:  G

Write a program to display the larger of two numbers entered:

Start

Input number1
from keyboard

Input number2
from keyboard

Is number1
Yes No
greater than
number2?

Output, “The Output, “The


largest number largest number
is “ number1 is “ number2

Stop
Nitrate Challenge
Difficulty:  G

When keeping fish, one of the goals to reduce algae is to keep nitrates to a minimum. One way of doing
this is to dose a carbon source which nitrifying bacteria within an aquarium consume together with
nitrates. The carbon source has to be dosed very precisely. Write this program to determine the dose:

Start

Enter the nitrate


level: a number
between 1 and 50

Yes Is nitrate No
above 10?

Output
“Dose 3ml” Yes Is nitrate
above 2.5?

No

Output Is nitrate Yes


“Dose 2ml” above 1?

No

Output “Dose Output “Dose


0.5ml” 1ml”

Stop
Portfolio grade challenge
Difficulty:  G

Write a program that inputs a mark from the keyboard for sections of a project: ‘analysis’, ‘design’,
‘implementation’ and ‘evaluation’. The program should output the total mark, the grade, and how many
more marks were needed to get into the next mark band.

Grades are:

0 U
4 G
13 F
22 E
31 D
41 C
54 B
67 A
80 A*

Cash machine challenge


Difficulty:  A

A cash machine dispenses £10 and £20 notes to a maximum of £250. Write a program that shows the user
their balance, asks them how much to withdraw, ensures this is a valid amount without going overdrawn
and with the notes available and outputs the new balance.

Periodic table challenge


Difficulty:  A

Write a program that asks the user to enter the symbol or name of an element, or group it belongs to. The
program should output the name of the element and its atomic weight. E.g.

The user enters Li. The program outputs:

Element: Lithium
Atomic weight: 6.94
Group: Alkali metals

If the user enters Alkali metals, the program outputs the data for all the elements in the alkali metals
group.

You only need to get this working for 6 elements from two different groups.
Train ticket challenge
Difficulty:  A

A train fare from Cheltenham to London is calculated in the following way:

• £20 per station from start to destination for adults.


• £5 extra per stop between 6am and 9am.
• Half price for children.

Write a program that allows the user to enter how many stations they need to pass through, how many
adults, how many children and the time of day (as a number: 24 hour clock). The program should output
the correct fare.

Test the program with the following data:

Test Stations Adults Children Time Expected


1 2 1 0 10 £40
2 4 2 2 11 £240
3 2 1 0 8 £50
4 4 1 0 8 £100
5 3 2 1 7 £187.50
6 0 0 0 0 £0

Hours worked challenge


Difficulty:  A

Write a program that asks the user for the number of hours worked this week and their hourly rate of pay.
The program is to calculate the gross pay. If the number of hours worked is greater than 40, the extra
hours are paid at 1.5 times the rate. The program should display an error message if the number of hours
worked is not in the range 0 to 60.

You might also like