Vous êtes sur la page 1sur 26

Python for Beginners

Kandarp Gandhi
EE295
009411649

TABLE OF CONTENTS:

PAGE

INTRODUCTION-------------------------------------------------------------------------------------------------------------1
OBJECTIVE--------------------------------------------------------------------------------------------------------------------1
STEPS FOR INSTALLATION------------------------------------------------------------------------------------------------2
EXERCISE 1-------------------------------------------------------------------------------------------------------------------3
EXERCISE 2-------------------------------------------------------------------------------------------------------------------3
EXERCISE 3-------------------------------------------------------------------------------------------------------------------4
EXERCISE 4-------------------------------------------------------------------------------------------------------------------4
EXERCISE 5-------------------------------------------------------------------------------------------------------------------5
EXERCISE 6-------------------------------------------------------------------------------------------------------------------6
EXERCISE 7-------------------------------------------------------------------------------------------------------------------7
EXERCISE 8-------------------------------------------------------------------------------------------------------------------7
EXERCISE 9-------------------------------------------------------------------------------------------------------------------8
EXERCISE 10-----------------------------------------------------------------------------------------------------------------9
EXERCISE 11-----------------------------------------------------------------------------------------------------------------10
EXERCISE 12-----------------------------------------------------------------------------------------------------------------11
EXERCISE 13-----------------------------------------------------------------------------------------------------------------12
EXERCISE 14-----------------------------------------------------------------------------------------------------------------13
EXERCISE 15-----------------------------------------------------------------------------------------------------------------14
EXERCISE 16-----------------------------------------------------------------------------------------------------------------15
EXERCISE 17-----------------------------------------------------------------------------------------------------------------15
EXERCISE 18-----------------------------------------------------------------------------------------------------------------16
EXERCISE 19-----------------------------------------------------------------------------------------------------------------17
EXERCISE 20-----------------------------------------------------------------------------------------------------------------17
EXERCISE 21-----------------------------------------------------------------------------------------------------------------18
EXERCISE 22-----------------------------------------------------------------------------------------------------------------19
EXERCISE 23-----------------------------------------------------------------------------------------------------------------20
EXERCISE 24-----------------------------------------------------------------------------------------------------------------22
REFERENCE------------------------------------------------------------------------------------------------------------------24
1

INTRODUCTION:
Python is a powerful high-level scripting and programming language. It provides simple readability to
users and coders while simultaneously reducing the number of lines one uses to express an idea when
compared to traditional programming languages like C++ or Java. Python finds its application in a wide
range of areas from computing, statistics to various other fields like bio-numeric calculations. Python
enjoys an upper hand over other languages like Perl due to its fairly easy style of coding and mainly
because for non-computer people, learning computer science concepts become fairly simple.
One of the most important features of Python is the vast collection of libraries that are available
for almost every application. These libraries contain in built functions that can be imported into the file
where one writes the Python code. Another important feature of Python is the use of indentation as
syntax. Python uses white space for indentation, indicating that a new block of code has started. The
keywords that Python uses are easy to understand because they are mostly common English words. The
conditional statements like loops and if are very east to implement in Python. Also, implementation of
arrays and lists can be done without much hassle.
There are many useful features of Python excluding the above mentioned ones. These features
not only make Python a powerful language but also provide users with a language that is easy to pick up.
Python can be easy to learn for people who have no prior programming language experience as it has
such good features.

OBJECTIVE
The main objective of this paper is to teach Python to those people who have some or almost zero
programming experience. This paper aims to teach the fundamentals of Python programming so that
those with no experience in programming can learn how to program and update their skills. Also, all
those students who want to enter into the software industry should read this paper to get the basic
knowledge of Python programming.

STEPS FOR INSTALLING PYTHON:


FOR WINDOWS:
1. Install Python from http://python.org/download.
2. Make sure that you install Python 2 and not Python 3.
RUNNING PYTHON IN WINDOWS:
1.
2.
3.
4.

