Escolar Documentos
Profissional Documentos
Cultura Documentos
Python interpreter and interactive mode; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; modules and functions, function definition and use, flow of execution,
parameters and arguments;
Illustrative programs: exchange the values of two variables, circulate the values of n
variables, distance between two points.
Python interpreter :
• Python is Interactive - It means that you can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
• Python is Object-Oriented - It means that Python supports Object Oriented style or
technique of programming that encapsulates code within objects.
• Python is Beginner's Language - Python is a great language for the beginner
programmers and supports the development of a wide range of applications from simple
text processing to www browsers to games.
• Easy-to-maintain - Python's success is that its source code is fairly easy-to-maintain.
• A Broad Standard Library - One of Python's greatest strengths is the bulk of the library
is very portable and cross-platform compatible on UNIX, Windows and Macintosh.
• Portable - Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Extendable - You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• Databases - Python provides interfaces to all major commercial databases.
• GUI Programming - Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh and
the X Window system of Unix.
• Scalable - Python provides a better structure and support for large programs than shell
scripting.
Python
Python is an interpreted, cross-platform, object-oriented language that can be used to write
large scale Internet search engines, small administration scripts, GUI applications, CGI
scripts and more.
Python is a freely distributed technology whose open-source nature has encouraged a
wide base of developers to submit modules that extend the language. Using Python’s core
modules and those freely available on the Web, programmers can develop applications that
accomplish a great variety of tasks. Python’s interpreted nature facilitates rapid application
development (RAD) of powerful programs. GUI applications, in particular, can be tested
quickly and developed using Python’s interface to Tcl/Tk (among other GUI toolkits).
Running Python
There are three different ways to start Python:
Option Description
-d : provide debug output
-O : generate optimized byte code (resulting in .pyo files)
-S : do not run import site to look for Python paths on startup
-v : verbose output (detailed trace on import statements)
-X : disable class-based built-in exceptions (just use strings); obsolete starting with
versionb1.6
-c : cmd run Python script sent in as cmd string
file : run Python script from given file
If you are not able to set up the environment properly, then you can take help from your
system admin. Make sure the Python environment is properly set up and working perfectly
fine.
Note: All the examples given in subsequent chapters are executed with Python 2.4.3
version available on CentOS flavor of Linux.
We already have set up Python Programming environment online, so that you can execute
all the available examples online at the same time when you are learning theory. Feel free
to modify any example and execute it online.
The Python language has many similarities to Perl, C, and Java. However, there are some
definite differences between the languages.
$ python
>>>
Type the following text at the Python prompt and press the Enter:
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to use print statement with
parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this
produces the
following result:
Hello, Python!
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no
longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the
following source code in a test.py file:
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file
#!/usr/bin/python
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to
run this program as follows –
Hello, Python!
Some of the functions like input() and print() are widely used for standard input and
output operations respectively. Let us see the output section first.
Python Output Using print() function
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given
below.
a=5
In the second print() statement, we can notice that a space was added between
the string and the value of variable a. This is by default, but we can change it.
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value
is sys.stdout (screen). Here are an example to illustrate this.
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done
by using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in which it is
printed by using numbers (tuple index).
We can even format strings like the old sprintf() style used in C programming language. We
use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
Python Input
Up till now, our programs were static. The value of variables were defined or hard coded
into the source code.
To allow flexibility we might want to take the input from the user. In Python, we have
the input() function to allow this. The syntax for input() is
input([prompt])
Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
This same operation can be performed using the eval() function. But it takes it further. It
can evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.
For example, we can import the math module by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can also import
some specific attributes and functions only, using the from keyword. For example:
While importing a module, Python looks at several places defined in sys.path. It is a list of
directory locations.
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed
by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are
two different identifiers in Python.
Here are naming conventions for Python identifiers Class names start with an uppercase
letter. All other identifiers start with a lowercase letter. Starting an identifier with a single
leading underscore indicates that the identifier is private. Starting an identifier with two
leading underscores indicates a strongly private identifier. If the identifier also ends with
two trailing underscores, the identifier is a language defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot
use them as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
Keywords in Python programming language
Every value in Python has a datatype. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.
Python Numbers
Integers, floating point numbers and complex numbers falls under Python
numbers category. They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and
the is instance() function to check if an object belongs to a particular class.
Eg:
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", is instance(1+2j,complex))
Answer :
(5, 'is of type', <type 'int'>)
(2.0, 'is of type', <type 'float'>)
((1+2j), 'is complex number?', True)
A floating point number is accurate up to 15 decimal places. Integer and floating points are
separated by decimal points. 1 is integer, 1.0 is floating point number.
Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within
brackets [ ].
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index
starts form 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]
Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# Generates error
# Tuples are immutable
t[0] = 10
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
a = {5,2,3,1,4}
We can perform set operations like union, intersection on two sets. Set have unique values.
They eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator []
does not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
Python Dictionary
It is generally used when we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. Key and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))
# Generates error
print("d[2] = ", d[2]);
Conversion between data types
We can convert between different data types by using different type conversion functions
like int(), float(), str() etc.
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
Python Variables
They are given unique names to differentiate between different memory locations. The
rules for writing a variable name is same as the rules for writing identifiers in Python.
We don't need to declare a variable before using it. In Python, we simply assign a value to a
variable and it will exist. We don't even have to declare the type of the variable. This is
handled internally according to the type of value we assign to the variable.
Variable assignment
We use the assignment operator (=) to assign values to a variable. Any type of value can be
assigned to any valid variable.
a=5
b = 3.2
c = "Hello"
Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of characters)
assigned to the variables b and c respectively.
Multiple assignments
a, b, c = 5, 3.2, "Hello"
If we want to assign the same value to multiple variables at once, we can do this as
x = y = z = "same"
Python Statement
Instructions that a Python interpreter can execute are called statements. For example,
a = 1 is an assignment statement. if statement, for statement, while statement etc. are other
kinds of statements which will be discussed later.
Multi-line statement
a=1+2+3+\
4+5+6+\
7+8+9
This is explicit line continuation. In Python, line continuation is implied inside parentheses
( ), brackets [ ] and braces { }. For instance, we can implement the above multi-line
statement as
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:
colors = ['red',
'blue',
'green']
We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results
into Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It
makes the code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer.
Python Comments
Comments are very important while writing a program. It describes what's going on inside
a program so that a person looking at the source code does not have a hard time figuring it
out. You might forget the key details of the program you just wrote in a month's time. So
taking time to explain these concepts in form of comments is always fruitful.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example:
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
Evaluating expressions
An expression is a combination of values, variables, and operators. If you type an expression
on the command line, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
The evaluation of an expression produces a value, which is why expressions can appear on the
right hand side of assignment statements. A value all by itself is a simple expression, and so is
a variable.
>>> 17
17
>>> x
2
Confusingly, evaluating an expression is not quite the same thing as printing a value.
When the Python shell displays the value of an expression, it uses the same format you would
use to enter a value. In the case of strings, that means that it includes the quotation marks.
But the print statement prints the value of the expression, which in this case is the contents
of the string.
Tuple Assignment :
• A tuple is a sequence of values.
• The values can be any type, and they are indexed by integers
• Example Swap to variables
>>> temp = a
>>> a = b
>>> b = temp
Tuple assignment
>>> a, b = b, a
The left side is a tuple of variables;
the right side is a tuple of expressions
Operators :
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output
of the operation.
Arithmetic operators
Bitwise operators
Assignment operators
Special operators
Arithmetic operators
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
x**y (x to the
** Exponent - left operand raised to the power of right
power y)
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
Logical operators
# Output: x or y is True
print('x or y is',x or y)
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by
bit, hence the name.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Assignment operators
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Special operators
Python language offers some special type of operators like the identity operator or the
membership operator. They are described below with examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does
not imply that they are identical.
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the same x is not
is not
object) True
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Here, we see that x1 and y1 are integers of same values, so they are equal as well as
identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. Since list are mutable (can be
changed), interpreter locates them separately in memory although they are equal.
Membership operators
in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
For example:
>>> 5 - 7
-2
To evaluate these type of expressions there is a rule of precedence in Python. It guides the
order in which operation are carried out.
But we can change this order using parentheses () as it has higher precedence.
The operator precedence in Python are listed in the following table. It is in descending
order, upper group has higher precedence than the lower ones.
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
or Logical OR
If you do not know any CS professional, go to MeetUps. There are Python study groups that
can be a valuable resource at this point.
Girl Develop It (They offer an Intro to Python course. Their approach is hands-on
experience)
Python MeetUp Groups
Let us consider the following:
x=3
x equals to 3
So, when I saw this expression, I freaked out … literally!
x=x+1
***
A variable is a “place holder”. Let us see how this changes our point of view:
x=3
Knowing this, the expression: x = x + 1 is read as: variable x gets the value of x plus one (1).
So, let us call the function ‘print_twice’ that we just created in the Python shell with
the argument “Laaa, lalalalala “:
>>> print_twice (“Laaa, lalalalala “)
Laaa, lalalalala
Laaa, lalalalala
>>>
I stumbled on the fact that the concepts of parameter and variable seemed identical to
me. I understood why:
When we define our function, the most important is to establish what the function will do.
You do not want to start thinking about what you can put in the function. At the creation
stage, you just want your function to work in a particular way. In that case, you will use the
concept of parameter.
Later, when you want to call the function and you know what you want to put in to make it
work, you may use a variable or an argument.
Let us see how the function works with a variablenamed x :
Remember: Variable x gets the value of the following string “Hickory Dickory Dock”
So, we can make our function work with arguments and previously defined variables.
When we use built-in modules in our function definition, here is something to consider:
Remember: A parameter is an information that I want to to consider but I still do not know
the exact value.
Using the user-defined function we created earlier ‘print_twice’, let us try this in the Python
shell, in order to seize this concept.
>>> line1 = “Hickory Dickory Dock” #The variable ‘line1’ gets the value of “Hickory
Dickory Dock”
>>> line2 = “The mouse ran up the clock.” #The variable ‘line2’ gets the value of “The
mouse ran up the clock”
>>> cat_twice (line1, line2) #We will call the function that we created
‘cat_twice’ with the variables ‘line1’ and ‘line2’
Hickory Dickory DockThe mouse ran up the clock.
Hickory Dickory DockThe mouse ran up the clock.
>>> #The result is the concatenation of variables ‘line1’
and ‘line2’ and printed twice
Let us double-check what happens with the variable ‘cat’ that we initially defined in the
function ‘cat_twice’
Furthermore, it is important to notice that the parameter ‘bruce’ is useless outside the
function we defined called ‘print_twice’.
Flow of Execution
When you are working with functions it is really important to know the order in which
statements are executed. This is called the flow of execution and we’ve already talked
about it a number of times in this chapter.
Execution always begins at the first statement of the program. Statements are executed one
at a time, in order, from top to bottom. Function definitions do not alter the flow of
execution of the program, but remember that statements inside the function are not
executed until the function is called. Function calls are like a detour in the flow of
execution. Instead of going to the next statement, the flow jumps to the first line of the
called function, executes all the statements there, and then comes back to pick up where it
left off.
That sounds simple enough, until you remember that one function can call another. While
in the middle of one function, the program might have to execute the statements in another
function. But while executing that new function, the program might have to execute yet
another function!
Fortunately, Python is adept at keeping track of where it is, so each time a function
completes, the program picks up where it left off in the function that called it. When it gets
to the end of the program, it terminates.
What’s the moral of this sordid tale? When you read a program, don’t read from top to
bottom. Instead, follow the flow of execution. This means that you will read
the def statements as you are scanning from top to bottom, but you should skip the body of
the function until you reach a point where that function is called.
y = b ** p
return y
def square(x):
a = pow(x, 2)
return a
n=5
result = square(n)
print(result)
>>>
25
MODULES
A file containing Python code, for e.g.: example.py, is called a module and its module name
would be example.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
result = a + b
return result
Here, we have defined a function add() inside a module named example. The function takes
in two numbers and returns their sum.
Function
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Example of a function
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
Function Call
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
>>> greet('Paul')
>>> findArea(3)
28.27431
Function definition
A function is a block of reusable code that is used to perform a specific action. The
advantages of using functions are:
Functions in Python are first-class citizens. It means that functions have equal status with
other objects in Python. Functions can be assigned to variables, stored in collections, or
passed as arguments. This brings additional flexibility to the language.