Computational Thinking-Y8-Part2
Computational Thinking-Y8-Part2
1 Make a list
A variable is :
• a named area of storage
• stores one value
A list is:
• A special kind of variable can store several items
• Is shown inside square brackets [ ]
• Each item in a list is called an element
• Items are separated by commas
Append an element
• Append : add to the end
• Rule: list name.append(item)
• Ex: colorlist.append(“orange”)
• Append user input:
Color=input(“enter a color”) get input from user and save it in variable called Color
colorlist.append(Color)
Output: -------------------------------------------------------------------------
• Put (T) or (F):
1. List numbering starts at 0 ( )
2. the second element in the goals list is goals[1] ( )
3. To print first element: print(goals) ( )
4. To delete first element: del goals[0] ( )
5. To edit the second element in the list : goals[2]=“buy a car” ( )
3.3 Block bad input
• Python function len() tell you the length of a string or a list
• Ex: len(“hello”) the output of this command will be 5
colorList=[“red”,”black”,”green”]
Output will be 3 because the list has 3
Listlength=len(colorList) elements
Print(Listlength)
• Allowed number range from 0 to one less than the number of items in the list
• A program which doesn’t crash called a robust program
• To make robust program you need to block bad input
• A check which blocks bad input is called a validation check
• If….else • While loop
Logical test to test the input number • This program will handle out of bounds error
when the user enter a number:
• If the test is true , carry out the command
• Greater than or equal to the length of the list
• If the test is false, show an error message
3.4 traverse a list
• Traversing a list is to look at every value in it
• Example in real life:
• Social media apps wants to check that every user is still active
• Business want to check every item in stock
• Manager wants to send email to every team member
• Traversing a list using for loop
Colorlist=[“red”,”yellow”,”blue”,”green”]
For I in range(4)
Print(I,colorlist[i])
What if you use wrong stop value?
• You have to find list length at first
Stop=len(colorlist)
for I in range(stop):
Print(I,colorlist[i])
Assignment
trees=[“oak”,”beech”,”willow”]
Number=len(trees)
Print (number)
1. What would be the out put of these commands
2. What is the valid index numbers
3. Write a logical test to check whether the user enter a valid index number
4. To traverse this list using for loop what is the stop value
5. What is the command we use to get length of the list
6. “a list can change in size while a program is running” is this statement
true or false and why?
This program is for traversing trees list.what is the output of this
program,find the error in the program and correct it
trees=[“oak”,”beech”,”willow”,”ash”]
For I in range (3):
print(trees[i])
• Create an empty list called teamlist
• Use a while loop to append names to this list
• Use a for loop to traverse this list