Go to the start menu and open the Powershell application.


In Powershell, run Python.
If Python does not run, exit Powershell and install Python again and try it again.
If Powershell is still unable to recognize Python run the following script:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27
", "User")
5. In Python, type quit(), and press Enter
6. Learn how to make and change directories in Powershell and also how to open files and close
them.

FOR LINUX:
1. Linux already has the gedit text editor installed in it. Use it for writing the code.
2. In gedit, change the following features:
1. Increase the tab width to 4.
2. Select the checkbox that says Insert spaces instead of tab.
3. Check the Automatic Indentation
4. Also, turn on the display line numbers.
3. Run the XTerm or Terminal in the system.
4. A command line input is needed. Here type python. Python will start
5. Type quit ( ) to exit the application.
6. For using Terminal, learn how to make directory, change a directory and how to access other
files.
NOTE:
Do not install Python 3. Currently, the most popular version to start learning to code is Python 2. If one
begins learning using Python 2, it will be easy to shift on to Python 3, but vice versa will not be easy.
Also, there is no particular operating system that is better to learn Python. If one is comfortable with
Linux, use Linux or else use Windows. Remember, one only needs a text editor, a Terminal or Powershell
and Python to start learning.

EXERCISE 1: THE FIRST PYTHON PROGRAM:


Open the text editor and type the following:
1.
2.
3.
4.
5.

print Hello there world ! How is it going


print This is the first Python Program
print It is going to be fun learning this language
print Oh well ! This stuff is being printed
print Well, it looks nice, doesnt it?

Now, after completing typing the following text in the text editor, save the file with the desired name
and a .py extension. For example, example1.py. It is important to save it in this way as .py indicates
that it is a Python code file.
One of the most important commands in Python is the print command. Print command prints all the
data that is between the double quotes everything as it is. Now, to run the example1.py program, open
terminal and type the following in the command line:
>python example1.py (and press enter).
Make sure that the directory is correct while you enter the following command. If not, there will be an
error.
One should be able to see the following as the output:
$ python example1.py
Hello there world ! How is it going
This is the first Python Program
It is going to be fun learning this language
Oh well ! This stuff is being printed
Well, it looks nice, doesnt it?

EXERCISE 2: USING COMMENTS AND # CHARACTER


Comments are very important in programming. The main role of comments is to explain somewhat what
a command or a line in a program does or how a given block of command works. Also, one may use the
comments to temporarily disable some part of the program when required for various purpose.
Lets see how comments work.
Open a new text file named example2.py and type the following:
1. # This is a comment.
2. # Comments are used to explain how the given part of a code works.
3. # The are useful because it helps to understand how a program works if someone tries to read it
#or if someone who wrote it quite a long time ago wants to check it again.
4. print So this is how comments work and how # is used to start one.

Now, run the following program in the same way like the previous one and observe the output.
One would notice that whatever was written after the # character does not get printed or displayed
in the output. Thus, comments are used to explain parts of code to others.
EXERCISE 3: USING SOME BASIC MATH
Addition, subtraction, multiplication, etc. are simple mathematical operations that can be
performed very easily in Python. The following program will teach how to use mathematical
operations.
Open a new text file and name it example3.py. Write the following code:
print We will now count the number of balls in the court
print Basket balls, 25 + 30 / 5
print Baseballs, 100 - 25 * 3 % 4
print Now, we will count the total number of bats
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
One should get the following output after running it.
$ python example3.py
We will now count the number of balls in the court
Basket balls 31
Baseballs 97
Now, we will count the total number of bats
7

EXERCISE 4: USING NAMES AND VARIABLES


Variables are used in programming to store a name, number, value or anything, which needs to be
used from time to time. Variable names are the meaningful names given to it. These names should
be meaningful because often there are many different variables in a code and it may become
difficult to remember what each one does. For example, the variable name number_of_mangoes
denotes the quantity of mangoes. Lets see more about these in the following code.
Write the given code in a new text file named example4.py
vans = 100
space_in_van = 5
drivers = 30
passengers = 60
Vans_not_driven = vans drivers
vans_driven = drivers
4

