Python review
Python
• Open source general-purpose language.
• Object Oriented, Procedural, Functional
• Easy to interface with C/ObjC/Java/Fortran
• Easy-ish to interface with C++ (via SWIG)
• Great interactive environment
• Downloads: http://www.python.org
• Documentation: http://www.python.org/doc/
• Free book: http://www.diveintopython.org
Why Use Python?
Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading, and
multiple inheritance
It's free (open source)
Downloading and installing Python is free and easy
Source code is easily accessible
Free doesn't mean unsupported! Online Python community is huge
It's portable
Python runs virtually every major platform used today
As long as you have a compatible Python interpreter installed, Python programs will
run in exactly the same manner, irrespective of platform
It's powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, SciPy)
Automatic memory management
Running Programs
% python filename.py
You could make the *.py file executable and add
the following #!/usr/bin/env python to the top to
make it runnable.
Monday, October 19, 2009
Introduction to Python
Python is an easy to learn, powerful programming language. It has
efficient high-level data structures and a simple but effective
approach to object-oriented programming. Python’s elegant syntax
and dynamic typing, together with its interpreted nature, make it an
ideal language for scripting and rapid application development in
many areas on most platforms.
The Python interpreter and the extensive standard library are freely
available in source or binary form for all major platforms from the
Python Web site,https://www.python.org/, and may be freely
distributed. The same site also contains distributions of and pointers
to many free third party Python modules, programs and tools, and
additional documentation
Technical Issues
Installing & Running Python
Monday, October 19, 2009
Installing
• Python comes pre-installed with Mac OS X and
Linux.
• Windows binaries from http://python.org/
Monday, October 19, 2009
Installing
Batteries Included
• Large collection of proven modules included in the
standard distribution.
http://docs.python.org/modindex.html
https://docs.python.org/2/tutorial/index.html
Monday, October 19, 2009
History of Python
• Python
– Designed to be portable and extensible
• Originally implemented on UNIX
• Programs often can be ported from one operating
system to another without any change
– Syntax and design promote good programming
practices and surprisingly rapid development
times
• Simple enough to be used by beginning programmers
• Powerful enough to attract professionals
ICP: Chapter 1: Introduction to Python
August 29, 2005 10
Programming
Python IDLE
After installing the IDLE then you can start writing your
program as following:
ICP: Chapter 1: Introduction to Python
August 29, 2005 11
Programming
Run your program
• Go to menu File
• Make a new file
• Give name for the new file such as
• FirstProgram.py and then save .py
• You can start to write your code.
• If you want to run then go to run choose run
Module or press F5
Your First Python Program
print (“Game Over”)
– Press F5
ICP: Chapter 1: Introduction to Python
August 29, 2005 13
Programming
Your First Python Program
• Python is “case-sensitive”
– print “Game Over”
– Print “Game Over” //error
– PRINT “Game Over” //error
ICP: Chapter 1: Introduction to Python
August 29, 2005 14
Programming
Your First Python Program
• In Python, this computer instruction is called a
“statement”
– Command (like a verb) (print)
– Expression (like a value) (“Game Over”)
• More specifically, “Game Over” is called a
string expression
– A series of characters between “ “
ICP: Chapter 1: Introduction to Python
August 29, 2005 15
Programming
Syntax Errors
• When the computer does not recognize the
statement to be executed, a syntax error is
generated
• Analogous to a misspelled word in a
programming language
– Bug
>>> primt “Game Over” //error
why?
SyntaxError: invalid syntax
ICP: Chapter 1: Introduction to Python
August 29, 2005 16
Programming
Programming in Script Mode
• Interactive mode gives you immediate
feedback
• Not designed to create programs to save and
run later
• Script Mode
– Write, edit, save, and run (later)
• Word processor for your code
• Save your file using the “.py” extension
ICP: Chapter 1: Introduction to Python
August 29, 2005 17
Programming
Program Documentation
• Comment lines provide documentation about
your program
– Anything after the “#” symbol is a comment
– Ignored by the computer
# Ima P Programmer
# First Python Program
# September 1, 2005
ICP: Chapter 1: Introduction to Python
August 29, 2005 18
Programming
Variables.
●
A variable is a name that refers to a value.
●
Variables let us store and reuse values in
several places.
●
But to do this we need to define the variable,
and then tell it to refer to a value.
● We do this using an assignment statement.
Input values from the Keyboard
Data Types in Python
• Python supports four different numerical types −
• int (signed integers) − They are often called just integers or ints, are
positive or negative whole numbers with no decimal point.
• long (long integers ) − Also called longs, they are integers of unlimited
size, written like integers and followed by an uppercase or lowercase L.
• float (floating point real values) − Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and
fractional parts. Floats may also be in scientific notation, with E or e
indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
• complex (complex numbers) − are of the form a + bJ, where a and b
are floats and J (or j) represents the square root of -1 (which is an
imaginary number). The real part of the number is a, and the imaginary
part is b. Complex numbers are not used much in Python programming.
Number Type Conversion
• Python converts numbers internally in an expression containing
mixed types to a common type for evaluation. But sometimes, you
need to coerce a number explicitly from one type to another to
satisfy the requirements of an operator or function parameter.
• Type int(x) to convert x to a plain integer.
• Type long(x) to convert x to a long integer.
• Type float(x) to convert x to a floating-point number.
• Type complex(x) to convert x to a complex number with real part x
and imaginary part zero.
• Type complex(x, y) to convert x and y to a complex number with
real part x and imaginary part y. x and y are numeric expressions
• Casting is when you convert a variable value
from one type to another. This is, in Python,
done with functions such
as int() or float() or str(). A very common
pattern is that you convert a number, currently
as a string into a proper number.
Example
• >>> x = '100'
• >>> y = '-90'
• >>> print (x + y)
• 100-90
• >>> print (int(x) + int(y) )
• 10
Ex2
Prompting from Keyboard
• For entering value from key board we can use
as following :
• X=input(“enter you text” )// hello Ahmad
• Print (x)
• the output Hello Ahmad
Reading value from the keyboard
• For reading value from the keyboard we can
use “eval” which converts the string to values
• Example :
• >>x=eval(input(“enter your number”)) //5
• >>y =eval(input(“enter your number”)) //10
• >>x+y
• >> 15
• Or we can use as following
• X=int(input(“enter the value”)) //5
• y=int(input(“enter the value”)) //10
• X+y=15
• Also
• X=float(input(“enter the value”)) //5.0
• y=float(input(“enter the value”)) //10.0
Casting in Python
If Statements
• Let’s try a guess-a-number program. The
computer picks a random number, the player
tries to guess, and the program tells them if
they are correct. To see if the player’s guess is
correct, we need something new, called an if
statement
To select number from 1-10
randomly
If Statement
• The guess-a-number game works, but it is pretty
simple. If the player guesses wrong, nothing
happens. We can add to the if statement as follows:
Conditional operators
Common Mistakes
elif
• A simple use of an if statement is to assign letter
grades. Suppose that scores 90 and above are A’s,
scores in the 80s are B’s, 70s are C’s, 60s are D’s, and
anything below 60 is a F. Here is one way to do this:
• The code above is pretty straightforward and it
works. However, a more elegant way to do it is
shown below.
Exercises
• 1. Write a program that asks the user to enter a length in centimeters. If the user enters
a negative length, the program should tell the user that the entry is invalid. Otherwise,
the program should convert the length to inches and print out the result. There are
2.54 centimeters in an inch.
• 2. Ask the user for a temperature. Then ask them what units, Celsius or Fahrenheit, the
temperature is in. Your program should convert the temperature to the other unit. The
conversions are F = 9/5C + 32 and C = 59(F -32).
No Braces
• Python uses indentation instead of braces to
determine the scope of expressions
• All lines must be indented the same amount to be
part of the scope (or indented more if part of an inner
scope)
• This forces the programmer to use proper indentation
since the indenting is part of the program!
For Loop
• Example 1 The following program will print
Hello ten times:
• for i in range(10):
print('Hello')
• The structure of a for loop is as follows:
• for variable name in range( number of times
to repeat ):
• statements to be repeated
• Example 2 The program below asks the user for a
number and prints its square, then asks for
• another number and prints its square, etc. It does
this three times and then prints that the loop is
done.
The Output
The first two print statements get executed
once, printing an A followed by a B. Next,
the C’s and
D’s alternate five times. Note that we don’t
get five C’s followed by five D’s. The way
the loop
works is we print a C, then a D, then loop
back to the start of the loop and print a C
and another D,
etc. Once the program is done looping with
the C’s and D’s, it prints one E.
The loop variable
• When the loop first starts, Python sets the
variable i to 0. Each time we loop back up,
Python
• increases the value of i by 1. The program loops
100 times, each time increasing the value of i by
1, until we have looped 100 times. At this point
the value of i is 99.
• Example—
• Since the loop variable, i, gets increased by 1 each time
through the loop, it can be used to keep
• track of where we are in the looping process. Consider the
example below:
The range function
• The value we put in the range function
determines how many times we will loop. The
way range works is it produces a list of
numbers from zero to the value minus one.
For instance, range(5) produces five values: 0,
1, 2, 3, and 4.
Range Function
• If we want the list of values to start at a value other than 0, we can do that by
specifying the starting value. The statement range(1,5) will produce the list 1, 2, 3, 4.
This brings up one quirk of the range function—it stops one short of where we think it
should. If we wanted the list to contain the numbers 1 through 5 (including 5), then we
would have to do range(1,6). Another thing we can do is to get the list of values to go
up by more than one at a time. To do this, we can specify an optional step as the third
argument. The statement range(1,10,2) will step through the list by twos, producing 1,
3, 5, 7, 9.
• To get the list of values to go backwards, we can use a step of -1. For instance,
range(5,1,-1) will produce the values 5, 4, 3, 2, in that order. (Note that the range
function stops one short of the ending value 1). Here are a few more examples:
Here are a few more examples:
While loops
• We have already learned about for loops, which allow us to repeat
things a specified number of
• times. Sometimes, though, we need to repeat something, but we
don’t know ahead of time exactly
• how many times it has to be repeated. For instance, a game of Tic-
tac-toe keeps going until someone
• wins or there are no more moves to be made, so the number of
turns will vary from game to game.
• This is a situation that would call for a while loop.
• Example 1 Let’s go back to the first program we wrote back in
Section 1.3, the temperature converter.
• One annoying thing about it is that the user has to restart the
program for every new temperature.
• A while loop will allow the user to repeatedly enter temperatures. A
simple way for the user to indicate that they are done is to have
them enter a nonsense temperature like 1000 (which is below
absolute 0). This is done below:
Loop
• Example 2 One problem with the previous program is
that when the user enters in 1000 to quit, the
program still converts the value 1000 and doesn’t
give any message to indicate that the program has
ended. A nicer way to do the program is shown
below.
While-For Loop
• Example 4
• We can use a while loop to mimic a for loop,
as shown below. Both loops have the exact
same effect.
While Loops-Example
>>> import whileloop
1
x=1 2
while x < 10 : 3
print(x) 4
x=x+1 5
6
7
8
In whileloop.py 9
>>>
In interpreter
Loop Control Statements
break Jumps out of the closest
enclosing loop
continue Jumps to the top of the closest
enclosing loop
pass Does nothing, empty statement
placeholder
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)
x=1
~: python whileelse.py
while x < 3 : 1
print (x) 2
hello
x=x+1
else:
print ('hello‘) Run from the command line
In whileelse.py
The Loop Else Clause
x=1
while x < 5 :
print (x)
x=x+1
break
else :
print (‘got here‘) ~: python whileelse2.py
1
whileelse2.py
Basic Statements: The While Statement (1)
While statements have the following basic structure:
# inside the interpreter # inside a script
>>> while condition: while condition:
... action action
...
>>>
As long as the condition is true, the while statement will execute the action
Example:
>>> x = 1
>>> while x < 4: # as long as x < 4...
... print x**2 # print the square of x
... x = x+1 # increment x by +1
...
1 # only the squares of 1, 2, and 3 are printed, because
4 # once x = 4, the condition is false
9
>>>
Basic Statements: The While Statement (2)
Pitfall to avoid:
While statements are intended to be used with changing conditions. If the condition
in a while statement does not change, the program will be stuck in an infinite loop
until the user hits ctrl-C.
Example:
>>> x = 1
>>> while x == 1:
... print ('Hello world‘)
...
Since x does not change, Python will continue to print “Hello world” until interrupted
Basic Statements: The For Statement (1)
For statements have the following basic structure:
for item i in set s:
action on item i
# item and set are not statements here; they are merely intended to clarify the
relationships between i and s
Example:
>>> for i in range(1,7):
... print (i, i**2, i**3, i**4)
...
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
>>>
Function & Returns
• abs(x) The absolute value of x: the (positive) distance
between x and zero.
• ceil(x) The ceiling of x: the smallest integer not less
than x
• cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y
• exp(x) The exponential of x: ex
• fabs(x)The absolute value of x.
• floor(x)The floor of x: the largest integer not greater
than x
• log(x)The natural logarithm of x, for x> 0
Function & Returns
• log10(x)The base-10 logarithm of x for x> 0.
• max(x1, x2,...)The largest of its arguments: the value closest to
positive infinity
• min(x1, x2,...)The smallest of its arguments: the value closest to
negative infinity
• modf(x)The fractional and integer parts of x in a two-item tuple. Both
parts have the same sign as x. The integer part is returned as a float.
• pow(x, y)The value of x**y.
• round(x [,n])x rounded to n digits from the decimal point. Python
rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-
0.5) is -1.0.
• sqrt(x)The square root of x for x > 0
Escape Meaning
\\ \
\' '
\” “
\n newline
\t tab
\N{id} unicode dbase id
\uhhhh unicode 16-bit hex
\Uhhhh... Unicode 32-bit hex
\x Hex digits value hh
\0 Null byte (unlike C, doesn't end
string)
End
Thank You