Python Challenges Mr Petford.

Similar presentations


Presentation on theme: "Python Challenges Mr Petford."— Presentation transcript:

1 Python Challenges Mr Petford

2 Printing, Variables and Inputs

3 Print command Task 1e * ** *** **** ***** Task 1f Task 1a
Write a program which displays HELLO WORLD Task 1b Change the program so it says Pleased to meet you. Task 1c Write a program that says: This is a computer program that prints on several lines Task 1d My Name Is . Ishy Hanif Task 1e * ** *** **** ***** Task 1f * * * * * * Task 1g * ** *** **** *****

4 Variables – Able to learn how variables are used to store a value.
Task 2d name='Bob' name=name+'by' print('Hello '+name) Task 2e name=name+name Task 2f Complete the following program so it uses the variables to print out the cat sat on the mat. Remember you will need to add spaces. E.g. word1='the' word2='cat' word3='sat' word4='on' word5='mat’ Task 2a Copy and run the following program: name='Bob' print('Hello '+name) Task 2b Language = ‘python’ I am learning to program in Python Task 2c name='Liz'

5 Inputs name=input('What is your name?') print('Hello '+name)
Task 3a Write a program that asks for the town you live in and then replies I love visiting [town name] e.g. Where do you live? London I love visiting London Task 3b Write a program that asks for your first name, then asks for your last name and finally greets you with your full name. What is your first name? John What is your last name? Smith Hello John Smith Task 3c Write a program that asks for your name then prints it out 5 times What is your name? Trevor Trevor Trevor Trevor Trevor Trevor Task b3d Create a dialogue asking user their name, age, what school they attend, where they live, what they like eating, favourite car, etc and output this information a their CV

