For KS3/4

Transcription

Python ChallengesFor KS3/4 Zi gZag Education, 2014Thi s resource may only be copied by the purchasing i nstitution on a single site and for their own use

Python ChallengeChallenge 1Write a program that: asks the user to input their age outputs 'Your age is: ' followed by theirageDifficulty: Zi gZag Education, 201411You will need to use:SequencingVariables

Python ChallengeChallenge 1: Solution#!/usr/bin/python3#Function that can be used to ask each questiondef ask(q,s):answer int(input(questions[0][q]))if answer questions[1][q]:s s 1return sprint("----MATHS QUIZ----\n")print("----SCORES----")#Creates the scores.txt file if it doesn't existfile open("scores.txt", "a")file.close()#Opens the file in read-only modefile open("scores.txt", "r")#Loop that prints each line from the file to thescreenfor line in file:print(line)file.close() Zi gZag Education, 20141

Python Challenge2Challenge 2Write a program that: asks the user to input two numbers calculates the average outputs the resultTip: To calculate the average of two numbers you needto add them together and divide them by two.Difficulty: Zi gZag Education, 20141You will need to use:SequencingVariables

Python ChallengeChallenge 2: Solution#!/usr/bin/python3print ("----AVERAGE CALCULATOR----")#Asks the user to input two numbers and stores themin the num1 and num2 variablesnum1 int(input("Enter your first number: "))num2 int(input("Enter your second number: "))#Calculates the average of the two numbersaverage (num1 num2)/2#Outputs the value stored in the average variable tothe screenprint ("The average is:",str(average)) Zi gZag Education, 20142

Python ChallengeChallenge 3Write a program that: asks the user to input the width andheight of a rectangle calculates the area outputs the result3You will need to use:SequencingVariablesTip: Multiply the width by the height to find the area of a rectangle.Difficulty: Zi gZag Education, 20141

Python ChallengeChallenge 3: Solution#!/usr/bin/python3print ("----AREA CALCULATOR----")#Asks the user to input the width and height andstores them in variableswidth int(input("Enter the width: "))height int(input("Enter the height: "))#Calculates the area and stores it in the areavariablearea width*height#Outputs the value stored in the area variable tothe screenprint ("The area is:",str(area)) Zi gZag Education, 20143

Python ChallengeChallenge 4Write a program that: asks the user to input two numbers divides the first number by the secondnumber outputs the resultDifficulty: Zi gZag Education, 201414You will need to use:SequencingVariables

Python ChallengeChallenge 4: Solution#!/usr/bin/python3print ("----DIVIDER----")#Asks the user to input two numbers and stores themin two variablesnum1 int(input("Enter your first number: "))num2 int(input("Enter your second number: "))#Divides the value in the num1 variable by the valuein the num2 variableresult num1/num2#Outputs the value stored in the result variable tothe screenprint ("The result is:",str(result)) Zi gZag Education, 20144

Python ChallengeChallenge 5Write a program that: asks the user their name asks what their favourite subject is(using their name in the question) responds to their answer by sayingthat you like that subject as wellDifficulty: Zi gZag Education, 201415You will need to use:SequencingVariables

Python ChallengeChallenge 5: Solution#!/usr/bin/python3#Asks the user to input their name and stores it ina variablename input("Enter your name: ")#Asks the user to input their favourite subject,using the value stored in the name variable in thequestionsubject input("What is you favourite subject" name "? ")#Outputs the value stored in the food variableprint ("I like",subject,"as well!") Zi gZag Education, 20145

Python ChallengeChallenge 6Write a program that: asks the user their name if it is the same as your name, outputs'You’re cool', otherwise outputs 'Niceto meet you'Difficulty: Zi gZag Education, 201426You will need to use:SelectionVariables

Python ChallengeChallenge 6: Solution#!/usr/bin/python3#Asks the user to input their name and stores it ina variablename input("Enter your name: ")#Asks the question: is the value in name equal to"Bob"?if name "Bob":#If the answer to the question is yes this lineis outputtedprint ("You're cool")else:#Otherwise this line is outputtedprint ("Nice to meet you") Zi gZag Education, 20146

Python ChallengeChallenge 7Write a program that: asks the user how long on averagethey spend watching TV each day if it is less than 2 hours, outputs ‘Thatshouldn’t rot your brain too much’; if itis less than 4 hours per day, outputs‘Aren’t you getting square eyes?’;otherwise outputs ‘Fresh air beatschannel flicking’Difficulty: Zi gZag Education, 201427You will need to use:SelectionVariables

