Loops, Function, Tuples, Lists and Dictionary in Python
Background
Loops in Python:
The 'while' loop
a = 0
while a < 10:
a = a + 1
print a
The 'for' loop
for i in range(1, 5):
print i
for i in range(1, 5):
print i
else:
print 'The for loop is over'
Functions:
How to call a function?
function_name(parameters)
Code Example - Using a function
a = multiplybytwo(70)
The computer would actually see this:
a=140
Define a Function?
def function_name(parameter_1,parameter_2):
{this is the code in the function}
return {value (e.g. text or number) to return to the main program}
range() Function:
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
Lists:
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero. You can remove values from the list, and add new values to the end. Example: Your many cats' names. Compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
print cats[2]
cats.append('Catherine')
#Remove your 2nd cat, Snappy. Woe is you.
del cats[1]
Compound datatype:
>>> a = ['spam', 'eggs', 100, 1234]
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
>>> a= ['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
Remove some:
... a[0:2] = []
>>> a
[123, 1234]
Clear the list: replace all items with an empty list:
>>> a[:] = []
>>> a
[]
Length of list:
>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4
Nest lists:
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
Functions of lists:
list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L): Extend the list by appending all the items in the given list;equivalent to a[len(a):] = L.
list.insert(i, x): Insert an item at a given position. 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, and a.insert(len(a), x) is equivalent to a.append(x).
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.sort(): Sort the items of the list, in place.
list.reverse(): Reverse the elements of the list, in place.
Tuples:
Tuples are just like lists, but you can't change their values. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.
months = ('January' , 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', ' December’)
index | Value |
0 | Jan |
1 | Feb |
2 | Mar |
3 | April |
4 | May |
5 | Jun |
6 | Jul |
7 | Aug |
8 | Sep |
9 | Oct |
10 | Nov |
11 | Dec |
|
|
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
Dictionaries:
Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition.
In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing.
You can add, remove, and modify the values in dictionaries. Example: telephone book.
phonebook = { 'ali':8806336, 'omer':6784346,'shoaib':7658344, 'saad':1122345 }
#Add the person '' to the phonebook:
phonebook['waqas'] = 1234567
# Remove the person '' to the phonebook:
del phonebook['shoaib']
phonebook = {'Andrew Parson':8806336, \
'Emily Everett':6784346, 'Peter Power':7658344, \
'Lewis Lame':1122345}
#Add the person 'Gingerbread Man' to the phonebook:
phonebook['Gingerbread Man'] = 1234567
#Delete the person 'Gingerbread Man' to the phonebook:
del phonebook['Andrew Parson']
Task 1
Write a program of simple calculator program. Follow the steps below,
Declare and define a function name Menu which displays a list of choices for user such as addition, subtraction, multiplication etc. It takes the choice from user as an input and return.
Define and declare a separate function for each choice.
In the main body of the program call respective function depending on user’s choice.
Program should not terminate till user chooses last option that is “Quit”.
Task 2
Write a method to calculate Fibonacci Series up to ‘n’ points. After calculating the series, the method should return to the main.
Task 3
Write a program to calculate factorial of a number entered by user.
Task 4
Write a program that lets the user enter in some English text, then convert the text to Pig-latin.
Task 5
Splits the string |text| by whitespace and returns two things as a pair: the set of words that occur the maximum number of times, and their count, i.e. (set of words that occur the most number of times, that maximum number/count) You might find it useful to use collections. Counter().
Check solution here Python Learning Week 2 (Solution)