All published worksheets from http://sagenb.org
Image: ubuntu2004
SEQUENCE TYPES: lists, ranges and strings
LISTS
1. A list can be defined with square brackets. The list can be empty, or you can initialize the list with any number of items separated by commas
new_list_object = [element_1, element_2, element_3]
empty_list = []
2. the append method adds a new item to the end of the list
empty_list.append(new_item)
3. the extend method adds multiple elements to the end of the list
empty_list.extend([list_of_items])
Extend adds each item to the list, while append adds the entire list as a single item!!!
RANGE - returns a list of integers that starts at zero and increments by one until it reaches (but does not include) the specified value.
Another shortcut for creating a list of integers that is similar to the range function:
[start_value..endpoint, step=1]
STRINGS - they have all the features of sequence types
FOR loop - A Python for loop iterates over the items in a list.
for loop_variable in list_name:
statement 1
statement 2
Let's say you have some data stored in a list, and you want to print the data in a particular format. We will use three variations of the for loop to display the data.
zip accepts one or more sequence types (with the same number of elements) as arguments and returns a list of tuples, where each tuple is composed of the one element from each sequence.
The syntax time,value was used to unpack each tuple, so that we could access the values through the variables time and value.
for loop_counter in range(len(list_name)):
statement 1
statement 2
Two simple examples of for loops:
How many lines will be printed when the following loop runs?
We defined a list of strings, each of which contained whitespace before and/or after the character.
The string method strip was used to remove the whitespace from each string, and we used the list method append to create a new list of stripped strings.
LIST COMPREHENSION - general sintax
new_list = [ operation_on_value for value in existing_list ]
If you are creating a new list, then the existing list can be generated by a function like range or srange.
WHILE loop - is used when we don't know how many iterations will be required and in that case we can't use FOR loop!
WHILE conditional_expresion:
statement 1
statement 2
The loop iterates as long as the conditional expression evaluates to the value True.
The loop terminates as soon as the expression evaluates to False.
IF statement - allow a program to make decisions while it is running.
if conditional_expression:
statements
else:
statements
ELIF instead of SWITCH