carpool_capacity = vans_driven * space_in_van


passenger_per_van = passengers / vans_driven
Print There are, vans, vans available
print Each van has a capacity of, space_in_van, people.
print There will be, vans_not_driven, empty vans today.
print We can send, carpool_capacity, people to work today.
print We have, passengers, to carpool today.
print We can accomodate, passenger_per_van, in each van today.
Also, we can print the above code in another way
Print There are %d vans available % vans
print Each van has a capacity of %d people. % space_in_van
print There will be %d empty vans today. % vans_not_driven
print We can send %d people to work today. % carpool_capacity
print We have %d to carpool today. % passengers
print We can accommodate %d passengers in each van today. % passenger_per_van

One should be able to see the following output in the terminal:


$ python example4.py
There are 100 vans available.
There are only 30 drivers available.
There will be 70 empty vans today.
We can send 150 people to work today.
We have 60 to carpool today.
We can accommodate 2 passengers in each van today.

EXERCISE 5: STRINGS AND TEXT


A string is usually a collection of words or a piece of text that one wants to print or display. Python
recognizes a string when a user puts something between double or single quotes. Multiple strings
can be printed by using () and by separating the variable names for each string by a comma.

A = My name is Bond. James


B = Bond. Code name 007
Print A + B

Answer = True
Question = Are you an engineer? %r
print Question % Answer
The output for this program would be as follows:
$ python example5.py
My name is Bond. James Bond. Code name 007.
Are you an engineer? True

EXERCISE 6: SOME MORE PRINTING AND SPECIAL CHARACTERS


Special characters are used to provide a new line, view in table form, print stuff in the same way as
input, etc. For example, the /n character is known as the new line character. When it is written in a
string, it is identified and a new line is printed. %s prints the input string while %r prints the input as
it is. One would learn more from the following example.
Type the following in a new text file named example6.py
Class = class 1 2 3 4 5 6
names = names\nJohn\nMary\nMathew\nDavid\nPhilip\nPeter
Print Here are the classes: ,class
print Here are the names of the students: , names
Print
One can see that whatever is written in between
Three double-quotes is printed as it is until the
once again a triple double-quote appears.

Here is what the output is for the following code:


$ python example6.py
Here are the class: class 1 2 3 4 5 6
Here are the names of the students: John
Mary
Mathew
David
Philip
Peter
One can see that whatever is written in between
Three double-quotes is printed as it is until the
once again a triple double-quote appears

EXERCISE 7: TAKING INPUT FROM THE USER


