Python Workbook 1 - Dohan PDF
Document Details
Uploaded by LucidToucan
Dohan Ye
Tags
Summary
This Python workbook covers KS3 programming concepts, including variables, code, programs, loops, and conditional statements. It includes examples and exercises.
Full Transcript
[ [ [ [ [ [ [ [ [ [ t r r r Python KS3 Programming Workbook “Do you speak Parseltongue?” Name: Dohan Ye Written and prepared by Dohan Ye Page 2 ...
[ [ [ [ [ [ [ [ [ [ t r r r Python KS3 Programming Workbook “Do you speak Parseltongue?” Name: Dohan Ye Written and prepared by Dohan Ye Page 2 ICT Teacher ___________________Form: 9JOB Welcome to Python The python software has two windows that we will use. The main window is called the Python Shell and allows you to directly write in program lines and then a press of the return will execute them. This is good for testing one line of code. The second window is the “Edit Window” which allows you to enter several lines of code, or a create a program, save it and then execute the code. Opening the python software Python and the Raspberry Pi To create a new python program on the Pi, you can use a text editor called “Joe’s Text Editor” Type: joe (the name of your program).py To run or execute the program type: python (the name of your program).py KEY WORDS Code Text written by a programmer using a programming language to give the computer a task to complete. Program A set of logical instructions given to a computer in order to solve a problem or task Variable A named memory location with a specific value Written and prepared by Dohan Ye Page 3 Loop A group of instruction or a block of code that is repeated multiple times until a condition is reached. Else Used to specify an alternative option in the code if the previous conditions are not met. IF A conditional statement, that determines the path of the program depending on if a certain condition is true or false ELIF Used in a conditional statement to check for multiple conditions. While Used to repeat a certain block of code an unknown/infinite number of times until a certain condition is met. For Used for iterating over a sequence, or repeating a block of code a fixed number of times. To Execute the program code press F5 Your first program “Hello World” TYPE Print “Hello There” What does it do? To write this program, load up JustBASIC and start a new program (File New) Save your program as Hello Now Try These: ❒ Write a program to write your name on the screen Save as MyName Written and prepared by Dohan Ye Page 4 ❒ Write a program to write the words to your favorite song Save as Song Inputs “Your Favourite” You can use Python to enter in data, this is called an INPUT. The data that is entered is stored inside a VARIABLE. A variable is like a box that can be used to store a piece of information. We can put different information into the box and open the box at any time Written and prepared by Dohan Ye Page 5 START A NEW PROGRAM AND TYPE IN THIS CODE: Print "welcome" x=raw_input ("What is your name?") Print x 1. The variable is called x, this is like calling the box ‘x 2. The raw_input allows the user to enter any symbol or letters. 3. The input allows the user to enter numbers Now see if you can complete these: ❒ Write a program that asks for your favourite food and then returns the statement, I like x as well. Save as FavFood. (Use commas to separate the ‘I like’ and ‘as well’ ❒ Write a program that asks for 2 of your friend’s names and then states which friend is the best friend. Save as BestFriends Written and prepared by Dohan Ye Page 6 ❒ Make up one of your own Working with numbers Python is also a powerful calculator, go back to the shell mode and type in 1+1 EQUATION ANSWER What does it do? 2+5 7 adds 2 and 5 Written and prepared by Dohan Ye Page 7 67/34 divides 67 by 34 1.97058823529 41178 20**5 3200000 20 raised to the power of 5 30*4 120 30 X 4 3==6 False Asks if 3 is equal to 6 3!=5 True Asks if the factorial of 3 is equal to 5 39==39 True Confirms that 39 is equal to 39 range(100) Outputs the all Outputs all the integers from 1 to the integers 100 from 1 to 100 range(46,100) Outputs the Outputs the integers from 46 to integers from 46 100 to 100 range(100, 1000, 7) Prints a sequence of integers starting from 100, and adds seven each time until it reaches a limit of 100 In the text editor window you have to type the command to print range ( ). Can you create a program that list all the numbers starting from 100 to 10000, going up in intervals of 9? You can also float numbers as in create a decimal. Return to the text editor window. TYPE IN x = 3 print(x) y = float(x) print(y) A SIMPLE PROGRAM TO WORK OUT HOW MANY CALORIES YOU CAN EAT IN A DAY print "Welcome" c=input("How many calories have you eaten today?") s=2000-c print "You can eat", s, "calories today" Written and prepared by Dohan Ye Page 8 Now see if you can complete these: ❒ Jennifer wants to carpet her new room with pink carpet, Create a program that will work out the area of any sized room, (l x w), Save as Square ❒ Create a program that will work out the area of any triangle, (h x w), Save as Triangle Written and prepared by Dohan Ye Page 9 ❒ Write a program to work out how many days you have been alive for? Save as Age What do you need to work out? How to calculate how long you've been alive: age x 365.24 Written and prepared by Dohan Ye Page 10 IF all ELSE fails If and Else are powerful features where you can create different outcomes IF certain criteria or numbers are met. Else the programme will do something ELSE. START A NEW PROGRAM AND TYPE IN THIS CODE: if 10==10: print "hello" Notice the : at the end of the first line, this tells the computer to do whatever is on the next line, the second line sis also indented to show that it is related to the first line. AFTER : YOU SHOULD USE TAB THE NEXT LINE Now change one of the 10s to a different number, what happens? Written and prepared by Dohan Ye Page 11 WHY? Because 10 is not equal to the number on the other side of the equals sign, the computer does not print out hello Now we want the program to feedback and different answer depending on the size of a number. See if you can create the program to ask the users to Input a number and then if the number is bigger than 500 state big number ELSE print small number, ANSWER OVER THE PAGE: Written and prepared by Dohan Ye Page 12 Explain in your own words what a variable is A variable is a piece of memory that stores data that can be changed. It has a label or a name to easier identify it, the value can also be changed as the program runs. What have you enjoyed so far? What have you found difficult? What would help? ANSWER x=input("Please enter a number") if x >500: print "Big number" else: print "small number" The Christmas ELIF What about three responses the number of calories that are entered. For example, less than 250, less than 500, more than 500? You can use the ELIF function, this means else if. START A NEW PROGRAM AND TYPE IN THIS CODE: x=input("Please enter a number") if x >500: print "Big number" elif x > 250: print "medium number" else: print "small number" Written and prepared by Dohan Ye Page 13 Calorie Counter Part 2 ❒ Load the calorie counter program you made earlier, can you now create the program so that it asks if you are male or female and then calculate the calories based on your gender. Save as Calorie2 Written and prepared by Dohan Ye Page 14 (HINTS: Place all the variables at the top of the page, watch the indents) Written and prepared by Dohan Ye Page 15 More than words The length function, what does it do? Try these two examples. x=”frank” print len(x) a=(‘cat’) print a, len(a) What does the len() command do? The len command calculates the length of the string input Adding Strings A string is a block of text. It could be a single word, a sentence or an entire paragraph. In Python we use the term “str” to mean a string. TRY OUT THE FOLLOWING CODE: start = "Hello, " name = input("What is your name? ") end = ". How are you today?" sentence = start + name + end Written and prepared by Dohan Ye Page 16 Looping, For Sometimes you want something to keep happening, this is called a loop. There are several types of loop, the FOR loop and the WHILE Loop. Try te example below and save as ForExample a = ('cat', 'dog', 'frog') for x in a: print x, len(x) What is the for command doing? The for command is a looping command, in thiscase it it used to repeat the length of the words in a. What does the x do? Written and prepared by Dohan Ye Page 17 x is a placeholder for a value. The for command is useful if you want to hide a word, like a password, which should be kept secret. Now see if you can complete these: ❒ Create a program that coverts the variable “apples are nice” into zeros. Save as Zeros ❒ Create a program that has a variable called p which is the password, then the program prints the letters as * to hide the real password. Save the file as Password. Written and prepared by Dohan Ye Page 18 What do you notice about the way it displays the characters? Displays the characters each on its one line What happens if you place a comma after the print “*”, Nothing changes. Using letters instead of numbers In the Python shell we can show how letters or variables can be used with values / numbers assigned. These can then be used with mathematical functions. TRY THIS >>> h=156453737 >>> print h*h*h Written and prepared by Dohan Ye Page 19 While statements Like the For Loop the While Loop will do something while a condition is being met, While I am feeling hungry, eat food. Once the while condition has been met the program stops the loop, once you are not hungry, stop eating TRY THIS x=1 while x==1: print "EPIC FAIL" Explain what the program lines doing? The program isn't stopping, the line epic fail keeps repeating over and over. it wont stop because 1 will always be equal to 1 Countdown You can create a countdown by taking away 1 from the variable number each time, ie x = 5, x-1, so now x =4, x-1, so now x=3 and so on. The code is x =x-1, ❒ Change the x variable value to 10, the while should be changed so that the while the x value is greater than 1. Finally add x = x-1 to the last line of the program. Save as Countdown Written and prepared by Dohan Ye Page 20 Pausing The program runs very fast and all the instructions are completed very quickly. To slow down the instructions or pause between them we can use the sleep function. The sleep function is storedin the time module, so we first have to import the time module. TRY THIS USING YOUR COUNTDOWN PROGRAM, Add the codes import time to the first line of your program (This imports the time features) Add the code, time.sleep(2) after the print x feature ? Written and prepared by Dohan Ye Page 21 What does it do? The time.sleep command pauses the program for two seconds, before displaying the next number. Now see if you can complete these: ❒ Create a program that asks the user to enter a number of times that a sentence will be displayed, and then displays it that many times. Save as ❒ Create a program that asks the user to enter a number of times that a the sentence, (You asked me to display this,? times) and counts down each time. Saves as Number of times Written and prepared by Dohan Ye Page 22 ❒ Create a program that asks the user to enter a number of seconds until countdown. The program counts down in one second intervals and when it reaches 0 states “BLAST OFF”. Save as Blastoff Random Numbers If you are going to create a simple game you require the program to automatically select a random number. This requires the use of the random module. import random x = random.randrange(100) print x The randrange(100) selects any number from between 1 and 100, had it been (500) it will select any number between 1 and 500 Written and prepared by Dohan Ye Page 23 ASSIGNMENT Using all the command you have learnt so far, create a game below, save as GuessingGame ACTION HINTS Welcomes the user to the game PRINT Picks a random number RANDOM Asks the user to guess the number INPUT If the number user number matches the random number IF state you win! If the number the user number is higher than the random ELIF number state your number is too high If the number the user number is lower than the random ELSE number state your number is too low The program loops until the user guesses correctly WHILE LOOP EXTENSION The user only gets 5 turns to guess the correct number, HINT you will need to use the break function to stop the program from running. Create a new game that asks 10 questions, if they get the answer correct it adds points to the score, if they answer incorrectly no score is added. The game reports the score at the end of the session. Written and prepared by Dohan Ye Page 24 Extension BONUS: Writing to a file Python can be programmed to write and read from files. You made need to try this at home due to the security settings at the school system TRY THESE, WRITING TO A FILE fob=open('C:/folder/folder/Documents/file.name.txt', 'w') fob.write('This is the test to write to the document') fob.close() EVALUATION What have you enjoyed so far? - I enjoyed learning about the different types of commands in python - i enjoyed coding games, and tools for calculations What have you found difficult? - I found iteration, for and while loops difficult. What would help? - Doing more codes with iteration and looping as practice. Written and prepared by Dohan Ye Page 25 What are your strengths in Python programming? - Coding games and calculation tools What do you need to do next? - Explore more functions and commands within python, maybe branch onto other programming languages Written and prepared by Dohan Ye Page 26