6 Calculations – Able to learn how different operators are used in python.
Task 4a Copy and run the following program print(1+6) print(7-5) print(3*9) print(7/2) Print (7//3) Print(10%3) Task 4b Try changing the calculations to new ones. We can put the results of calculations into variables. These variables will not be string but integer (whole numbers) or float (decimal). a=10 b=2 c=a/b print(c) Task 4c Complete this program so it uses addition on the two variables make c equal to 15 then prints it. a=7 b=8 c= [REMAINDER OF PROGRAM HERE] Task 4d 4**2 8**2 Task 4e Pie = 3.14 Radius = 3 Area = pie x radius²

7 Quotation Task 1 - Uppercase Text =( “hello world”) Print(text.upper()) Task 2 - Lowercase Text1= (“HELLO WORLD”) Task 3 - Title Text2= (“this is my world”)

8 Data Types

9 Data type able to understand how data types work in python
Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole numbers. (e.g. 1, 78, 0 and -54) Float - Decimal numbers (e.g , , -6.3). Boolean - True or False

10 Data type Task 1 - Copy and run the following program.
a=input('Enter number 1:') b=input('Enter number 2:') c=A+b print('Adding your numbers together gives:'+c) What is wrong with this program? How you will fix it ? (hint: data types) Task 5b - Write a program that asks for a length and width and outputs the area of a rectangle. Please enter width: 9 Please enter length: 5 The area is: 45

11 Data type Task 5c – using float values
Write a program that asks you for the radius and height of a cylinder then calculates the volume and surface area.

12 IF, Elif, Else

13 Selection with IF Sometimes we only want a program to execute code under certain circumstances. We call this selection. The most commonly used way of doing this is using if. Here we say if a condition is true or false (Boolean Logic) execute some code. First we need to make sure we are happy what a condition is. A boolean condition is one that can have only two values true or false.

14 Boolean values

15 Task 1: What happens? Task 1a
Find yourself using the decision tree (on the next slide) and write down all of the decisions you had to make to get there. Task 1b There are 3 types of Boolean Decisions on the Decision Tree: (Fill in the missing two) Yes / No Boolean Logic.

16 How old are you? <=13 You cannot take the quiz, sorry! >=13 Are you a Male or Female? Male Female Do you like Football? Do you have long hair? Yes Yes No Why not? Do you watch I’m a Celebrity? Do you Support Wolves? No Me neither, It gets in the way! Yes Yes Good, me too! My favourite player is Danny Batth. Good, me too! Foggy is my favourite. Why not? Why not?

17 Task 2: Examples of IF statements
Task 2a – copy this program and write a sentence explaining what happens letter = 'a' if letter=='a': Print('This prints if letter is a') Task 2b – copy this out and explain what happens We can add as many statements we want inside the if. All must be indented. if lettter=='a': print('This prints if letter is a') print('This prints as well) Task 2c – explain what happens When we want to stop the if we remove the indentation. letter = 'a’ if letter='a' print('This prints if letter is a') print('This prints as well') Print('This prints out whatever the letter is')

18 Task 3: If – elif – else Task 3 – Add an input to the start of this that asks the user to enter a letter. letter= Insert an input here. if letter=='a': print('This prints if letter is a') print('This prints as well') Elif letter=='b': print('This prints if the letter is b') else print('This prints if the letter is neither a nor b) print('This prints out whatever the letter is')

19 Task 4: Practising if statements
Task 4a - Copy and run the code below. print('What is the capital of France?') city = str(input()) if city== 'Paris': print('Well done') elif city=='Lyon': print('Right country, wrong city') elif city=='F': print('Terrible joke and wrong answer.') else: print('Sorry wrong answer') Task 4b Change the question so that it asks for your age and prints out whether this is correct. You will need to use the correct datatype. Task 4c Change the code so that it works out how many days old you are (to the nearest year) and prints this along with the answer. Hint: Look at your solution to the Time in lesson challenge.

20 More complex if statements
Task 5 – Add #comments to this to show what happens at each stage. x=int(input('Enter a number between 1 and 100: ')) if x>=1 and x<=100: print('You have entered a valid number') else: print('Your number is not valid')

21 Task 6: print('How old are you?')) Age = int(input() if Age== ‘15' print(‘You’re too old to be in this class') elif age=<12: print(‘You’re too young to be in the class') elif Age=>13: print(‘Welcome to Computer Science!') else: print(‘Uhhhhhh, wrong.') The code to the right does not work. There are a total of 6 errors, fix them and #comment your solution to show what happens at each stage.

22 Task 7 Create a program that first asks for your sex and then asks for your age. It should print out your Age and your Sex and the recommended hours you should spend sleeping! Male <10: 10 Hours 10-20: 8 Hours 20+: At least 6 Hours Female 10-20: 9 Hours 20+: At least 7 Hours Hint: You will need to use an IF statement that checks Sex and Age: If sex == something and age =< something.

23 Extension Task 1 Create a game of SNAP. You will need to input 2 numbers and if they are the same it will output ‘Snap’ if they are not the same it will output ‘Better Luck Next Time’

24 Extension Task 2 The grade boundaries for a test are: U-0 D – 40
C – 50 B – 60 A – 70 Write a program that asks for a name and then a mark and then prints their name, mark and what grade their mark is worth.

25 Count Controlled (FOR) Loops

26 FOR Loops Theory “In computer science a FOR loop is a programming language statement which allows code to be repeatedly executed. A FOR loop is classified as an iteration statement.” FOR Loops repeat for a set number of times FOR loopCounter in range (10): print(loopCounter) Hint: Remember the computer starts counting at 0, so the 10th number is 9 The program underneath the FOR loop is repeated as many times as are set, as long as they are indented. The FOR Loop is closed (finished) by removing the indent

27 What Happens when Task 1a Run these pieces of code and write a sentence to describe what happens. for a in range (10): print(a) for a in range (1, 10): print(a) Task 1b for a in range (1, 11,2): print(a) for a in range (1, 11,2): The 1 tells the loop: The 11 tells the loop: The 2 tells the loop:

28 FOR Loops Task 2b Write a program that displays Task 2a Write a program that displays ‘Hello World’ 5 times on 5 separate lines using a FOR loop Task 2b Write a program that says ‘Hello World’ 5 times on 5 separate lines. Hello World

29 Looping Variables Task 3a
Write a program that stores ‘I am Looping’ in a variable and repeats it 5 times Task 3b Change the program so that it repeats your name Task 3c Change the program so that it asks you what your name is using an input.

30 Counting in a Loop Copy and run the following program Task 4a
for loopCounter in range(10): print(loopCounter) You can be a bit more specific with your loop by setting a start and an end number: for loopCounter in range(5,10): for loopCounter in range(0,10,-2): Task 4a Write a program that Counts up from 0 to 50 in 2s, 5s and 10s Write a program that Counts down from 0 to 50 in 5s Task 4c Write a program that Counts from 0 to 50 in increments of an inputted number Hint: You will need to set up a variable for ‘increments’ for loopcounter in range (0,51,increments): print(loopcounter)

31 Breaking a Loop Remember that Loops are closed (or finished) by removing the indent Copy and run the following program for loopCounter in range (1,4): print(loopCounter) print(“Finished”) Task 5a Write a program that displays: 1 Potato 2 Potato 3 Potato 4 5 Potato 6 Potato 7 Potato More! Task 5b Write a program that displays: 2 4 6 8 Who do we appreciate? Your Name!

32 Looping Calculations Task 6a Task 6b
Copy and run the following program: times = int(3) for loopCounter in range(1,11): print(loopCounter, " x ", times, " = ",loopCounter * times) Task 6a Write a program that prints the 5 times table Task 6b Write a program that prompts for an integer (whole number) and prints the correct times table (up to 10x)

33 Strings Task 7a Write a program that allows you to type in a sentence, which is printed in uppercase, lowercase, title case, capitalized, no spaces and swapped case. Hint: See Python Tasks in K:/Year-10/CS (Slide 6) Task 7b Write a program that allows you to type in your name with a mixture of upper and lower case, but it prints it out correctly.

34 Debugging Code Task 8

35 Working with Numbers Task 9a
Create a program that will ask ‘How many minutes have you been in lesson today?’ and will print out how many minutes and seconds you have been in? (2 minutes = 2 * 60) Task 9b Create a program that will work out the area of any sized square, (length x width) Task 9c Create a program that will work out the area of any triangle, (height x width / 2) Hint: See the Python Cheat Sheet in K:/Year-10/CS

36 IF’s Task 10a Write a program that asks for a number and checks if it can be divided by 3 to make 0, if it can print the word fizz Task 10b Write a program that asks for a number and checks if it can be divided by 5 to make 0, if it can print the word buzz Task 10c Write a program that asks for a number and checks if it can be divided by BOTH 3 and 5 to make 0, if it can print the word FizzBuzz Hint: IF number % 5 ==0 and number % 10 == 0: print(“This would print if the number is divided by 5 and 10 to make 0”)

37 FOR Loops Hint: remember the computer starts counting at 0 Task 11a
Write a program that counts from 0 to 50 in increments of 2, in even numbers only. Hint: remember the computer starts counting at 0 Task 11b Run the following code: a = ('cat', 'dog', 'frog') for x in a: print x, len(x) What is the FOR command doing? What does the x do?

38 Challenge! Copy and run the following code:
print "Welcome" c=input("How many calories have you eaten today?") s=2000-c print "You can eat", s, "calories today” This code calculates how many calories you have left to eat. Task 12 Change this code so that it asks if you are a Male (m or M) or Female (f or F) and calculates how many calories you have left to eat. Hint: The average male needs 2500 calories and the average female

39 What Happens When Run the following code: Task 13 What is the output?
sentence = ('I love programming in Python!') for x in sentence: print(x) Task 13 What is the output? How is this different from FOR Loops that print a countdown?

40 What happens IF? Task 14a What does this code do? Task 14b
Draw an Algorithm for this program using the four Flow Chart shapes we have looked at previously. Run the following code: answer = int(input("How many hours a day do you play computer games? ")) if answer =< 2: print("That seems fairly reasonable") elif answer =< 4: print("You're probably good enough by now") else: print("Put the controller down and go outside") (See FOR Loops in K:/Year-10/CS)

41 One Final Challenge Task 15
A Supermarket has agreed to start buying Fair trade Bananas from a farm in Ghana. They have agreed a price of £1 per Kilo of Bananas They have also agreed that the bananas are to be weighed at the farm and at the supermarket to make sure both companies are happy and that the weight is correct There is one major problem The Scales in Ghana only measure in kilos and the scales At the Supermarket weigh in pounds (Ibs). You have been asked to create a program that can convert kilos to pounds for the Supermarket The formula you need is 1 kilo = 2.2 pounds

42 Python Challenges Mr Petford.

43 Strings Task 1a Write a program that allows you to type in a sentence, which is printed in uppercase, lowercase, title case, capitalized, no spaces and swapped case. Hint: See Python Tasks in K:/Year-10/CS (Slide 6) Task 1b Write a program that allows you to type in your name with a mixture of upper and lower case, but it prints it out correctly.

44 Debugging Code Task 2

45 Working with Numbers Task 3a
Create a program that will ask ‘How many minutes have you been in lesson today?’ and will print out how many minutes and seconds you have been in? (2 minutes = 2 * 60) Task 3b Create a program that will work out the area of any sized square, (length x width) Task 3c Create a program that will work out the area of any triangle, (height x width / 2) Hint: See the Python Cheat Sheet in K:/Year-10/CS

46 IF’s Task 4a Write a program that asks for a number and checks if it can be divided by 3 to make 0, if it can print the word fizz Task 4b Write a program that asks for a number and checks if it can be divided by 5 to make 0, if it can print the word buzz Task 4c Write a program that asks for a number and checks if it can be divided by BOTH 3 and 5 to make 0, if it can print the word FizzBuzz Hint: IF number % 5 ==0 and number % 10 == 0: print(“This would print if the number is divided by 5 and 10 to make 0”)

47 FOR Loops Hint: remember the computer starts counting at 0 Task 5a
Write a program that counts from 0 to 50 in increments of 2, in even numbers only. Hint: remember the computer starts counting at 0 Task 5b Run the following code: a = ('cat', 'dog', 'frog') for x in a: print x, len(x) What is the FOR command doing? What does the x do?

48 Challenge! Copy and run the following code:
print "Welcome" c=input("How many calories have you eaten today?") s=2000-c print "You can eat", s, "calories today” This code calculates how many calories you have left to eat. Task 6 Change this code so that it asks if you are a Male (m or M) or Female (f or F) and calculates how many calories you have left to eat. Hint: The average male needs 2500 calories and the average female

49 What Happens When Run the following code: Task 7 What is the output?
sentence = ('I love programming in Python!') for x in sentence: print(x) Task 7 What is the output? How is this different from FOR Loops that print a countdown?

50 What happens IF? Task 8a What does this code do? Task 8b
Draw an Algorithm for this program using the four Flow Chart shapes we have looked at previously. Run the following code: answer = int(input("How many hours a day do you play computer games? ")) if answer =< 2: print("That seems fairly reasonable") elif answer =< 4: print("You're probably good enough by now") else: print("Put the controller down and go outside") (See FOR Loops in K:/Year-10/CS)

51 One Final Challenge Task 9
A Supermarket has agreed to start buying Fair trade Bananas from a farm in Ghana. They have agreed a price of £1 per Kilo of Bananas They have also agreed that the bananas are to be weighed at the farm and at the supermarket to make sure both companies are happy and that the weight is correct There is one major problem The Scales in Ghana only measure in kilos and the scales At the Supermarket weigh in pounds (Ibs). You have been asked to create a program that can convert kilos to pounds for the Supermarket The formula you need is 1 kilo = 2.2 pounds

52 Condition Controlled (WHILE) Loops

53 WHILE Loops “In computer science a WHILE loop is a programming language statement which allows code to be repeatedly executed whilst a condition is or is not true. A WHILE loop is classified as an iteration statement.” WHILE Loops repeat for a set number of times loopCounter = 1 while loopCounter <10: print(loopCounter) loopCounter = loopCounter + 1 The program underneath the WHILE loop is repeated until the condition becomes either true or false The WHILE Loop is closed (finished) by removing the indent

54 Task 1: WHILE Loops loopCounter = int(1) while loopCounter <10:
The ‘loopCounter’ variable is what datatype? This condition statement will run whilst what? loopCounter = int(1) while loopCounter <10: print(loopCounter) loopCounter = loopCounter + 1 What does this do? What does this last line do? What does this program do?

55 Task 2: Infinite Loops Visit: and answer the following questions: What is an Infinite Loop? How can you avoid an Infinite Loop?

56 Infinite Loops c) Run the following code: count = 1 while count != 100: print(count) d) The code from task c created an Infinite Loop, change it so that it doesn’t.

57 Task 3: Have a go a) Run the following code: answer = str(“pedmore”) guess = str(input(“What school do you go to?”) while guess != answer: print(“Incorrect”) guess = str(input(“What school do you go to?”) if guess == answer: print(“Correct, you may enter”) b) Change the code so that it asks you how old you are (this is an integer) and then tells you if you are correct. c) Change the code so that it stores a password which has a capital letter, number and a special character, and only allows access if the correct password is entered.