Python ChallengeChallenge 7: Solution#!/usr/bin/python3#Asks the user to input a value and stores it in thetime variabletime int(input("How many hours on average do youspend watching TV each day?: "))#If statement that outputs different stringsdepending on the value stored in#the time variableif time 2:print ("That shouldn’t rot your brain too much")elif time 4:print ("Aren’t you getting square eyes?")else:print ("Fresh air beats channel flicking") Zi gZag Education, 20147

Python ChallengeChallenge 8Write a program that: converts and outputs marks intogrades, using the following data:Greater than or equal to 75AGreater than or equal to 60BGreater than or equal to 35CLess than 35DDifficulty: Zi gZag Education, 201428You will need to use:SelectionVariables

Python ChallengeChallenge 8: Solution#!/usr/bin/python3print ("----GRADE CALCULATOR----")#Asks the user to input the mark and stores it inthe mark variablemark int(input("Enter the mark: "))#If statement that outputs different stringsdepending on the value stored#in the mark variableif mark 75:print ("Grade: A")elif mark 60:print ("Grade: B")elif mark 35:print ("Grade: C")else:print ("Grade: D") Zi gZag Education, 20148

Python ChallengeChallenge 9Write a program that: asks the user to name one of theOlympic Values (Respect, Excellenceand Friendship) if they correctly name one, output'That’s correct‘, otherwise output 'Tryagain'Difficulty: Zi gZag Education, 201429You will need to use:SelectionVariables

Python ChallengeChallenge 9: Solution#!/usr/bin/python3#Asks the user to input one of the Olympic Valuesand stores it in a variablevalue input("Name one of the Olympic Values: ")#Outputs different strings depending on whether theuser correctly#entered the name of an Olympic Valueif value "respect" or value "excellence" orvalue "friendship":print ("That's correct")else:print ("Try again") Zi gZag Education, 20149

Python ChallengeChallenge 10Write a game that: allows the user to play rock, paper,scissors against the computer must display the computer’s choiceand show the result of the gameTip: The computer’s answer must be random.Difficulty: Zi gZag Education, 2014210You will need to use:SelectionVariables

Python Challenge10Challenge 10: Solution#!/usr/bin/python3print ("----ROCK, PAPER, SCISSORS----")import random#generates a random number between 1 and 3computer random.randint(1,3)#asks the user to input their choice and stores it in a variableuser int(input("Enter yourchoice:\n1 Rock\n2 Paper\n3 Scissors\n"))#outputs the computer's moveprint("The computer has chosen",computer)#outputs a different string depending on the game outcomeif computer user:print ("Tie game")elif computer 1 and user 3:print ("Computer wins")elif computer 2 and user 1:print ("Computer wins")elif computer 3 and user 2:print ("Computer wins")else:print ("You Win!") Zi gZag Education, 2014

Python ChallengeChallenge 11Write a program that: asks the user to input a sentence calculates and outputs how manycharacters there are in the sentenceDifficulty: Zi gZag Education, 2014311You will need to use:VariablesString Manipulation

Python ChallengeChallenge 11: Solution#!/usr/bin/python3#asks the user to input a sentence and stores it inthe text variabletext input("Enter your sentence: ")#outputs the number of characters to the screenprint ("There are",len(text),"characters") Zi gZag Education, 201411

Python ChallengeChallenge 12Write a program that: asks the user to input a sentence outputs the sentence in upper case12You will need to use:VariablesString ManipulationDifficulty: Zi gZag Education, 20143

Python ChallengeChallenge 12: Solution#!/usr/bin/python3#asks the user to input a sentence and stores it inthe text variabletext input("Enter your sentence: ")#outputs the sentence in upper caseprint (text.upper()) Zi gZag Education, 201412

Python Challenge13Challenge 13Write a program that: asks the user to input a sentence asks the user to input: the word they want to replace the word they want to replace it with outputs the new sentenceDifficulty: Zi gZag Education, 20143You will need to use:VariablesString Manipulation

Python ChallengeChallenge 13: Solution#!/usr/bin/python3#asks the user to input a sentence and stores it in thetext variabletext input("Enter your sentence: ")word1 input("Enter the word you want to replace: ")word2 input("Enter the word you want to replace it with: ")#outputs the sentence with the original word replacedwith the new wordprint (text.replace(word1,word2)) Zi gZag Education, 201413

Python ChallengeChallenge 14Write a program that: asks the user to input a sentence outputs the number of times the word'the' occurs in itDifficulty: Zi gZag Education, 2014314You will need to use:VariablesString Manipulation

