Python Unit 1
Python Unit 1
Chapter 1
1.1 Introduction:
As you might infer from the name high-level language, there are also low-level
languages, sometimes referred to as machine languages or assembly languages.
Loosely speaking, computers can only execute programs written in low-level
languages. Thus, programs written in a high-level language have to be processed before
they can run. This extra processing takes some time, which is a small disadvantage of
high-level languages.
Due to these advantages, almost all programs are written in high-level languages.
Low-level languages are used only for a few specialized applications.
INTERPRETER
SOURCE OUTPUT
CODE
A compiler reads the program and translates it into a low-level program, which can
then be run.
In this case, the high-level program is called the source code, and the translated
program is called the object code or the executable. Once a program is compiled,
you can execute it repeatedly without further translation.
1) In shell mode, you type Python statements into the Python shell and the
interpreter immediately prints the result.
2) In this course, we will be using an IDE (Integrated Development and learning
Environment) called IDLE. When you first start IDLE it will open an
interpreter window.
One has to write when one observers >>>, which is the Python prompt. The
interpreter uses the prompt to indicate that it is ready for instructions.
If we type print 1 + 1 the interpreter will reply 2 and give us another prompt.
>>> print 1 + 1
output
2
Alternatively, you can write a program in a file and use the interpreter to execute the
contents of the file. Such a file is called a script.
Interactive/shell
mode
Script mode
By convention, files that contain Python programs have names that end with .py.
To execute the program run the program
History of Python:
Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.
FEATURES OF PYTHON
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows a student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode, which allows interactive
testing and debugging of snippets of code
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.
GUI Programming: Python supports GUI applications that can be created and ported
Scalable: Python provides a better structure and support for large programs than shell
scripting.
Installing python
Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available on download page The
following different installation options are available.
Windows x86-64 embeddable zip file
Windows x86-64 executable installer
Windows x86-64 web-based installer
Windows x86 embeddable zip file
Windows x86 executable installer
Windows x86 web-based installer
Note:In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1. For
versions 3.0 to 3.4.x, Windows XP is acceptable.
Debugging:
Runtime errors
The second type of error is a runtime error, so called because the error does not
appear until you run the program. These errors are also called exceptions because
they usually indicate that something exceptional (and bad) has happened. Runtime
errors are rare in the simple programs you will see in the first few chapters, so it
might be a while before you encounter one.
Eg
myval=10
a=my val + 10;
Semantic errors
The third type of error is the semantic error. If there is a semantic error in your program, it will run
successfully, in the sense that the computer will not generate any error messages, but it will not do the right
thing. It will do something else. Specifically, it will do what you told it to do
Strings belong to the type str and integers belong to the type int. Less obviously, numbers
with a decimal point belong to a type called float, because these numbers are represented in
a format called floating-point.
>>> type(3.2)
<class ’float’>
What about values like “17” and “3.2”? They look like numbers, but they are in quotation marks
like strings.
>>> type("17")
<class ’str’>
>>> type("3.2")
<class ‘str’> They’re strings. Strings in Python can be enclosed in either single quotes (’) or
double quotes (”):
This example makes three assignments. The first assigns the string "What’s your name?" to
a new variable named message. The second assigns the
integer 17 to n, and the third assigns the floating-point number 3.14159 to pi. The
assignment operator,
=, should not be confused with an equals sign (even though it uses the same character).
Assignment operators link a name, on the left hand side of the operator, with a value, on the
6
right hand side. This is why you will get an error if you enter:
>>> 17 = n
KEYWORDS : these are predefined , reserved words used in programming that have special
meaning .
STATEMENTS :
A statement is a unit of code that the python interpreter can execute .
Eg :
>>>print(1)
1
>>>x=2
>>>print(x)
2
ASSIGNMENT STATEMENTS
A assignment statement creates a new variable and gives it a value
>>>myval=”hello”
>>>y=4
This example makes assignment :
Myval assigns hello , y assigns value 4
7
Python datatypes :
The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them
and the storage method for each of them.
Python has five standard data types-
Numbers
String (unit 2)
List (unit 3)
Tuple (unit 3)
Dictionary (unit 3)
Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them. For example
var1= 1
var2 = 10
Type Conversion
Sometimes it's necessary to perform conversions between the built-in types. To convert
between types you simply use the type name as a function. In addition, several built-in
functions are supplied to perform special kinds of conversions. All of these functions return a
new object representing the converted value.
Function Converting what to what Example
>>> int('2014') 2014
int() string, floating point → integer >>> int(3.141592) 3
>>> float('1.99') 1.99
float() string, integer → floating point >>> float(5) 5.0
number
>>> str(3.141592) '3.141592'
str() integer, float, list, tuple, dictionary >>> str([1,2,3,4]) '[1, 2, 3, 4]'
→ string
8
OPERATORS AND OPERANDS
Operators are special symbols that represent computations like addition and multiplication.
The values the operator uses are called operands. The following are all legal Python
expressions whose meaning is more or less clear
The symbols +, -, *, /, have the usual mathematical meanings. The symbol, **, is the exponentiation
operator. The statement, 5 ** 2, means 5 to the power of 2, or 5 squared in this case. Python also uses
parentheses for grouping, so we can force operations to be done in a certain order just like we can in
mathematics.
When a variable name appears in the place of an operand, it is replaced with its value before the
operation is performed. Addition, subtraction, multiplication, and exponentiation all do what you
expect, but you might be surprised by division. The following operation has an unexpected result:
>>> minute = 59
>>> minute / 60
0 .9833333333333333
Expressions:
>>> 1 + 1
2
>>>a=b+c+10
Types of Operator
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Let us have a look on all operators one by one.
9
* Multiplies values on either side of the operator a * b = 200
Multiplication
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the
power 20
// Floor Division - The division of operands where the 9//2 = 4 and
result is the quotient in which the digits after the 9.0//2.0 = 4.0, -
decimal point are removed. But if one of the operands 11//3 = -4, -
is negative, the result is floored, i.e., rounded away 11.0//3 = -4.0
from zero (towards negative infinity):
2) Python Comparison Operators : These operators compare the values on either sides of them
and decide the relation among them. They are also called Relational operators.
3) Python Assignment Operators : Assume variable a holds 10 and variable b holds 20, then
Operator Description Example
= Assigns values from right side operands to left side c = a + b assigns
operand value of a + b
into c
+= Add It adds right operand to the left operand and assign the c += a is
result to left operand equivalent to c =
c+a
-= Subtract It subtracts right operand from the left operand and c -= a is
assign the result to left operand equivalent to c =
c-a
*= Multiply It multiplies right operand with the left operand and c *= a is
assign the result to left operand equivalent to c =
c*a
/= Divide It divides left operand with the right operand and c /= a is
assign the result to left operand equivalent to c =
c / ac /= a is
equivalent to c =
c/a
%= Modulus It takes modulus using two operands and assign the c %= a is
result to left operand equivalent to c =
c%a
10
**= Exponent Performs exponential (power) calculation on c **= a is
operators and assign value to the left operand equivalent to c =
c ** a
//= Floor It performs floor division on operators and assign c //= a is
Division value to the left operand equivalent to c =
c // a
4) Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
11
Operator Description Example
in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if
specified sequence and false otherwise. x is a member of sequence y.
not in Evaluates to true if it does not finds a variable x not in y, here not in results
in the specified sequence and false otherwise. in a 1 if x is not a member of
sequence y.
7) Python Identity Operators :Identity operators compare the memory locations of two objects.
There are two Identity operators explained below:
Operator Description Example
is Evaluates to true if the variables on either side of the x is y, here is results in
operator point to the same object and false otherwise. 1 if id(x) equals id(y).
is not Evaluates to false if the variables on either side of the x is not y, here is
operator point to the same object and true otherwise. not results in 1 if id(x)
is not equal to id(y).
Python Operators Precedence : The following table lists all operators from highest precedence
to lowest.
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators
The first line assigns a value to miles, but it has no visible effect. The second line is an
expression, so the interpreter evaluates it and displays the result. So we learn that a marathon
is about 42 kilometers.
12
But if you type the same code into a script and run it, you get no output at all. In script mode
an expression, all by itself, has no visible effect. Python actually evaluates the expression, but
it doesn’t display the value unless you tell it to:
miles = 26.2 print miles * 1.61
Script mode:
In script mode, however, Python doesn't automatically display results.you save your file with
py extension and then execute it.
In order to see output from a Python script, we'll introduce the print statement. This statement
takes a list of values and prints their string representation on the standard output file. The
standard output is typically directed to the Terminal window. We'll revisit this in depth
in The printStatement.
Order of Operations:
When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence. Python follows the same precedence rules for its mathematical operators
that mathematics does. The acronym PEMDAS is a useful way to remember the order of
operations:
Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2*(3-1) is 4, and
(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in
(minute*100)/60, even though it doesn’t change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and
not 27.
Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1 is
-1, not 1 (remember that in integer division, 2/3=0).
Comments
Comments are nothing but self=-descibing text that helps programmer to get the information
about the code block
Single line comment :The hash-mark # symbol:
Eg
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
v = 5 # assign 5 to v
13
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
“””
A
B
C
“””
UNIT 1 Chapter 3 : Conditional ,looping and control statements
1) if statement:
The IF statement is similar to that of other languages. The if statement contains a logical
expression using which the data is compared and a decision is made based on the result of the
comparison.
Syntax
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. In Python, statements in a block are uniformly indented after the :
symbol. If boolean expression evaluates to FALSE, then the first set of code after the end of
block is executed.
Eg
n=15
print(n)
if (n>0):
print("Positive number")
output
15
Positive number
2. if else Statements
An else statement can be combined with an if statement. An else statement contains a
block of code that executes if the conditional expression in the if statement resolves to 0 or
a FALSE value.
The else statement is an optional statement and there could be at the most only one else
14
statement following if.
Syntax
The syntax of the if...else statement is-
if expression:
statement(s)
else:
statement(s)
eg :
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Syntax
The syntax of the nested if...elif...else construct may if expression1:
if expression 1
statement(s)
elif expression2:
statement(s)
else:
statement(s)
eg
s=4
t=4
print("s=",s,"t=",t)
15
if (s>t) :
print("s is greater than t")
elif (t>s) :
print("t is greater")
else :
print("s and t are equal")
output :
s= 4 t= 4
s and t are equal
Looping statements:
For loop :
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Eg
n=[1,2,3,4]
for i in n:
print(i)
Output
1
2
3
4
Eg
for i in range(5):
16
print(i)
output
0
1
2
3
4
Eg 2:
for i in range(2,10,2):
print(i)
Output
2
4
6
8
While Loop
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
We generally use this loop when we don't know beforehand, the number of times to iterate.
while test_expression:
Statement(s)
Eg
i=1
while(i<=5):
print(i)
i=i+1
Output
1
2
3
4
5
Control statements:
Terminating loops:
The break statement terminates the loop containing it. Control of the program flows to the
17
statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Syntax :
break
eg
for val in "string":
if val == "i":
break
print(val)
print("The end")
output
s
t
r
the end
Skipping specific conditions
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Syntax
continue
eg
for i in range(4):
if(i==2):
continue
print(i)
output
0
1
3
Pass statement
It is used when a statement is required syntactically but you do not want any command or
code to execute . the pass statement is null operation , nothing happens when it executes ,
18
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
19