58 Task 4: Debugging Copy this table into your evidence PowerPoint and fill it in. Code What do you think will happen? Why do you think this? What actually happened? a = 1 while a != 10: print (a) a = a+1 While a = 10: a ++ While a != 10:

59 Task 5: Practice The sequence 1,4,9,16,25 is made up of square numbers: 1x1 = 1 2x2 = 4 3x3 = 9 etc. Write a program that writes out all the square numbers under 5000. Start off by writing the Pseudocode in #comments to show what you are trying to do, then build up the program slowly.

60 Task 6: Challenge! A motorbike costs £2000 and loses 10% of its value each year. Print the bike’s value each year until it falls below £1000 Hint: You will need to store the value and then change this by -10% each iteration.

61 Extension Task 7: Go tohttp:// and play the game. Draw and annotate a Flow Chart to show the Algorithm for the program behind the game.

62 Loop Challenges Mr Petford

63 WHILE Loops “In computer science a WHILE loop is a programming language statement which allows code to be repeatedly executed whilst a condition is or is not true. A WHILE loop is classified as an iteration statement.” WHILE Loops repeat for a set number of times loopCounter = 1 while loopCounter <10: print(loopCounter) loopCounter = loopCounter + 1 The program underneath the WHILE loop is repeated until the condition becomes either true or false The WHILE Loop is closed (finished) by removing the indent