Python ChallengeChallenge 14: Solution#!/usr/bin/python3#asks the user to input a sentence and stores it in thetext variabletext input("Enter your sentence: ")#outputs the number of times "the" occurs in the sentenceprint ("'The' appears",text.count("the"),"times") Zi gZag Education, 201414

Python ChallengeChallenge 15Write a program that: asks the user to input a sentence outputs the sentence in lower case15You will need to use:VariablesString ManipulationDifficulty: Zi gZag Education, 20143

Python ChallengeChallenge 15: Solution#!/usr/bin/python3#asks the user to input a sentence and stores it in thetext variabletext input("Enter your sentence: ")#outputs the sentence in lower caseprint (text.lower()) Zi gZag Education, 201415

Python Challenge16Challenge 16Write a program that: outputs all numbers between 1 and 10You will need to use:VariablesRepetitionTip: You must use a For Loop for this challenge.Difficulty: Zi gZag Education, 20143

Python ChallengeChallenge 16: Solution#!/usr/bin/python3#a loop that outputs numbers from 1 to 10for x in range(1,11):print(x) Zi gZag Education, 201416

Python Challenge17Challenge 17Write a program that: outputs all odd numbers between1 and 99You will need to use:VariablesRepetitionTip: You must use a For Loop for this challenge.Difficulty: Zi gZag Education, 20143

Python ChallengeChallenge 17: Solution#!/usr/bin/python3num 1#a loop that outputs the odd numbers from 1 to 100for x in range(0,50):print(num)num num 2 Zi gZag Education, 201417

Python Challenge18Challenge 18Write a program that: asks the user to input a number outputs the times table for thatnumberTip: You must use a For Loop for this challenge.Difficulty: Zi gZag Education, 20143You will need to use:VariablesRepetition

Python ChallengeChallenge 18: Solution#!/usr/bin/python3print ("----TIMES TABLE GENERATOR----")#asks the user to input a numbernum int(input("Enter a number: "))#this loop generates the times table for the numberstored in the num variablefor x in range(0,10):print (str((x 1)*num)) Zi gZag Education, 201418

Python ChallengeChallenge 19Write a program that: asks the user to input a number outputs the times table for thatnumber starts again every time it finishes19You will need to use:VariablesRepetitionTip: You must use a For Loop and a While Loop for this challenge.Difficulty: Zi gZag Education, 20143

Python ChallengeChallenge 19: Solution#!/usr/bin/python3print ("----TIMES TABLE GENERATOR----")#a loop that will continually repeat the programwhile True:#asks the user to input a number and stores itin the num variablenum int(input("\nEnter a number: "))#a loop that outputs the times table for thenumber stored in the num variablefor x in range(0,10):print (str((x 1)*num)) Zi gZag Education, 201419

Python ChallengeChallenge 20Write a program that: asks the user to input a number andrepeats until they guess the number 7 congratulate the user with a ‘WellDone’ message when they guesscorrectlyDifficulty: Zi gZag Education, 2014320You will need to use:VariablesRepetition

Python ChallengeChallenge 20: Solution#!/usr/bin/python3print ("----GUESS THE NUMBER----")guess 0#Loops until the user guesses the number 7while guess! 7:guess int(input("Enter your guess: "))if guess! 7:print("Incorrect. guess again")print ("Well done!") Zi gZag Education, 201420

Python ChallengeChallenge 21Write a program that converts betweencentimetres, and inches and vice versa, by: asking the user to input a number asking the user to choose betweenconverting from centimetres to inches or frominches to centimetres calculating and outputting the result usingfunctionsTip: 1 inch 2.54 cm1 cm 0.393700787 inchesDifficulty: Zi gZag Education, 2014321You will need to use:VariablesSelectionFunctions

Python Challenge21Challenge 21: Solution#!/usr/bin/python3print ("----INCHES/CM CONVERTER----")#Converts inches to cmdef intocm(n):convert n*2.54print(n,"inches ",convert,"cm")return#Converts cm to inchesdef cmtoin(n):convert n*0.393700787print(n,"cm ",convert,"inches")return#Asks the user to input a number and select the type ofconversion they want to performnum int(input("Enter the number you want to convert: "))unit int(input("Choose an option:\n1 INCHES toCENTIMETRES\n2 CENTIMETRES to INCHES\n"))#If statement calls the appropriate functionif unit 1:intocm(num)elif unit 2:cmtoin(num) Zi gZag Education, 2014

Python ChallengeChallenge 22Write a program that: asks the user for the distance (in metres) asks the user for the time in secondsthat a journey was completed in calculates and outputs the averagespeed using a functionTip: Speed Distance / TimeDifficulty: Zi gZag Education, 2014322You will need to use:VariablesSelectionFunctions

