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

Unit3 - Computational Thinking (Python)

Uploaded by

Wai Yan Hein
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
379 views

Unit3 - Computational Thinking (Python)

Uploaded by

Wai Yan Hein
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 26
Computational thinking: Team Manager You will learn > how to store a series of items as a list > how to add, delete and edit items in the list > how to look at every value in (traverse) alist > how to make a menu interface to help the user > how tw block bad input tw stop the program from crashing. In this unit you will make a program in Python. The program cat be used by anyone why atiages 4 learn or group of people. Tor example, the manager might be a team coach, an orchestra leader or a teacher. The program will help the manager make a team list. They will be able to add names, change them, or delete names from the list. They will he able ta print aut the list ~ You will make a menu of choices tu help Une user work @ with the program. You will add input checks so the user \ cannot crash the program with bad inputs. QUID LEZEN LATTE, Imagine you are the manager of a team or group. Pick something you enjoy. It does not have to be a sports team - for example, you could be managing a group of actors, a horse-riding club or a choir. On paper, design the interface for a phone application (app) that you could use to help you do your work as manager. Your interface can have: > pictures > amenu > maps. > text > buttons Include anything that you think could be useful. rT Rac A el ie ea rece Eel aa tae eo el (60) Putting facts into lists helps people to read and remember facts. The order of the list also matters! People tend to think that the first fact in a listis the most important. 2. People remember the first fact better than the other facts on the list. 3. Thisis called the ‘primacy effect. 4 Do research on the primacy effect to find out more. 5 Look out for the primacy effect next time you read alist. ae od Talk about... In this unit you will make a simple list of names. In real life, a manager would store many other pieces of information as well as names. What information does your schaal stare ahauit you? What other organisations have information about you? pooner enc ( In this lesson Voulwill (ears Last yoar you learned to write programs in Python that are user-friendly and readable. You learned to use variables and to make programs with Input and output. You learned to use for loops and while loops. You will use these Python skills as you make the Team Manager program. All of these skills and ‘commands are important for this lesson. If yau do not remember these Python commands, go back and review the work you did in Student Book 7. > how to store a series of values asa list variable. Variables and lists You have learned that a variable is a named area of storage. A variable stares one value or piece of data. Here are two Python commands which assign values to variables: number = 5 colour = "red" Alistis a special kind of variable. A list can store several different items of data. A lists shown inside square 9088 ‘A computer company sold devices in a range of colours. This Python command will make list of those colours. the listis called colonr1 ist colourlist - ["red","yellow", "blue", "green"} Each item in alist is called an element. This list has four elements. The elements are separated by commas. Ifa listis long, it can go over more than one line of the program. colourlist = ["red", “blue”, "green", “orange”, "purple", "pink", "brown", "teal", "scarlet", "grey", "crimson", "mauve", "magenta", "amber", “black print (colourlist) Append an element Append means ‘add to the end’. You can append items toa list. That means a new item will be added to the list. This command will append “orange” to colourlist. colourlist.append("arange") Append user input You can get input from the user and append that value to the list. colour = input("Enter a colour ") colourlist.append(colour) Remember to make input commands user friendly. You learned about thi in Student Book 7. An input command should include a clear prompt. In this example, ‘Enter a colour’ It is good practice to include a space at the end of the input prompt, inside the quote marks. Ihat means there will be a space between the Lext of the prompt and the input typed by the user. Print a list You can print a list just like any other variable. print (colourlist) This command will print out the whole list, including the brackets and commas. The completed program colourlist = ["red", "yellow" colourlist append ("orange") Here is the completed program. It colonr = inpnt ("Enter a colonr ") combines all the commands shown sofa, coluurlist .append (cvlouz) print (colourlist) "blue", "green"] Team Manager program A football manager wants to use Python to record his team selection. Here is a command that makes the list. team] ist is emply. It has no elements, teamlist = [] This command will add ‘Jamie’ to teamlist, teamlist.append( "Jamie" ) Or you can get input from the user and add that, input value to the list: name = input("Enter a name ") teamlist.append(name) OID 1 Make and run the colour ist program shown in this lesson. 2. Make and runa program which: a creates an empty list called toamlist b gcts.a name from the user © appends the name to the list prints the list. 8 uaBeuew weay :6upjuiyy jeuoneyndwo> ¢ Append elements using a loop The programs you have made add one element to the list. They: oe > use an input command to get a value from the user > append that value to the list. Often you want to add more than one element. A loop is a program structure that repeats commands. By using a loop structure, you can add multiple elements to the list. There are we pes feo in Pion: Be > for loop (counter loop) > vaste toner bn ee Using a ‘for’ loop EE A £0r loop is controlled by a counter. Itis a counter controlled loop. You learned to use counter-controlled loops in Student Book 7. Most programmers name the counter i. The program will stil work if you use another name for the counter. But using i makes your programs more readable. When you write the program, you set the number of times the loop will repeat. You can use a fox loop if you know exactly how many elements you want to add toa list. } colourlist = [] eS colourlist.append(colour) This program adds exactly seven values to colourlist. OID 1 Make and run the colour list program using a for loop. 2. Make and run a program which: > creates an empty list called teamlist > usesa for loop to append 11 naires Lo Une list ee > prints the list. Using a ‘while’ loop Awhile loop is controlled by a logical test. Itis a condition-controlled loop. When you write the program, you set a logical test. When the testis False the loop will stop. You can use a whi Le loop if you don’t know exactly how many elements you want to add to a list. Here is an example. This program adds valucs to colour list. The loop is. controlled by a question: Do you want to add another? (Y/N) IF the user types ‘V; the loop will repeat. If they type anything else, the loop will stop. colourlist ol repeat. while repeat vs colour = input ("Enter a colour ") colourlist.append(colour) repeat = input("Do you want to add another? (¥/N) ") print (colourlist) OID 1. Make and un the colourlist program using a while loop. 2, Make and run a program which: > creates an empty list called team] ist > uses a while loop to append names tv the list > prints the list. Or OERIIIIS This command creates a list: In this lesson you have made two programs that use loops. One program used a for . loop. A for loop repeats a set number of 1 How many elements are in this list? Rimeatyoll ser tnenlimberinT moti 2 Write the command to append the value Program adds exactly 11 names to the list. "sycamore" to the list. 3. Write the commands to get user input and add it trees = ["oak", "beech", "willow" ] Now make a program that: > asks the user how many names they want to the list toadd 4 You want the user to add elements to the list, but you are not sure how many elements, What type > loops exactly Wal number of times. of loop would you use? e apbeuey weay :6upuitp jeuoneynduoy ¢ ® Work with list elements In this lesson You will learn: > how to identify list elements using an index number > how to print, edit and delete list elements. List elements You have learned that a list isa series of elements. Astudent made alist of goals. Ithad three elements. goals = ["pass exams","help in shop", "buy trainers") You can choose any goals that are right for you. The elements are separated by commas. Each element stores one value or piece of data. Cvery elementiin a list has its own name. Index numbers The name of an element is made of two parts: > the name of the list > the position of the element in the list. List numbering starts at 0. The first element in the O lists called: ® goals[0] The next element is called: ® goals! 11 ‘And so on. The number in square brackets is called the index number. The index number tells you the position of an element in the list. Print an element Each element of a list is a variable in its own right. You can print the whole list. Or you can print a single element. goals = ["pass exams"," print(goals) print(qoals|01) help in shop","buy trainers"] You can try out these commands in the Python Shell, or make them into a program and run the program. You can include any goals that you like. Choose which element to print ‘The program above prints out the element with index number 0. You can change the program so that the user decides which element lo print. goals = ["pass exams","help in shop", "buy trainers} i = input ("which goal do you want to print? ") i = int(iy print (goals[i}) Here is an example of the output of this prograt which goal do you want to print? 2 buy trainere Edit a list element Remember that edit means make changes to something. You can change a single element of alist. You can give it a new value. This program changes the final element of the list to the value "buy a bicycle" goals print (goals) goale[2] - "buy a bicycle" print (goals) This program changes the final element of the list to a value input by the user. ("pass exams", "help in shop","buy trainers"] goals = ["pass exams","help in shop", "buy traincrs"] print (goals) goals[2] = input("enter a new goal ") print (goals) Try Uese cornmands in the shell or as a program. Choose which element to edit The program above edits the element with Index number 2. You can change the program so that the user decides which element to edit. 3 goals = ["pass exams", "help in shop", "buy trainers") 2 print (goals) 5 i = input( "which goal do you want to change? ") i = int(1) goals[i] = input("enter a new goal ") print (goals) Here is an example of this program, run in the Python Shell. (tpass exams", ‘help in chop', ‘buy trainers'] which goal do’ you want to change? 0 enter a new goal learn to drive ['learn to drive', ‘help in shop', "buy trainers") The Python Shell always uses single quote marks at the start and end of a string, e sabeuew weal :6upjump jeu Delete an element You can delete elements from a list. The command to delete is del. This program deletes element 0. goals = |"pass exams", "help in shop”, "buy trainers") print (goals) del goaisiv1 t print(goals) Try these commands in the shell or as a program, Choose which element to delete The program deletes the element with index number 0. You can change the program so that the user chanses which element to delete. goals = ["pass exams", "help in shop","buy trainers} print (goals) i = input ("which goal do you want to delete? int (4) del goals[ij print (goals) Example program Here iy a comiplete Python program. Itlets the user make and edit a list of goals. It combines commands you have learned in Lessons 3.1 and 3.2. goale = (] fappend values for i in range(5)+ new = input ("add a new goal to the list goals. append (new) fedit an item print (goals) i= input ("which goal do you want to change? ") i = int (i) guals[i] = input ("enter a new goal") print (goals) fdelete an item i= input ("which goal do you want to delete? ") i = int) del goalsfil print (goale) The program includes comments. Comments begin with the # symbol. The computer ignores comments. They are there to help human readers understand the program. @MID 1 Make and run a program to create and e 2. Make and run a program to: > create a team list of 11 names (using any method you know) alist of goals » allow the user to edit and delete names from the team list. oO Extra challenge ‘Amend the program that you made to make and edit a team list. Use a while loop so the edit and delete commands are repeated. OED This command creates a list: trees = ["oak", "beech", "willow" ] Whitis tne value of element 0? Give the command to delete element 2. Give the command to change element 1 to "encalyptns" The user entered this command: trees[6] - "pine" This caused an error. Explain why. CRIES In this lesson you wrote a program using a list of names. You may have used made-up names, or the names of people you know. Many computer programs store details of real people. If you store Information about a real person you must look after it carefully. You must be careful that the information is true, You must make sure the information is kept private. In many countries there are laws to protect personal data stored on computers. But even in countries without these laws, itis the responsibility of a programmer to treat personal data with care, e JaBeuew wea, :6urjuiy) euoNeNduio5 ¢ Block bad input In this lesson Last year you learned about input validation. Input validation lets you block incorrect inputs. In this lesson you will write code to block incorrect input to the program. You will learn: > how to recognise, avoid and fix out of bounds errors > how to block bad input to the program. Using index numbers You can print, edit or delete a single element of a list. To do this, you must give the index number of the element. Th \dex number can be included in the code, Here is an example. colourlist = ["red","yellow", "blue", "green"] print (colourlist[2]) Or the index number can be input by the user. Here is an example. colourlist = ["red","yellow","blue","grcen"] 4 = input (“which colour du you chouse? ") i = int(iy print(colourlist{i]) But only some numbers will work. For example, ifthe list has four items, they are numbered from 0 to 3. Ifyou give an index number that is bigger than 3, then the program will crash. For example, this user typed number 7. There isn't an element number 7. So they saw an error message. which colonr do you choose? 7 Traceback (most recent call last): File "C:/Users/Alison/Documents/Python/temp.py", line 4, in print (colourlist [i]) IndexError: list index out of range This type of error is called an out of bounds error. in this lesson you will see how to avoid and fix out of bounds errors. Length of a list The Python function 1en ( ) will tell you the length ofa string or alist. Type thi in the Python Shel: Jen("hell10") You will see the integer 5, because the string "he11o" has five characters. Now try these commands in the Python Shell. colourlist = ["red","yellow","blue","green"] listlength = len(colourlist) print (1istlength) You should see the integer 4, because colour ist has four elements. Think about how you can use this information to stop the user trom making an out of bounds error. What numbers are allowed? Ifwe know the length of alist, we know what numbers are allowed, The numbers {go from 0 to one less than the number of items in the list Here are sume examples. > Ifa list has 10 items, the index numbers go from 0 to 9. > Ifa list has 100 items, the index numbers go from 0 to 99. We can make a program to print this information. colourlist = ["red", "yellow", "blue", "gree! final_value = len(colourlist) - 1 print("index numbers go from 0 to", final value) Try these commands in the Python shell or as a program. Helpful message One way to reduce errors is to give the user helpful information. Then they know what they have to type. i you can print one colour from the list This message is not helpful. Itis easy for the user to make YU An if structure begins with a logical test. Test if the number input by the user is smaller than the length of the list. > Itthe testis True, carry out the command > Ifthe testis False, show an error message. Here is an example. colourlist = ("reu", "yellow", "blue", "green") i = input ("which colour do you choose? ") i = int (i) Af i < len(colourlist) : print (colourlist (i}) else: print ("out of bounds error") ‘While’ loop There is an alternative to using if... else. You can use awhile loop instead. ‘Awhile loop will ask for input until the value matches the requirement of the program. Here is an example. colourlist = ["red", "yellow", "blue", "green" i= input ("wnich colour do you choose? ") i= int (i) while § >= len(colourlist) : A input (enter a number ") i= intay print (colourlist[i]) This program uses the relational operator >=. This operator means ‘greater than orequal to’ You will get an out of bounds error if you enter a number: > thatis greater than the length of the list > that is equal to the length of the list. Remember that list numbering starts at zero. For example, think of alist with four elements. The elements will be numbered 0, 1, 2, 3. Ina list with four elements, the numbering stops at 3. In a list with 100 elements, the numbering stops at 99. To summarise ~ an index number that is equal to the length of the list will cause an out of bounds error. The while loop in the program will loop until you enter a value that will not cause this error. GI Make and run the example program shown in this lesson that uses i to block bad inputs to the program. else Change the program you have made so that it uses a while loop. (A) Extra challenge In the last lesson you made two programs to create and edit a list. Open any program. Use if... @1seto block bad input to this program. Adapt the program to use a whi le loop instead of if... else. orm This command creates a li trees = ["oak", "beech", “willow” 1. What would be the output of these commands? number ~ len(trecs) print (number) 2 Write a print command that will tell the user how to enter valid index number. 3. Write the commands to gat an index number from the user. Include a helpful message, for example, the one you thought of for Q2. 4. Aprogrammer wanted to check whether the user input was out of bounds. Write a logical test which will be True if the index number is valid, Crm Investigate user interfaces of real-life software apps. That might include apps you use on your phone. It might also include software you use at home or at school. Here are some questions to ask yourself. > Are there clear messages? > Do you know what input you have to provide? > Ifyou enter the wrong input, might you crash the program? ‘Ask family and friends about the software they have used, for example, at work, Studies have shown that a good user interface has a big impact on wheter people like to use software. Retlecting on your experiences with software will help to improve your programming skills, 8 sabeuew weal :burjuiyy weuoneindwod ¢ Bret mt In this lesson You will learn: > what traversing a list is > how to traverse a list. Data structures Alist is an example of a data structure, A data structure is a type of variable that can hold many values. in a list data structure, the different values are called elements. Lists and other data structures are used @ lol in programm That is because in real life we often want to stare many data values. Here are some examples. mation P Asucial inedia app sucli ay Facebuuk ur Twitter wails lo store inf about all the different accounts. > Abusiness wants to store information about its products, employees and suppliers. > Ateam manager wants to store information about the members of the team, And there are many other examples. Data structures are useful when we want to store a lot of data values. Some data structures can store millions of values. You have written programs to work with lists. You know how to append, delete and edit the clements ofa list. IF you are not sure how to do these things, look back at previous lessons. How to traverse a list Now you will earn how to traverse alist. ‘Traversing a data structure means looking at every value in the data structure. Think of the reasons people might want to do that. > Asocial media app might want to check that every user is, still active, > Abusiness might want to print out the number of items instock. > Ateam manager might want to write an email to every team member. In this lesson you will traverse a team list. You will print out each name in the list. This is a good way to show that you have traversed the list. Remember, real-life programs usually do something more complicated than just printing out. ‘For’ loop ‘A £or loopis a counter-controlled loop. The loop repeats a set number of times. You can use a counter-controlled loop when you knaw exactly how many times, you want a loop to repeat. A Lox loop has a counter, The counter starts at zero, It stops when it reaches the value set at the top of the loop. The number that stops the loop is called the stop value, In Lesson 3.1 you used a for loop to append values to a list. Here is an example. This program adds exactly four values to colour list. The stop value is 4. colourlist = [] for i in range(4): colour = input("Enter a colour ") colourlist.append(colour) print (colourlist) Print using a ‘for’ loop Each time the loop repeats, the value of i goes up by one. A for loop with a stop value of 4 counts through these values: plays jeuonernduio> = These are the same values as the index numbers of alist. This makes it easy to print out every elementiin a list. iso z -1 3 i= 2 = 3 i-3 a Smee rd Example: colourlist This command creates a list with four elements. colourlist = ["red", "yellow", "blue", "green"} Because the list has four elements, we can use a fox loop that counts to4, for i in range(4): Each time round the loop, we print a single element of colourlist. print (colourlist(ij}) The value of 1 goes up by one each time. Ihe program prints the next element in the list. When the value of { reaches 4, the loop stops. You can also adapt the command so that it prints out the index number as well as the colour. print(i, colourlist!il) Here is the completed program, colourlist - ["red", "yellow", "blue", "green"] tor 1 in range(4 print (i, colourlist [1]) @ImID 1 Make and run the example colourlict program shown in this lesson, using 2 for loop to traverse the list. 2. Make and run a program which: > creates an emply list called teamlist uses a for loop to append 11 names to the list > traverses the list, printing out each name in turn. Wrong stop value? The programs ya have made work fine When we write the pragram, we know how many elements there are in the list. We can use this number as the stop value. But in real life we don’t always know the size of alist. We could use a ony, whi le loop to append values to alist, which means we don't know how many values there will be. Alist can also change in size. > The user may append values to the list. This will make the list bigger. > The user may delete values from the list. The list will get smaller. This could make the program go wrong, The stop value won't match the size of the list. What effect would this have? > Ifthe list was bigger than the stop value, then the loop would stop too soon. The loop would miss out some of the values in the list. > Ifthe list was smaller than the stop value, then the loop would go on too long. There would be an out of bounds error (look back at Lesson 3.3). Find list length The solution is to find Une length of the list. You already know the command to do this. Store the list length as a variable. In this example we have called the variable stop. stop = len(colourlist) Now we can use the variable as the stop value of the loop. colourlist = ["red", "yellow", "blue" stop = len(colourlist) for i in range(stop): print (i, colourlist[i]) OI OEIIIIID Make a program that creates a list of colours. Make and run a program which: > Use the Len () function to find the stop value. > creates an empty list called teamlist > Use a for loop to traverse the list, printing out > uses awhile loop to append names to each value. the list, > uses for loop to traverse the list and print each element in the list. ora This command creates alist: trees = ["nak", "beech", "willow", "aoh"] 1 We could use a for loop to traverse this list. What is the stop value? 2 Write a command that assigns the length of the list to a variable called stop. 3. Auser wrote the following program to traverse this list. What is the error in this program? What is the output of this program? trees = ["oak","heech", "willow", "ash"] for i in range(3): print(trees[i]) 4. Give one reason that a list can change in size while a program Is running, e seGeuew wea, Bu Menu of choices In this lesson You will learn: > what an interface is > how to make a menu interface. What is a program interface? Aprogram interface is the part of a program that handles input and output. > Input: The interface gets user inputs. The user can control the program. > Output: The interface displays program outputs. The user can see results and content. In Student Books 1-7 you used the Scratch programming language. Scratch provides a colourtul interface with images and sounds. Python has a text-only interface. Requirements A program interface should have all of the following features. It should: > tell the user what the program is and what it can do > let the user make choices or select options > let the user enter information - you should include a helpful message and validation (remember Lesson 3.3) > display results or answers > let the user close the program. In this lesson you will make a menu interface for the Team Manager program. Make the Team Manager interface Stail.a new Python program file. Start with the command to make anew empty team list. teamlist = [] Now you will make an interface to let the team manager work with the team list. Introduce the program First, make the part of the interface that meets this requirement: Tell the user what the program is and what it can do. ‘This program is for the manager of a team, for example a football team or a music group. It will let them manage the membership list. Here are the commands to do this. You can change the words if you like. teamlist = [] print("TEAM MANAGER") a) print("rhis program will help you manage your team. print (" print("\n") Ihe final command prints." \n". That stands for ‘new line’ and it makes a blank line in your program. Menu of choices Now you will add commands for the next requirement: Let the user make choices or select options. The first version of the menu has only three options (A, B and X). Hereis the menu design. TEAM MANAGER ‘Add print commands to your programto print ‘This program will help you manage yonr team. out options A, B and X, with the words you see here. Your aim is to make this menus appear A: Append a value when you run the program. If you want to Be Beers) bbe Loam) ase, E xX: EXit the program change the wording or layout you can. Get user input After the menu has appeared, the user will make @ choice. This command will get input from the user and store it as a variable called choice. ) Run the program and you will see the menu. Remember, the menu choices don't work yet. choice = input("Enter your choice: teamlist = 11 print("T EAM MANAGER") print ("~. ) Print ("This program will help you manage your team.") print ("\n") print("A: Append a value") print ("B: Print the team 1ist" print ("1 Byit the program") choice = input ("enter your choice: ") OI Start a new Python program Use a series of print commands to make and display the Team Manager interface. Get user choice with an input command. oe seBeuew wuer, ‘6upuiyy jeuoneynduios ¢ Loop to repeat The team manager may want to do many different actions. For this reason, you will use a loop to repeat the menu. But remember this requirement: Let the user close the program. You must have some way to stop the program when the team manager has finished using the menu. You do not know exactly how many times the manager will want to look at the menu. That means you must use a conditional loop (a whe loop). The menu will repeat until the user enters the choice "x: What can go wrong? class made the Team Manager program. When they made it, some things went wrong, In this section we'll ook at some of the mistakes they made. Barbara's mistake Barbara entered this code at the start of thewhi1e loop. The program did not work properly. teamlist = 11 (OR: Append « value") ant the team List") baat the. program") Ut(PEnter your cnoice: “) Barbara's program did not work because she used this logical test: choice The operator == means ‘is equal to’. The loop will repeat when the user enters the value ‘X’, But we want the opposite. We want the loap to repeat if the user enters a value which is not’ The symbol for ‘not equal to” 1s: ! Barbara had to change the first line of the loop to this: while choice Ifchoice was not set to "X"", the loop would repeat. Rio's mistake Rio entered this code. veamist - (0 ne? RAH MAWACET ‘Thi proyian will twip You manage your team.") cle") (CA? Append a value") (cat erine the team List") (xX: Bae the progran”) eholce = input ("Enter your cnoice: “) The program crashed. Rio saw this error message. Traceback (ost recant call last): File "C:/Python/rio.py", line 2, in while cholew I= "X": NaneError: name ‘choice’ 18 not derinea Rio’s program crashed because the whi Le loop uses the variable choice. But the variable choice has not been given a value yet. Rio had to change his program to give choice a value before the wii 1e loop. The variable can have any value, even a blank. choice Kalif's mistake Kolif entered this code. The program worked. But there is still a mistake, Can you see what it is? choice nile choice ' "x ‘teanlist = (1 AM MANAGER" > (thie progran will help you mar cn") (a: Append = value") ein Une Lean List") ‘une program”) nter your choice: ") your team.) This command makes a new empty team list. teamlist = [] Kalif’s program was wrong because the command to make an empty lists inside the loop. It wil repeat. The team list will go back to being empty each time Kalif corrected the error by moving the command. He moved it so that it came before the loop. OLamm oka Putthe Team Manager menu insidea loop Programmer made a menu interface. It was inside with % to exit. awhile loop. Avoid the errors you saw in the examples. Thisis the first line of thewhi le loop: while more == "¥" ) Extra challenge 1. What is the name of the variable used in this command? eee ee a 2 What value could the user input to make the loop option ‘A, they can append anew name to rae the team list. 3. What line of code would you include before the loop to set the value of the variable? 4 Give an example of a line you would include inside the loop to let the user stop the loop. e JeGeuew weal :bupjung jeuoneynduioa ¢ Activate the menu choices In this lesson You will learn: > how to give users control over what software does. User interface In the last lesson you made a menu. The user entered a letter. It was stored as a variable called choice. Make sure you have campleted the activities in the last lesson before you continue with the tasks in this lesson. Think of different types of software. Each type of software has a different user interface. When you touch or click on the interface, something happens in the program. In this lesson, you will make that happen with your Team Manager program. You will add code to make your menu options work. The user will input a choice. The computer will carry out their choice, ‘If structure You used an if structure in Lesson 3.3, An i£ structure starts with a logical test. The logical test campares two values. Ifthe test is True, then the actians inside the if structure will be carried out, Append If the choice is ‘A, then the user can append a name to the team list. You already know the code to append a name to the list. You did this activity in Lesson 3.1. Put the code into the i£ structure. if choice name = input("Enter a name ") teamlist.append(name) The code lines inside the i £ structure are indented. Print If the choice is ‘B’, then the computer will print out the team list. You already know the code to print the list. You did this activity in Lesson 3.1 Put the code into the if structure, if choice 8 print (teamlist) The cade line inside the i ¢ structure is indented Double indentation Here is the program so far. This program has got two i£ structures. The i structures are inside a while loop. When a program structure is inside another structure, this is called nesting. The if structure Is ‘nested’ inside the while loop. > Commands inside a while loop are indented. > Commands inside an £ structure are indented. That means the program has double teantiee — 0 choice =" " print (" print Brine ( print (\ print ("Ai Brant ("5 Print ("X Ry =") fp you manage your team") choice = input ("Enter your choice: ") Af chotee == "ats ewe ~ input ("Eutes @ aie “) veam1ist append name) Sf choice == "2B": print (teanlist) indentation. Can you see the double indentation in this program? Gms Continue the Python program you made in the last lesson. Add code so that the menu options work properly. > Append a name. Remember to include double indentation. In the next part of the lesson you will develop the program further. You wil > Print the list. > add new menu options to print, delete and edit elements > block bad input from the user to avoid an out of bounds error > sort the list using a new Python function Make sure you have completed all earller activities before you go on to the final part of the lesson. If you need more practice, take time to get the previous activities right before you go on to the final part of this unit. GED In Lesson 3.3 you explored software interfaces and reflected on whether they were user-friendly. Continue this task, But this time look out for software menus. What software do you know that uses menus? How do you choose an option from the menu? Do you find the menu easy to understand and use? Does the menu use words or pictures? « @ @ (2) eo saBeuey wea, ‘Supjuny jeuonendwos ¢ DO ad Add more menu options In Lesson 3.2, you learned some extra commands which would be useful to the team manager. > Print an element. > Delete ait element. > Edit an element. The table shows the commands that carry out these actions. Sra) CUT Printanelement | 4 = input("which list item do you want to print? ") i= int(iy print (tcamlict[i]) Deleteanelement |i = input("wnich list item do you want to delete/ ”) i= int(i) del _teamlist[i] Edit an element i = input("which list item do you want to change? ") i= intGiy teamlist(i] - input("enter a new name ") Block bad input The table shows the commands that will let the user print, delete or edit an element of the ai y. In each case the user has to enter a number. The number is the index of alist item. In this example the value is stored asa variable called i. The value input by the user must he a valid index number. It can't he bigger than the biggest index number in the list. If itis too big it will cause an out of bounds error. For example. if the list had five items in it, and the user tried to delete Item 6, that would cause an error. In Lesson 3.3 you learned how to block bad input. You could use these skills to prevent the user from entering an index number thatis too large. Sort the list This command will sort the team list. teamlist.sort() Because the elements of teamast are strings, they will be sorted into alphabetical order. if they were numbers, they would be sorted into numerical order. Use this knowledge to add a new option to the menu, tosortteamlist. Add code to implement oneofthenewment this program will help you manage your team. options given in this lesson. This image shows all of the options - you don't have to do them all A: Append 4 value Print the team list Print one element : Delete one element Edit one element : Sort the list : Exit Uhe program Ifyou have time, do more than one. Ifyou have time, add a check to block invalid index numbers. or A programmer made a program. Here is an ‘extract from the program. Enter your choice: 1. What choice should the user enter in order to print the list? 2. What happens if the user types ‘A’? 3 Ifthe user types ‘A, what will they see next on the screen? 4 What happens if the user types ‘C’? colourlist choice = "" ["rea", "yellow", "blue", "green") while choice eee print ("2: rant ("Bs Add a new colour to the lict") vrint the colour 11st") choice = input ("Input your choice: ") if choice == "A": new ~ input ("Type a new colour ") colourlist.append (new) Af choice == "Bt": print (colourlist) Lf clive == 7c": colourlist.sort() @E==IS Itis hard to make an interface using Python. That is because the program will only print simple output made of text characters. Usain liked creative challenges. He made this title tor the program, using nothing but Python print, commands. Can you design and make an interesting title for your Team Manager program? 6 saBeuey wees :buryuiyy jeuoneyndwo ¢

You might also like