64 FOR Loops Theory “In computer science a FOR loop is a programming language statement which allows code to be repeatedly executed. A FOR loop is classified as an iteration statement.” FOR Loops repeat for a set number of times FOR loopCounter in range (10): print(loopCounter) Hint: Remember the computer starts counting at 0, so the 10th number is 9 The program underneath the FOR loop is repeated as many times as are set, as long as they are indented. The FOR Loop is closed (finished) by removing the indent

65 Task 1: Fizz! Run the following code: for num in range(1,52): if num % 7 == 0: numseven = num/7 print(num,'=', numseven, 'x Seven') b) Modify the code to print ‘Fizz’ when the number is perfectly divisible by 3

66 Task 2: Buzz a) Create a program that prints ‘Buzz’ when the number is perfectly divisible by 5 b) Create a program that prints ‘Fizz’ when the number is perfectly divisible by 3 and ‘Buzz’ when the number is perfectly divisible by 5

67 Task 3: FizzBuzz a) Create a program that prints ‘FizzBuzz’ when the number is perfectly divisible by 3 and 5

68 Task 4: Make the game. Challenge! Write a program that prints Fizz when the number is divisible by 3, FizzBuzz when the number is divisible by 5 and FizzBuzz when the number is divisible by 3 and 5. Hint: Check that 30 displays FizzBuzz.