Python ChallengeChallenge 22: Solution#!/usr/bin/python3print ("----AVERAGE SPEED CALCULATOR----")#Function to calculate average speeddef calculate(d,t):speed d/tprint("The average speed is:",speed,"m/s")return#User input of distance and timedistance int(input("Enter the distance travelled inmetres: "))time int(input("Enter the time it took to completethe journey in seconds: "))#Calls the calculate function, passing the distanceand time variablescalculate(distance,time) Zi gZag Education, 201422

Python Challenge23Challenge 23A gardener needs to buy some turf for a projectthey are working on. The garden is rectangularwith a circular flower bed in the middle.Write a program that: asks the user for the dimensions of the lawnand the radius of the circle (in metres) uses a function to calculate and outputthe amount of turf neededTip: Circle area Pi x Radius2Difficulty: Zi gZag Education, 20144You will need to use:VariablesSelectionFunctions

Python Challenge23Challenge 23: Solution#!/usr/bin/python3import mathprint ("----TURF CALCULATOR----")#Function to calculate the amount of turf requireddef calculate(w,l,r):lawnArea w*lbedArea math.pi*r*rturf lawnArea-bedAreaprint("You need",turf,"square metres of turf")return#User input of width and length of the lawn and theradius of the bedwidth int(input("Enter the width of the lawn: "))length int(input("Enter the length of the lawn: "))radius int(input("Enter the radius of the flower bed: "))#Calls the calculate function, passing the width,length and radius variablescalculate(width,length,radius) Zi gZag Education, 2014

Python Challenge24Challenge 24Write a function that takes two numbers.The first number indicates the number ofspaces that should be displayed and thesecond indicates the number of Xs thatshould be displayed. These should bothbe displayed on the same line.Now write another function that makesmultiple calls to your first function anddraws a picture with Xs.Difficulty: Zi gZag Education, 20144You will need to use:VariablesSelectionRepetitionFunctions

Python Challenge24Challenge 24: Solution#!/usr/bin/python3#Function to draw a line of the imagedef drawLine(s,x):for i in range(0,s):print(" ", end ""),for i in range(0,x):print("X", end ""),print()return#Function to call the drawLine function to draw imagedef (4,3)returndrawPicture() Zi gZag Education, 2014

Python ChallengeChallenge 25Write a sign-up program for an afterschool club; it should ask the user for thefollowing details and store them in a file: First NameLast NameGenderFormDifficulty: Zi gZag Education, 2014425You will need to use:VariablesSelectionFile Handling

Python ChallengeChallenge 25: Solution#!/usr/bin/python3print("----CLUB SIGN UP----")#User enters their detailsfirst input("Enter your first name: ")last input("Enter your last name: ")gender input("Enter your gender: ")form input("Enter your form: ")#Opens the file or creates it if it doesn't alreadyexistfile open("signup.txt", "a")#Records the user's details in the filefile.write("\nFirst name: " first ", Last name:" last ", Gender: " gender ", Form: " form)#Closes the filefile.close() Zi gZag Education, 201425

Python Challenge26Challenge 26Write a maths quiz with three questions.It must ask the user to input their name atthe start.At the end it should display a messageinforming the user of their score.Write a function that saves the user’sname and quiz result in a text file.Difficulty: Zi gZag Education, 20144You will need to use:VariablesSelectionFunctionsFile Handling

Python ChallengeChallenge 26: Solution#!/usr/bin/python3def saveScore(n,s):#Opens the file or creates it if it doesn'talready existfile open("scores.txt", "a")#Records the user's score in the filefile.write("Name: " n ", Score: " str(s) "\n")#Closes the filefile.close()returnprint("----MATHS QUIZ----")#Variable setupname input("Enter your name: ")score 0#Question 1answer int(input("What is 3 x 5?: "))if answer 15:score score 1. Zi gZag Education, 201426

Python ChallengeChallenge 26: Solution.#Question 2answer int(input("What is 10 13?: "))if answer 23:score score 1#Question 3answer int(input("What is 10 / 2?: "))if answer 5:score score 1#Prints the score to the screenprint("Your score is: ",score)#Calls the saveScore function and passes the nameand score variablessaveScore(name,score) Zi gZag Education, 201426

Python ChallengeChallenge 27Extend your maths quiz program fromChallenge 20 by including a list of thescores of people that have taken thequiz before.27You will need to use:VariablesSelectionFile HandlingDifficulty: Zi gZag Education, 20145