So far, the tutorial has been about predefined input. Now, its time to learn how to get input from
the user. User input is important because everyone has a different value to input and hence the
output will vary from user to user.
Lets take an elementary program for this. Type the following code in the text editor and name it
example7.py
print What is the users name ?
name = raw_input()
Print What is the users age ?
age = raw_input ()
print What is users weight?
weight = raw_input ()
print What is the users height?
height = raw_input ()
Print Hi %s ! Your age is %r while you are %r feet tall and weigh %r kgs %( name, age, height,
weight)
The raw_input () function is used for taking input from the user. It waits for the user to input and
then moves to the next line.
The above code can be written in another way also.
name = raw_input (What is the users name?)
age = raw_input ("What is the users age? ")
height = raw_input ("What is the users height? ")
weight = raw_input (What is the users weight? ")
print Hi %s ! Your age is %r while you are %r feet tall and weigh %r kgs % (name, age, height,
weight)
The above code should give the following output:
$ python example7.py
What is the users name ? John
What is the users age? 23
What is the users height? 57
What is the users weight? 54 kgs
Hi John! Your age is 23 while you are 57 feet tall and weigh 54 kgs

EXERCISE 8: PARAMETER, UNPACKING AND VARIABLES


Another method can be used to pass variables to a script (just another name for a python file). It is
known how to run a python file by typing python example1.py. The example1.py is called the
argument. Lets write a script that accepts arguments.
7

Write the following program and name it example8.py


from sys import argv
script, one, two, three = argv
print The script is called:, script
print The first variable is:, one
print The second variable is :, two
print The third variable is :, three
One would see the import function on the line 1. This is used to add the features from Python
modules. Here, the name of the module is sys. The import adds the features that the user wants in
the program and not all of them given in file.
The argv is the argument variable. It holds the arguments one passes to the Python script at the
time it is run. The next line unpacks the argument and assigns it to script, one, two and three.
The output of this code should look as follows:
$ python example8.py mango banana bike
The script is called: example8.py
Your first variable is: mango
Your second variable is: banana
Your third variable is: bike

EXERCISE 9: PROMPT AND PASS


Lets combine argv and raw_input and see how it works in a code.
from sys import argv
script, name = argv
print "Hello %s, this is the %s script" % (name, script)
print "Please answer the following questions."
print "Have you read this file %s?" % name
likes = raw_input(>)
print Indicate the location %s" % name
lives = raw_input(>)
print "What kind of computer do you have?"
computer = raw_input(>)
print """
You answered %r about reading the file.
You live in %r. It must be a nice place.
You use the %r computer. Heard its a fast one.
""" % (likes, lives, computer)
The following code should give the output as below:
8

$ python example9.py john


Hello john, this is the example9 script.
Please answer the following questions.
Have you read this file john?
> Yes
Indicate the location john.
> San Jose
What kind of computer do you have?
> Lenovo T420
You answered Yes about reading the file.
You live in San Jose. It must be a nice place.
You use the Lenovo T420 computer. Heard its a fast one.
EXERCISE 10: READING FILES
This exercise works using two files. One of them is example10.py and the other is the file
example10_sample.txt. The second file is a plain text file and one should use it to read in our script.
One wants to open the file in our script and print it out as it is.
Write the following in the example10_sample.txt file:
Let us write something really cool in the file.
It is a very useful file and will help in understanding the code.
This will be a lot of fun and interesting stuff.
from sys import argv
script, filename = argv
txt = open (filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input ("> ")
txt_again = open (file_again)
print txt_again.read()
The first line uses the argument argv, which is used to get the filename. The open command is used
to open the filename. After opening the file, we store it in variable txt. When we used open
command to open the filename, it returned us with a file. Now we can use read () function on txt
along with print command, which would fetch us all the contents of the file and print it.
The output should look like the following:
$ python example10.py example10_sample.txt
Here's your file 'example10_sample.txt':
Let us write something really cool in the file.
9

It is a very useful file and will help in understanding the code.


This will be a lot of fun and interesting stuff.
Type the filename again:
> example10_sample.txt
Let us write something really cool in the file.
It is a very useful file and will help in understanding the code.
This will be a lot of fun and interesting stuff.
EXERCISE 11: MORE WITH THE SCRIPT
Above exercise gave an introduction of reading using script. There are various things that can be
done using other functions in the script. The following functions are important for a beginner.
close- Similar to the save function in the text editor.
read- Reads the stuff given in the file and can be assigned to a variable
readline- Just reads a single line
truncate- Erases the contents of a given file. Should be used carefully.
write (stuff) - Writes the given stuff into the file. It is important to remember that the write
functions takes a string as a parameter.
Lets write a code that reflects a few of the above functions. Write the following code in
example11.py
from sys import argv
script, filename = argv
print "Erase the file named %r." % filename
print "To stop this process, hit CTRL-C (^C)."
print "To continue this process, hit RETURN."
raw_input ("?")
print "Opening the file..."
goal = open (filename, 'w')
print "Erasing the file. Swoosh!"
goal.truncate ()
print "Please enter three new sentences."
line_a = raw input ("line a: ")
line_b = raw_input ("line b: ")
line_c = raw_input ("line c: ")
print "Copying these lines to the file."
goal.write(line a)
goal.write("\n")
goal.write(line b)
goal.write("\n")

10

goal.write(line c)
goal.write("\n")
print "Closing the new file finally."
goal.close ()
One should be able to see the following output:
$ python ex11.py test.txt
Erase the file named 'test.txt'.
To stop this process, hit CTRL-C (^C).
To continue this process, hit RETURN.
?
Opening the file...
Erasing the file. Swoosh!
Please enter three new sentences.
line a: John is a good man.
line b: The dog is black.
line c: Peter was going to the mall.
Copying these lines to the file.
Closing the new file finally.

EXERCISE 12: DOING MORE WITH FILES


There are literally millions of operations that can be done on files. In this exercise, there will be
Python script used to copy one file to another. It will give a broader idea on file operations.
from sys import argv
from os.path import exists
script, src, dest = argv
print "Copying from %s to %s" % (src, dest)
in_file = open (src)
indata = in_file.read ()
print "The size of the source file is %d bytes " % len (indata)
print "Does the destination file exist? %r" % exists (dest)
print "Press RETURN to continue and Ctrl + C to cancel the operation."
raw_input ()
result = open (dest, 'w')
result.write (indata)
print "Successfully done."

11

result.close ()
in_file.close ()

Now suppose that the src file is a one named test.txt:


echo This is a test file.
The output of the above program should look like this:
$ python example12.py test.txt new_file.txt
Copying from test.txt to new_file.txt
The size of the source file is 21 bytes long
Does the destination file exist? False
Press RETURN to continue and Ctrl + C to cancel the operation.
Successfully done.

EXERCISE 13: FUNCTIONS


Functions are important parts of a program. A function can be named like any variable or string. It
takes in certain parameters or arguments and give out results as per the operation defined inside it.
A function in Python can be created by using def keyword. Lets write a few functions and see how
each one works.
Open the text editor and write the code in a file named example13.py
# define a function to add two numbers
def add (a, b):
a+b=c
print The result of adding %d and %d is %d %( a, b, c)
# prints just the same input
def print_value (var1):
print The value entered is %r % var1
# prints nothing
def print_empty ():
print Empty condition
add (10, 20)
print_value (Python_for_Beginners)
print_empty ()
The output of the above code should be the following:
$ python example13.py

12

The result of adding 10 and 20 is 30


The value entered is Python_for_Beginners
Empty condition

EXERCISE 14: EVEN MORE FUNTIONS


Functions play an important part in programming. They reduce a lot of work when one has to
perform similar operations again and again. What one may not have realized from the above
exercise is that variables in the function are not connected to the variables in the script. Lets see
more in the following program.
Make a new text file example14.py and type down the following code:
def soda_and_burgers (soda_count, no_of_burgers):
print "John has %d soda cans!" % soda_count
print "David has %d burgers!" % no_of_burgers
print "WOW ! Isnt that enough for everybody?!"
print "Lets start the game.\n"
print "Functions can be given numbers directly:"
soda_and_burgers (20, 30)
print "OR, we can use variables from our script:"
soda_cans = 10
cheese_burgers = 50
soda_and_burgers(soda_cans, cheese_burgers)
print "Maths can be done inside the function as well"
soda_and_burgers(10 + 20, 5 + 6)
print "Combination of maths and variables is also possible"
soda_and_burgers(soda_cans + 100, cheese_burgers + 1000)
The output of the program above should look as follows:
We can just give the function numbers directly:
John has 20 soda cans
David has 30 burgers!
WOW ! Isnt that enough for everybody ?
Lets start the game.
OR, we can use variables from our script:
John has 10 soda cans
David has 50 burgers!
WOW ! Isnt that enough for everybody ?
Lets start the game.
13

Math can be done inside as well:


John has 30 soda cans
David has 11 burgers!
WOW ! Isnt that enough for everybody ?
Lets start the game.
Combination of math and variables is also possible
John has 110 soda cans
David has 1050 burgers!
WOW ! Isnt that enough for everybody ?
Lets start the game.
This program shows how a variety of combination of numbers and variables can be used in
functions.

EXERCISE 15: MORE AND MORE FUNCTIONS


Up till now, = has been used to get the answer. Lets introduce the Python keyword return and see
how it works. Type the program given below and save it as example15.py
def add(a, b):
print "Add the numbers %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "Subtract the numbers %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "Multiply the numbers %d * %d" % (a, b)
return a * b
def divide(a, b):
print "Divide the numbers %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# Try this puzzle to know more on how nested functions work
print "Here is a puzzle."
puzzle = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "The answer here is: ", puzzle, "Is it possible to do it orally?"
14

The output of this program should be:


$ python example15.py
Let's do some math with just functions!
Add the numbers 30 + 5
Subtract the numbers 78 4
Multiply the numbers 90 * 2
Divide the numbers 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
Divide the numbers 50 / 2
Multiply the numbers 180 * 25
Subtract the numbers 74 4500
Add the numbers + -4426
The answer is: -4391 Is it possible to do it orally?

EXERCISE 16: READING SOME CODE


The last few exercises have been really tough and it might have been outright boring just looking at
strange symbols and trying to understand it. This exercise will not have any program to write and
observe. Instead, one should go on the internet and try reading some python codes. This exercise
will be more difficult than the previous ones. The goal of this exercise is not understand every piece
of information or code but, to teach the following skills:
1. Looking up Python codes for various resources.
2. Learning how to read code.
3. And trying ones best to at least understand a few lines inside a source code.
To do this exercise, one should visit websites like github.com, bitbucket.com and search for Python.
There will be many projects. Click on anyone of it and open the source code. Start reading the code
and try to understand what is the flow process and what is does. Make a note of keywords and
symbols that seem strange and research on it later.

EXERCISE 17: SOME PRACTICE


Write down the following program to revise and practice what has been taught till now.
print "This will give a brief revision on the work till now"
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
advise = """
\tPython is a very powerful language
with no problem regarding syntax
\n and one can easily learn.
15

Moreover, there are various Python tutorials available


that are interactive and can be done comfortably
\n\t\tThis is an important paper regarding Python
"""
print "**********"
print advise
print "**********"
six = 6
print "This should be six: %s" % six
def formula(begin):
beans = begin * 500
cans = beans / 1000
boxes = cans / 100
return beans, cans, boxes
initial_point = 10000
beans, cans, boxes = formula(initial_point)
print "With an initial point of: %d" % initial_point
print "We'd have %d beans, %d cans, and %d boxes." % (beans, cans, boxes)
initial_point = initial_point / 10
print "This can be done in another way also:"
print "We'd have %d beans, %d cans, and %d boxes." % formula (initial_point)
One should be able to see the following output in the terminal:
This will give a brief revision on the work till now.
You'd need to know 'bout escapes with \ that do
newlines and tabs.
**********
Python is a very powerful language
with no problem regarding syntax
and one can easily learn.
Moreover, there are various Python tutorials available
that are interactive and can be done comfortably
This is an important paper regarding Python
**********
This should be six: 6
With an initial point of: 10000
We'd have 5000000 beans, 5000 cans, and 50 boxes.
This can be done in another way also:
We'd have 500000 beans, 500 cans, and 5 boxes.
One important habit that is helpful is reading the code backwards. Try thinking about the flow of the
program and how it progresses line by line. Also, make sure to read it again for checks and dont
forget to write comments in parts, which are difficult to understand.

16

EXERCISE 18: LOGIC AND TRUTH TABLES


Logic here involves learning simple fundamentals that make real programs work and what is used by
programmers to create sense. This involves memorizing simple truth tables, which will be helpful in
solving complex problems when broken into pieces. These concepts would be exciting initially but
will tend to become boring and tedious as time passes. Memorizing all these tiny bits of logic will
pay off big later while doing more complex problem solving.
To memorize these concepts, follow a simple technique. Take a small time every day and enlist the
task needed to do. Make a habit of writing truth tables every day for a few days. Such activities will
train the brain for learning logic.

EXERCISE 19: BOOLEAN PRACTICE.


Below is a list of small logic exercise. Try writing the answers in a piece of paper and then type the
code in the Terminal. See the output and check the answers.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

True and False


True and True
1 == 0 and 2 == 1
"dogs" == "dogs"
1 == 1 or 2 != 0
True and 1 == 0
False and 0 != 0
True or 1 == 0
"test" == "virus"
1 != 0 and 2 == 1
"test" != "false"
"test" == 1
not (True and True)
not (1 == 0 and 0 != 1)
not (10 == 31 or 1000 == 100)

The following steps will be helpful while solving this exercise:


Find an equality test (== or !=) and replace it with its truth.
Find each and/or inside parentheses and solve those first.
Find each not and invert it.
Find any remaining and/or and solve it.
When finished one should have True or False.

EXERCISE 20: THE IF STATEMENT


The if statement is one of the most important conditional statements in any program. This
statement is a flow control instruction that is implemented only if the condition inside the
17

statement is true. If the condition is false, the if block will be bypassed and the compiler will
execute the remaining commands.
The following program will give more insight into the if statement and its use. Name the below
program as example 20.py and save it.
peter = 20
carl = 30
dan = 15
if peter < carl:
print "Age of carl is more than that of peter."
if peter > carl:
print "Age of peter is more than that of carl."
if peter < dan:
print "Age of dan is more than that of peter."
if peter > dan:
print "Age of peter is more than that of dan!"
dan += 5
if peter >= dan:
print "Peter and dan are greater than or equal in ages."
if peter <= dan:
print "Peter and dan are less than or equal in ages."
if peter == dan:
print "Peter and dan are of equal age."
The output of this program should be as follows:
$ python example20.py
Age of carl is more than that of peter.
Age of peter is more than that of dan.
Peter and dan are greater than or equal in ages.
Peter and dan are less than or equal in ages.
"Peter and dan are of equal age.

EXERCISE 21: ELSE IF STATEMENT


The if else statement is a slight variation of the if statement. In this statement, when the if
condition comes out false, the compiler then executes the else statement. The following program
will give a more clear idea about this.

18

Open a new text file and save it as example21.py


pizzas = 30
burgers= 40
soda = 15
if burgers > pizzas:
print "We should eat the burgers."
elif burgers < pizzas:
print "We should not eat the burgers."
else:
print "We can't decide."
if soda > burgers:
print "The soda is sufficient for everyone"
elif soda < burgers:
print "Should get some more soda cans."
else:
print "Leave it to the people to decide."
if pizzas > burgers:
print "Alright, start eating the pizzas."
else:
print "Fine, let's eat the burgers then."
The output of the program should look as following:
$ python example21.py
We should eat the burgers.
Should get some more soda cans.
Alright, start eating the pizzas.

EXERCISE 22: DECISION MAKING


The last script was an easy program. The next one will take a deeper look on these structures when
an input is taken from the user. Type the following program in a text file and save it as
example22.py.
print "John enters a dark room with two doors. Does he go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a lion here eating a chocolate cake. What does John do?"
print "1. Take the cake."
19

print "2. Scream at the lion."


lion = raw_input("> ")
if lion == "1":
print "The lion eats Johns head off. Scary job!"
elif lion == "2":
print "The lion eats Johns hands and feet. Good job!"
else:
print "Well, doing %s is probably better. Lion sprints away." % lion
elif door == "2":
print "You enter into the endless Pyramids of Egypt."
print "1. Mangoes and potato chips."
print "2. Say hi to Jack Sparrow."
print "3. Understanding stories of the war."
pyramids = raw_input("> ")
if pyramids == "1" or pyramids == "2":
print "Johns body becomes the mummy of a pharaoh. Good job!"
else:
print "The great Ramses calls upon his fighters to kill. Get ready to fight!"
else:
print "John stumble and falls inside a tomb and dies. Sorry!"
The output of the following program should look like this:
$ python ex22.py
John enters a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a lion here eating a chocolate cake. What does John do?
1. Take the cake.
2. Scream at the lion.
> 2
The lion eats Johns hands and feet. Good job!
The important point to understand here is that the program uses an if-statement inside an ifstatement. This is called nesting. It can be used when one decision affects other decision.

EXERCISE 23: LISTS AND LOOPS


Just as the if-statement, a for-loop is also an integral tool for programmers. To use for loops, the
results need to be stored somewhere. A list can be used to store the results. Lists are just a
collection of objects as the name suggests. Lets see some example of lists.

20

Fruits = [mango, banana, tomato, strawberry, pineapple]


students = [John, Mary, David, Morris, Peter, Frank]
weight = [22, 34, 43, 55, 63, 12]
A list always starts with [ bracket. This indicates opening a list. Lastly, ] indicates closing a list. Lets
look at the following program to learn more about it. Open a new text file and save it as
example23.py
counter = [1, 2, 3, 4, 5]
basket = ['apples', 'bananas', 'tomatoes', 'pineapples']
money = [1, '1-dollar', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in counter:
print "This is counter %d" % number
# same as above
for fruit in basket:
print "A fruit of this type is in the basket: %s" % fruit
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in money:
print "John has an amount of %r" % i
# we can also build lists, first start with an empty one
objects = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Appending %d to the current list." % i
# append is a function that lists understand
objects.append(i)
# now we can print them out too
for i in elements:
print "Object in the list was : %d" % i
The output of this program should look like this:
$ python example23.py
This is counter 1
This is counter 2
This is counter 3
This is counter 4
This is counter 5

21

A fruit of this type is in the basket: apples


A fruit of this type is in the basket: bananas
A fruit of this type is in the basket: tomatoes
A fruit of this type is in the basket: pineapples
John has an amount of 1
John has an amount of '1-dollar'
John has an amount of 2
John has an amount of 'dimes'
John has an amount of 3
John has an amount of 'quarters'
Appending 0 to the current list.
Appending 1 to the current list.
Appending 2 to the current list.
Appending 3 to the current list.
Appending 4 to the current list.
Appending 5 to the current list.
Object in the list was: 0
Object in the list was: 1
Object in the list was: 2
Object in the list was: 3
Object in the list was: 4
Object in the list was: 5

EXERCISE 24: WHILE LOOPS


The while loops are also conditional statements. It is written as while (parameter). The loop
executes till the parameter is true and ends when it becomes false. For example, the while loop can
be used to scan a port for data. Till the data is 1, the port is open and when it is 0, the port closes.
An important thing that one should keep in mind is that while loops should be avoided. Try using for
loops instead of while loops.
The following program will make things clearer. Open a new text file and save it as example23.py
after typing the following program.
a=0
count = []
while a < 6:
print "At the top a is %d" % a
count.append(a)
a=a+1
print "count now: ", count
print "At the bottom a is %d" % a
22

print "The count: "


for a in count:
print a
The output of this program should look like this:
$ python example23.py
At the top a is 0
count now: [0]
At the bottom a is 1
At the top a is 1
count now: [0, 1]
At the bottom a is 2
At the top a is 2
count now: [0, 1, 2]
At the bottom a is 3
At the top a is 3
count now: [0, 1, 2, 3]
At the bottom a is 4
At the top a is 4
count now: [0, 1, 2, 3, 4]
At the bottom a is 5
At the top a is 5
count now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5

23

REFERENCES
1. http://learnpythonthehardway.org/book

24

Vous aimerez peut-être aussi