69 Extension If it did not display FizzBuzz at 30 this is probably because 30 is divisible by 3, so the first IF statement runs. To solve this we have to print a ‘message’ variable, and we have to use the IF statement to add to the message variable. There is a solution on the shared area. (K:\ICT\Year-10\CS\Mr Petford). Copy and paste this solution into your work and add #comments on what it is doing. Create the algorithm for the ‘msg’ variable for num in range(1,52): msg = '' if num % 3 == 0: msg += 'Fizz' if num % 5 == 0: msg += 'Buzz' if not msg: msg += str(num) print (num,msg)

70 Extension Task 7: Go tohttp:// and play the game. Draw and annotate a Flow Chart to show the Algorithm for the program behind the game.

71 External Libraries

72 External Libraries: Theory
An external library is a repository that stores information on common, shared, resources. For example: datetime is a library that stores information on dates and times including how to output a .date() and what a timezone is. We use external libraries to store complex functions of code that can be called later, for example the math library remembers what pi is, if you had to type that into every program you write you would never finish writing one!

73 Thinking time Task 1 Write a short answer for the above questions.
What does the random library do? Why is this useful for programmers? Write a short answer for the above questions.

74 External Libraries Task 2a Run the following code: Task 2b Task 2c
import turtle #this is an external library window = turtle.Screen() #this is an external library timmy = turtle.Turtle() #this is an external library for loopCounter in range(3): timmy.forward(50) timmy.right(120) window.exitonclick() What is the output? Describe what happens. Task 2b What does timmy.forward(50) timmy.right(120) Do? Task 2c Change the code to draw a square

75 Working with Numbers: Random & Math
Task 3c The area of a circle is πr2 Run the following code and see what happens: import math r = 5 area = math.pi*(r*r) print(area) Task 3d Write a program that finds out the area of a circle which has a radius of 10 Task 3a import random a = random.randint(50,150) print(a) Task 3b Change the code to generate a number between 1 and 100.

76 Working with dates: datetime
Task 4a Run the following code: From datetime import datetime From datetime import date now = datetime.date.today() print(now) Task 4b The date.today() has 2 parts, what do you think each part does? What does “.date.” do? What does “.today()” do? Task 4c Change the code to print the current date and time. Hint: you need to find the datetime for .now() but only show the .time()

77 Task 5 What’s happening here?
Write a sentence describing each what the code in each box does. What is the difference between import library and from library import X? from datetime import date import random import turtle Window = turtle.Screen()

78 External Libraries So far you have used: Random Turtle Datetime
These are three of the external libraries that python can use to generate random entities, draw graphics and produce date time fields.

79 Task 6: Turtle Look back at your code for task 2c.
Change your code so that it asks the user how many sides they would like their shape to have, and draws this. Use a FOR loop to make the square draw 4 times. Hint: you will need to add

80 Task 7: Turtle What does this do? Take a screenshot of the result.
Change your solution to Task 6 to have the following code inside the FOR Loop: turtle.color("red“) What does this do? Take a screenshot of the result. Change your code so that it draws a shape in green.

81 Task 8: Turtle! Run the following code: a) What does this code do?
b) #comment the code to explain what happens import turtle import random def hexagon(angle,size): angle=60 for i in range(6): turtle.forward(size) turtle.left(angle) for i in range(18): print hexagon(60,random.randint(40,100)) turtle.color(random.randint(0,1),random.randint(0,1),random.randint(0,1)) turtle.left(20) turtle.exitonclick() c) Change the code underneath ‘def hexagon(angle, size)’ To draw a Pentagon. Hint: You will need to change the number of sides and the angle.

82 Extension Task 1 Write a program that overlays different sided shapes on the same centre point, to create a ‘flower’. Hint: Use the internet to help you; this is a good starting website:

83 Extension Task 2 Fill the screen with random shapes of different colour. Hint, you will want to look at the code in Question 8 and create more than one shape.

84 Challenge: Number Guessing Game

85 Task 1: Algorithm Play the number guessing game ( bin/gn.cgi?A1=s&A2=100&A3=0) Model the Algorithm for the number guessing game ( copy this onto this slide and add #comments to explain what each stage does.

86 Task 2: Generating a Random Number
a) Write a program that generates a random number between Print the number

87 Task 3: Asking for an Input
a) Add an input to your program and print both the number and the input.

