Python Work
Python Work
Class: 10B
VARIABLES, INPUT
AND OUTPUT
1. Display the following on 3 separate lines:
This is my first program.
It shows messages
Sometimes on different lines
Paste your code below:
Print(name*5) would
work too.
6. Create a program that ask the user for their favourite food.
Display “I also like”, food. Food should be replaced with the
user’s answer.
Paste your code below:
7. Ask for a user’s name and age. Display “your name is”, name,
“and you are”, age, “year old”.E.G:
Paste your code below:
Data Types
• String holds alphanumeric data as text.
• Integer holds whole numbers.
• Float/Real holds numbers with a decimal point.
• Character holds a single, alphanumeric character.
• Boolean holds either ‘True’ or ‘False’.
Age Integer
Name String
Weight Float
Price Float
Is 5 == 5 Boolean
9. Ask the user for 2 numbers then divide the first number by the
second number. Display the answer.
Paste your code below:
10. Asks for the width of a rectangle. Asks for the length of a
rectangle. Calculates the area of a rectangle. Print the area of a
rectangle.
Paste your code below:
11. Asks 2 users for their weight, calculate the average weight of
the 2 users.
Paste your code below:
ARITHMETIC OPERATORS
12. Complete the following table:
Arithmetic operator name Arithmetic operator symbol
Addition +
Subtraction -
Multiplication *
Division /
Exponent ^^
Modulus %
Floor Division //
13. Create a variable x with a value of 5. Create a variable y
with a value of 3. Create a variable z with a value 10. Multiply
three numbers together and store them in a variable called
answer. Comment on the code.
Paste your code below:
14. Alex has £20. Spending:£5 on pens. £3 on pencils. Total
amount left?
Demonstrate this example using 4 variables and arithmetic
operators. Comment on your code.
Paste your code below:
15. Ask how many apples the user wants. Ask how many
people the user will share the apples with. Find out how many
apples will remain if you share the apples equally. Hint: use
modulus %.
Paste your code below:
16. Asks for the home team name. Asks for the opponent team
name. Asks for the number of goals scored by the home team.
Asks for the number of goals scored by the opposition team.
Calculates the goal difference for the home team.
Paste your code below:
RELATIONAL OPERATORS
KEYWORDS: Equal to, not equal to, greater than, less than
Relational operators
Question True/False
5 == 3 false
2 != 5 true
5>6 false
8<2 false
2!=2 false
7==7 true
1>=1 true
7>=2 true
9<=2 true
9<=9 true
18. Use the code on the previous slide to complete the following
table:
Index 0 1 2 3
Character m a r k
name = "mark"
Up to but not
print(name[0:2])
included
Starting position
Substring
name = input("Enter a name")
print(name[0]) #displays the first character.
You can change the steps that each loop around will change the
counter value by
for y in range(100,0,-1) :
print(y)
while x > 7:
this code will be repeated
so will this code
This code will not be repeated
Note that indenting (using the TAB key) is used to decide what
code is inside the while statement.
22) Use a while loop to create the 2 times table up to 100. Display “You
have finished” when you get to the number 100.
Paste your code below:
23) Display “Hey” and “Bye” on separate lines 1000 times using a while
loop.
Paste your code below:
24) Ask the user to input 4 names. Display “You have entered 4 names”
when the user inputs all 4 names.
Paste your code below:
25) Ask the user to input a password. If password is correct, display correct
password. If password is incorrect, display incorrect password. Display
“LOCKED” after 4 attempts.
Paste your code below:
26) Ask the user to input a password. If password is correct, display correct
password. If password is incorrect, display incorrect password. The program
will loop until the correct answer is entered. Hint: use attempts = False
Paste your code below:
27)
1- Ask the user for a username.
2- While the username is less than 8 characters long,
3-Display “Invalid username, enter another username”) and force the user to
enter another username.
4- Display “your username has been accepted” if the username is at least 8
characters long.
5- Ask the user for a password.
6- While the password is less than 8 characters long OR greater than 15
characters long,
7- display “Invalid password, enter another password”) & force the user to
enter another password.
Display “your password has been accepted” if the password is between 8 and
15 characters long.
Hints: use while len(password) < 8 or len(password) > 15:
Paste your code on the next slide:
Paste your code below:
28) Write a program that allows the user to type in a number. This number
will then be added onto a total, which will be displayed. Continue to ask for
a number until the total is over 100.
Paste your code below:
RANDOM NUMBER PICK
import random
x = random.randint(1,100)
print(x)
1D ARRAYS
Theory: Understanding Arrays
array = ["saw","batman","superman"]
for x in array:
print(x)
We can loop through an array using a for loop.
array = ["saw","batman","superman"]
film = input("Enter a film to see if it's in the
array")
for i in range(len(array)):
if film == array[i]:
print ("found")
34) Write a program that checks whether an element occurs in a list. For
example: array = [4, 6, 7, 8, 10]. Which number would you like to find? 10
Found!
Paste your code below:
Append means add #Declare an empty array
(something) to the end. student = [ ]
score = []
for i in range (__):
number=______________
score.append(____)
option = _________________
total = score[0]+______________
if option == "total":
print(_____)
elif option == "average":
print(______)
else:
print("Invalid option")
38.6) Create a questionnaire program that asks the user for their
gender and gives the options MALE/FEMALE/QUIT. Store the
answer in an array. Keep asking the question until someone
enters QUIT. Then print out the total number of people who
answered the question, the number of males and the number of
females. Use the code on the next slide if you are struggling.
Paste your code on the next slide:
Q38.6)
males = _
females = _
storage = []
gender = ____________
storage.append(_____)
while gender.lower() == "male" or ____________________:
gender = input("Are you a male or female, or quit? ")
____________(gender.lower())
if gender.lower() == "quit":
for item in storage:
if item.lower() == _______:
males = _____ + 1
else:
if _______== "female":
females = females + ___
print(str(males) +" males")
print(str(females) +" females")
38.7) Create a program to store the names of computer games
that they play in an array. Create a simple menu system to allow
the user to either add, edit or delete a game. Also allow the user
to print the array whenever needed.
Use the code on the next slide if you are struggling.
Paste your code on the next slide:
games = [] Q38.7)
while True:
menu = input("\nDo you want to add, edit or delete a game, or print all games? ")
if _____ == "add":
newgame = input(___________)
games.append(________)
print("Game '"+newgame +"' added. ")
elif menu == "print":
print("Your games are: ")
print(_______)
elif _____ == "edit":
print("Your games are: "+str(games))
editone = input("Which one do you want to edit?")
edittext = _____("What do you want to change it to?")
games.______(editone)
games.______(edittext)
elif _____ == "delete":
print("your games are: "+str(games))
delete = input("Which game would you like to delete?")
games.______(_____)
____:
print("Invalid option")
2D ARRAYS
array = [ [3,2,1], [2,3,4], [7,5,2] ]
print(array[2][1])
print(array[0][1])
Plonker", 23,12,32]]
print(grades) # displays the list.
print(grades[1][2]) # displays 22
grades[1].append(56) # adds 56 to billy
KEYWORDS: array, element, table, assigning, identifier
39) Write a program that converts the following table into a two-
dimensional array called ‘grades’:
Student name Grade1 Grade2 Grade3
Paste your code below: Alfie Little 24 32 5
Billy Bob Junior II 22 22 53
Mark Jones 43 54 23
King Plonker 23 12 32
40) Modify Mark Jones Grade2 to 76 from the previous question. You will
need the following: grades[index][index] = 76
Paste your code below:
41) Add ‘Grade4’ to your array with the following data: You will need the
following: grades[x].append(value) Student name Grade4
Alfie Little 37
Paste your code below: Billy Bob Junior II 99
Mark Jones 32
King Plonker 42
42) Add to your previous code “question” to calculate the average for grade1,
grade2, grade3, and grade4 for Alfie Little. Display the outcome.
Paste your code below:
43) This two dimensional array holds the current level each pupil is working
at.
• Develop a program that initialises the two dimensional array. Display the
array.
• Remove Emma Baldridge from the array as she no longer attends the
school then display the array. hint: x.remove
• Add a new student “Jonathan Pierce” and his current grade as “5+”.
x.append
• Display the new array. “Alex Chadwick” “7+”
“Seema Patel” “5-”
Fill the gaps on the next slide. “Dion Scott” “6-”
“Emma Baldridge” “8”
“Gareth Wild” “8+”
43)
Fill the gaps.
import ______
teamList = _____("team.txt", "__")
data = teamList._______()
randomChoice= random._______(____)
teamName =[]
player =[]
for lines in data:
split = lines._____(',')
teamName.______(split[0])
player._______(_____[1])
teamName = teamName[_______]
letters = _______[randomChoice]
print("\nThe team is ",______)
splitLetters = letters._____(' ')
print("And the first letter of the player’s firstname and surname is")
for x in range(_____(splitLetters)):
print((______[x][_]).upper())
14. Write a program that allows the user to create and store a checklist for their
homework. Ask for pupil’s name, and create a text file using the pupil’s name.
Ask how many homeworks they need to complete. The user should then be able to
enter each homework name. Store them in a file.
Paste your code below:
Q14 Helpsheet
homework=[]
name=__________
homeworkNum=__________
for i in range(0,_____):
homework._____(input("Enter the name of homework
"+str(i+1)+": "))
file = _____((name+".txt"), "_")
for item in ______:
file.write(_____+"\n")
file._____()
Procedures
• A subroutine or a subprogram is a
named self-contained section of code
that performs a specific task.
• Parameters: Specific variables used to
pass values into a sub program.
• Arguments: Actual values that the
parameters take when the sub program
is called.
KEYWORDS: Procedure, function, subroutine, subprogram, return, parameter
PROCEDURE
Function/procedure
def is a name
command
Ask the
which allows
def firstSubroutine(): user to
you to define a
name=input("what is your name") input a
new function / print(name) name.
procedure. firstSubroutine()
firstSubroutine()
Calls the Displays
procedure. This the user’s
will run line 2 answer.
and 3.
KEYWORDS: Procedure, arguments, subroutine, subprogram, parameter
PROCEDURE
Function/procedure
name. Parameter.
def is a
command def welcome(name):
which allows print(“Welcome to school“ , name )
Displays
welcome("Alex")
you to define a welcome to
welcome(“Tom")
new function. school + the
value of the
Calls the argument.
procedure. This
will run line 2. Argument.
Parameters
def calculate(num,num2):
print(num * num2)
calculate(2,4) Local
Variable
Global
variable
15. Create a procedure that will ask the user for their name. Display the name.
def calculate(num,num2):
Stores the
value
answer = num * num2
returned return answer
in the
function
output = calculate(2,4) answer returned to
the main program.
print(output) Local
Variable
Arguments, the values 2 and 4 are passed into num and num2.
Parameter passing
You can return multiple values.
Parameters
def calculate(num,num2):
Stores the
value
message = "your answer is"
returned answer = num * num2
in the Message & answer
function
return message, answer returned to the main
output = calculate(2,4) Variable
Local program.
print(output)
____ function(currentage,year):
futureAge= _____ + _____
_____ futureAge
age = ___________
ask = _____("Would you like to know how old you will be in 18 year in 12"))
num18= _____(age,18)
num12= function(___,____)
if ask == 12:
print(_____)
elif ____== 18:
print(_____)
___:
___("invalid option")
22. Create a function to return the value of 3 numbers multiplied by each other. Ask
the user to input these numbers. Use 3 arguments and 3 parameters.
Paste your code below:
Validation: to check that the data entered by a user or from a file
meets specified requirements. Validation does not check if the
data is accurate.
1. Range check
2. Valid choice check
3. Length check
4. Presence check
5. Lookup check
6. Validation
Range check
validnum = False
lengthokay = False
E Mr_Suffar
That is not valid. Try again.
Username recognised.
D