Python Challenge27Challenge 27: Solution#!/usr/bin/python3def saveScore(n,s):#Opens the file or creates it if it doesn't already existfile open("scores.txt", "a")#Records the user's score in the filefile.write("Name: " n ", Score: " str(s) "\n")#Closes the filefile.close()returnprint("----MATHS QUIZ----\n")print("----SCORES----")#Creates the scores.txt file if it doesn't existfile open("scores.txt", "a")file.close()#Opens the file in read-only modefile open("scores.txt", "r")#Loop that prints each line from the filefor line in file:print(line). Zi gZag Education, 2014

Python ChallengeChallenge 27: Solution.#Variable setupname input("Enter your name: ")score 0#Question 1answer int(input("What is 3 x 5?: "))if answer 15:score score 1#Question 2answer int(input("What is 10 13?: "))if answer 23:score score 1#Question 3answer int(input("What is 10 / 2?: "))if answer 5:score score 1#Calls the saveScore function and passes the variablessaveScore(name,score) Zi gZag Education, 201427

Python ChallengeChallenge 28Write a random name generator thatasks for the user to input 5 names, storesthem in an array and then outputs oneof them at random.28You will need to use:VariablesRepetitionArraysDifficulty: Zi gZag Education, 20145

Python ChallengeChallenge 28: Solution#!/usr/bin/python3import randomprint("----RANDOM NAME GENERATOR----")#Creates an empty arraynames []#Asks the user to enter 5 names and adds them tothe arrayfor i in range(1,6):names.append(input("Enter name " str(i) ": "))#Generates a random number between 1 and 5num random.randint(0,5)#Outputs the randomly chosen nameprint(names[num],"has been chosen") Zi gZag Education, 201428

Python Challenge29Challenge 29Write a program that allows the user tocreate and store a checklist for a holiday.It should start by asking them thedestination of the holiday, how manythings they need to pack and how manytasks they need to complete to prepare.The user should then be able to entereach item they need to pack and eachtask they need to complete.Difficulty: Zi gZag Education, 20145You will need to use:VariablesRepetitionArraysFile Handling

Python Challenge29Challenge 29: Solution#!/usr/bin/python3print("----HOLIDAY CHECKLIST----")#Creates the empty arrayspackList []tasks []#Asks the user to input the holiday infoname input("Enter the destination of the holiday: ")itemsNum int(input("Enter the number of items youneed to pack: "))tasksNum int(input("How many tasks do you need tocomplete to prepare for the holiday?: "))#Loop to store the packing listfor i in range(0,itemsNum):packList.append(input("Enter the name of item" str(i 1) ": ")). Zi gZag Education, 2014

Python Challenge29Challenge 29: Solution.#Loop to store the tasksfor i in range(0,tasksNum):tasks.append(input("Enter task " str(i 1) ": "))#Stores the checklist in a filefile open((name " checklist.txt"), "w")file.write("Destination: " name "\nPacking List: \n")for item in packList:file.write(item "\n")file.write("Tasks: \n")for item in tasks:file.write(item "\n")file.close()print("Your list has been saved") Zi gZag Education, 2014

Python ChallengeChallenge 30Improve your maths quiz from Challenge20 and 27 by storing all the questionsand possible answers in a twodimensional array.Write a function that can be reused toask each of the questions.30You will need to use:Global VariablesRepetitionFunctions2D ArraysDifficulty: Zi gZag Education, 20145

Python ChallengeChallenge 30: Solution#!/usr/bin/python3#Function that can be used to ask each questiondef ask(q,s):answer int(input(questions[0][q]))if answer questions[1][q]:s s 1return sprint("----MATHS QUIZ----\n")print("----SCORES----")#Creates the scores.txt file if it doesn't existfile open("scores.txt", "a")file.close()#Opens the file in read-only modefile open("scores.txt", "r")#Loop that prints each line from the file to thescreenfor line in file:print(line)file.close(). Zi gZag Education, 201430

Python ChallengeChallenge 30: Solution.#Variable setupname input("Enter your name: ")score 0questions [["What is 3 x 5?: ", "What is 10 13?:", "What is 10 / 2?: "],[15,23,5]]#Loop to call ask function to ask each questionfor i in range(len(questions) 1):score ask(i,score)#Opens the file in append modefile open("scores.txt", "a")#Prints the score to the screenprint("Your score is:",score)#Records the user's score in the filefile.write("Name: " name ", Score:" str(score) "\n")#Closes the filefile.close() Zi gZag Education, 201430

ZigZag Education, 2014 This resource may only be copied by the purchasing institution on a single site