88 Task 4: Checking the Answer against the Number
a) Add an IF statement to your program that checks whether or not the inputted answer is equal to the randomly generated number. If it is print ‘Correct’, if it is not print ‘Incorrect’.

89 Task 5: Making the game Loop
Change your program so that it tells the user if the guess is higher or lower than the number Change your program so that the program runs a loop that does not end until the user gets the answer right. Hint: You will need to ask the user to input a new answer every time they get it wrong.

90 Task 6: Counting the attempts
Add a variable that counts how many attempts it has taken the user to get the answer right. Change your program so that the user can only have 7 attempts Hint: You will need to use a while loop that only works whilst they have not had 7 tries.

91 Procedures and Functions

92 Theory: Procedures If the same piece of code needs to be used several times we can use a loop (FOR or WHILE) - but only if those times are all together. If you need to run the same bit of code again later, you can use a procedure. There are several advantages to this: The program becomes easier to read. The program becomes easier to test. If you have tested a procedure you don’t have to worry about it when you subsequently use it. Procedures can be reused throughout a program meaning code does not need to be rewritten

93 Task 1: Procedures What does ‘def’ do? Run this code and explain what it does: (Questions on the right) What does the for loop do? #Subroutine that prints out sentence 3 times def myFirstProcedure(): for i in range(1,3): print(i, 'This is a procedure') #Main Program print('Start of main program') myFirstProcedure() print('End of program') What does this line do? b) Change the name of the Procedure and call it twice in the #Main Program.

94 Task 2: Procedures - Parameters
We can use parameters to make procedures even more useful. The parameters in the procedure below are text and times. Run the following code: #Subroutine that prints out sentence 3 times def myFirstProcedure(text, times): for i in range(0,times): print(i, text) #Main Program print('Start of main program') myFirstProcedure(str(input('Input a String')),int(input('Input an int'))) print('End of program') B) Change the program to have an input for text and times. Hint: The input will need to go in to the part of the program that calls the Procedure. e.g. callProcedure1(str(input(‘input a string’)),int(input(‘input an int’)))

95 Task 3: Procedures – Inside a Loop
Run the following code: #This is a procedure called output #It will print a given number and its square def output(number): print(number,"squared =",number*number) #This is the start of the main program number = 1 while number < 21: output(number) number = number + 1 B) Write a program that has a procedure called ‘multiply’ that takes 2 numbers and multiplies them together. Make num1 5 and the num2 10, both nums should increment by 1 with each iteration. Hint: Start off by #comment designing your solution, then write the procedure and then the #Main program.

96 Task 4: Procedures – Optional Parameters
Run the following code: #Output Procedure def output(grade,score=50,feedback="Well done!"): print("You scored",score,"which is a grade",grade,feedback) #Main Program output("C") output("A",87) output("E",12,"Rubbish!") B) What parameters are defined in the Output Procedure? Hint: There are 3. C) What order are the parameters printed? What order are the parameters inputted in the #Main Program? What order are the parameters defined in the #Output Procedure? D) Change the program to add a fourth parameter called Name. The program should print the students name, score, grade and then feedback.

97 Challenge: Procedures
Write a program that has 2 procedures; one called ‘add’ and one call ‘subtract’. The program should ask for 2 numbers to be inputted and then output 10 addition and 10 subtraction calculations, incrementing the first number by 5 and the second number by 7 each time.

98 Theory Functions Sometimes a procedure will have to send some data back. This is called a return. Procedures that return something are called functions. That means we can use the value within other statements. We use the return keyword to send the value back to the main program.

99 Task 5: Functions B) Change the program so that it runs the double function inside a FOR Loop and prints the following output: Run the following code and explain what happens: #Function to double a number def double(number): twicenum=2*number return twicenum #Main Program a=int(input('a: ')) print('Double a is') print(double(a)) What does return do? What does this print line do?

100 Task 6: Functions A) Write a function called circle that takes in an integer representing the radius and returns the area of a circle. Hint: Area of a circle is πr2 where r is the radius Call your function from the main program: print(circle(1)) print(circle(2)) print(circle(3))

101 Task 7: Functions Write a calculator program that asks the user for 2 numbers and then asks them what they would like to do with these numbers, if they press ‘1’ it will add the numbers, ‘2’ will subtract them and ‘3’ will multiple them. The program should have 3 functions: Add Subtract Multiply Add should return x + y Subtract should return x – y Multiply should return x * y

102 Challenges: Procedures and Functions
Write a program that uses a procedure output the following:

103 Challenge 2: Write a program that uses 2 functions to return double and half of a number.

104 Challenge 3 Write a program that allows you to type in a sentence and it automatically removes all the vowels to turn it into text speak. Hint: You will need to find out how to remove certain letters from the sentence, store these and then remove them before printing. Use the internet to help you solve the challenge!

105 Python Lists (Arrays) Mr Petford

106 Lists: Theory Python Lists:
The list is a most versatile data type available in Python which can be written as a list of comma-separated values (items) between square brackets. Good thing about a list is that items in a list need not all have the same type. Creating a list is as simple as putting different comma- separated values between square brackets. For example: list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];

107 Lists: Theory The list type is a container that holds a number of other objects, in a given order. The list type implements the sequence protocol, and also allows you to add and remove objects from the sequence. Like string indices, list indices start at 0, and lists can be sliced, concatenated, entries can be added (appended) and entries can be deleted. For your coursework you will need to be able to sort lists in: Alphabetical Order Highest to Lowest Score Average Score, Highest to Lowest 1 2 3 physics chemistry 1997 2000

108 Lists: Some useful websites to help you
(For reading and writing files) _qr.pdf (Python reference sheet) (Lots of Python cheat sheets)

109 Task 1 list1 = ['physics', 'chemistry', 1997, 2000 Print(list1) del list1[2] print("After deleting value at index 2 : print(list1) A) There are 4 syntax errors in the code above. Debug them to make the code work and take a screenshot to show that you have made the program work. What does the program do? Add a #Comment to the start of the program explaining what it does. B) Run the code and add a #Comment after each line to explain what it does. You will need to have read the theory slides to do this.

110 List Operations Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string. Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition 3 in [1, 2, 3] True Boolean Logic Condition for x in [1, 2, 3]: print x, 1 2 3 Iteration (print) over a list

111 Lists: Cheat Sheet list.append(x) Add an item to the end of the list list.insert(i, x) Insert an item at a given position (i). The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list. list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item. list.pop(i) Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. list.count(x) Return the number of times x appears in the list. list.reverse() Reverse the elements of the list, in place.

112 Task 2 For this task use the list code above.
List1 = [‘Apples’, ‘Pears’, ‘Stairs’, ‘Dog’, ‘Bone’, ‘Phone’] For this task use the list code above. Create a program that counts how many items are in a list Create a program that prints all items in a list Create a program that prints the third item in a list Create a program that prints the first, second and third items in a list

113 Task 3 Create a program that adds an item to the end of a list
B) Create a program that adds an item into the 3rd position in a list. C) Create a program that creates a new list called List2, that contains ‘I love Computer Science’ 7 times. D) Create a program that will print this list 3 times.

114 Sorting Lists Python lists have a built-in sort() method that modifies the list in- place and a sorted() built-in function that builds a new sorted list from an iterable. To sort a list into ascending and descending order the following lines can be used: Ascending Descending list.sort() Where list is the variable name of the list. list.sort(reverse= True)

115 Task 4 Create a program that sorts a stored list into alphabetical order before printing it. Create a program that sorts a numerical list into descending order (Highest to Lowest) Hint: You will need to create the lists first. Use

116 Task 5 Create a program that deletes all items from a list
B) Create a program that deletes the last item from a list C) Create a program that deletes the third, and only the third item from a list

117 Arrays vs. Lists Most languages use arrays rather than lists so you may come across the term array being used in a similar context. (Python does have arrays available but lists are much more commonly used.) The two main differences between the two are: Lists can hold different sorts of data whereas an array (usually, depending on the language) only holds one data type. Lists change size as new items are added where as in most languages arrays have their size declared at the start.

118 Extension: Adventurers Challenge

119 Task 1 – Thinking Time In a computer game, what is an inventory?
What does the word ‘mutable’ mean? What does the word ‘concatenate’ mean?

120 Task 2 – What would you take to a desert island?
a) Write a program that asks you for an object you will add to an adventurer’s inventory. The program should store this in a list called ‘Inventory’.

121 Task 3 – Counting and Printing
a) Write a program that will count the items and print out the inventory. b) Create a program that fills a list and once the list is full asks the user if they want to print the list or remove any items.

122 Task 4 – Deleting and Joining
Write a program that will remove an object from the inventory. Write a program that joins two lists together.

123 Task 5 – Challenge! Write a program that asks the user how many items they want to take with them to the desert island (but make sure they can’t take more than 20), these items should be stored in a list. When the list is full it should be sorted alphabetically and then printed.

124 Extension Challenge! Make sure that your code for Task 5 – Challenge! Is #commented before answering these questions. How could you optimize the performance of the program? How could you add this program to into another program? Hint: Reducing the number of lines of code? You may need to use the Internet to help you research these ideas. Google is a good place to start – put these keywords into your searches ‘Python’ & ‘programming’

125 File Handling

126 File types A file is usually categorized as either text or binary.
A text file is often structured as a sequence of lines and a line is a sequence of characters. The line is terminated by a EOL (End Of Line) character. The most common line terminator is the \n , or the newline character. The backslash character indicates that the next character will be treated as a newline.

127 Opening a file To open a file for writing use the built-i open() function. The syntax is: FileVariableName = open(filename, mode) FileVariableName is the variable name of the file, this is what the file will be called in the program. open() is the function filename is the name of the file mode is the way that the file will be used (more on that later)

128 File modes added to the end. Mode Description r To read the file w
To write over or to create the file a To ‘append’ to the end of the file; any data written to the file is automatically added to the end. r+ Opens the file for both reading and writing

129 Task 1: Creating a text file
Task 1a In your Python folder create a new text file (right click, new, text file) Call this text file myfile.txt (don’t put anything in it) Run the following code: Open your text file, take a screenshot of the text file, your code and the python IDLE screen file = open("myfile.txt", "w") file.write("hello world this is the first line of myfile\n") file.write("and this is the second line\n") file.close()

130 Task 1: Creating a text file
B) Annotate the code using #comments: C) file = open("myfile.txt", "w") file.write("hello world this is the first line of myfile\n") file.write("and this is the second line\n") file.close() What file = open() do? What does the “w” do? What file.write do? What does file.close() do?

131 Task 2: Writing to files Create a program that creates a text file called ‘myfile2.txt’ that contains 5 lines: My name is Your name I go to Pedmore Technology College in Stourbridge My favourite colour is Your favourite colour Create a program that overwrites the ‘myfile2.txt’ file with the following line: I have just deleted my work

132 Task 3: Appending files You have made a file called myfile2.txt and have written to and overwritten this, but you might not always want to overwrite a file, you may want to append it (add to the end). Create a program that adds the following line to myfile2.txt This line has been appended to the end of the file

133 Task 4: Writing from a list
The following code will not run. It doesn’t work because there are 5 Syntax errors in it. Fix them and make it work. #Comment the code to explain what each line does What is the difference between file.write() and file.writelines()? Why would you write from a list instead of using separate file.write() functions for each statement? fh = open("hello.txt” "w") lines_of_text = ["a line of text", another line of text", "a third line” fh.writelines(lines of text) fh.close(

134 Task 5: Reading text files
If you want to return a string containing all characters in the file, you can use file.read(). You can also use this function to read a specific number of characters, file.read(n) will read n many characters. Create a program that reads the hello.txt file Create a program that reads only the first 5 characters of the hello.txt file Create a program that reads the first line of the hello.txt file

135 Task 6: Reading with readline()
There is a quicker way to read an entire line from a file than using file.read(). The readline() function will read from a file line by line (rather than pulling the entire file in at once). Use readline() when you want to get the first line of the file, subsequent calls to readline() will return successive lines, the second time you call readline() it will return the second line in the file. Create a program that reads the first and second lines of hello.txt using readline()

136 Task 7: Reading FULL Lines
Run the following code: What is the difference between this and your solution to 6b? Use the internet to find out what .readlines() does – write an explanation in your own words file = open('hello.txt', 'r') print file.readlines()

137 Task 8: Looping over files
To make a program faster and more memory efficient you can read (iterate) over a file using a FOR loop instead of using lots of .readline() or .readlines() Fix the code above to make it work, there are 3 Syntax errors. Use #Comments to explain what each part does. Create a program that reads all lines in myfile.txt using a FOR Loop. file = open('hello.txt' 'r’) For line in file print line

138 Closing files When you’re done with a file, call .close() to close it and free up any system resources taken up by the open file. After calling f.close(), any attempt to use the file object will fail. This means that no changes can be made to the file. BUT! If you do not close the file the program will be able to make changes to it – You may not always want this to happen.

139 Task 9: With Statements Another way of working with file objects is the With statement. It is good practice to use this statement. With the "With" statement, you get better syntax and exceptions handling. In addition, it will automatically close the file. The with statement provides a way for ensuring that a cleanup is always used.

140 Task 9: With Statements The syntax for a WITH statement is:
with open(filename) as file: Debug (4 Syntax errors), Run and #Comment the following code: Why would you use WITH instead of file.open(), file.write() and file.read()? with Open("newfile.txt") as f FOR line in f: Print line

141 WITH Examples Run the following code and add a #comment to the start of to describe what happens Write a program that: Opens your hello.txt and reads all of the lines Writes 3 new lines ‘WITH Test 1’, ‘WITH Test 2’ and ‘WITH Test 3’ Reads all of the lines again. with open("hello.txt", "w") as f: f.write("Hello World")

142 Splitting Lines The split function splits the string contained in the variable data (this could be a file or just a normal string variable), whenever it sees a ‘special’ character. line.split(":") would split the line using colons line.split(“ ”) would split the line using spaces line.split(“,”) would split the line using commas

143 Task 10: Splitting Lines Debug and run the following code, #comment to say what happens Write a program that lets the user input 10 words and then saves these into a string separated by commas. Modify this program to split the string into different outputs using the split(“,”) function as shown in task 10A. s = "One two three" word = s.split() FOR word in word: print(word)


Download ppt "Python Challenges Mr Petford."

Similar presentations


Ads by Google