Python Unit - 1
Python Unit - 1
INTRODUCTION:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language.
It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available
under the GNU General Public License (GPL). This tutorial gives enough understanding on Python
programming language.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
Characteristics of Python
Following are the some of the important characteristics of Python Programming −
It supports functional and structured programming methods as well as OOP(object oriented programming).
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Features
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the 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.
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 is interpreted, there’s a rapid turnaround after program changes. And because python’s parser is
embedded in python-based systems, it’s easy to modify programs at runtime. For example, we saw how
GUI programs developed with python allow developers to change the code that handles a button press
while the GUI remains active; the effect of the code change may be observed immediately when the
button is pressed again. There's no need to stop and rebuild.
Applications of Python:
Systems Programming
GUIs
Internet Scripting
Component Integration
Database Programming
Rapid Prototyping
Numeric and Scientific Programming
INPUT Function:
To get input from the user you can use the input function. When the input function is called the program
stops running the program, prompts the user to enter something at the keyboard by printing a string called
the prompt to the screen, and then waits for the user to press the Enter key. The user types a string of
characters and presses enter. Then the input function returns that string and Python continues running the
program by executing the next statement after the input statement.
Python provides the function input(). input has an optional parameter, which is the prompt string.
Ex:
# Taking input from the user
# Output
print("Hello", name)
Output:
Enter your name:sai
Hello sai
Ex:
Here, we can see that the entered value 15 is a string, not a number. To convert this into a number we can
use int() or float() functions.
Here, we can see that the entered value 15 is a number, not a string.
OUTPUT function:
We use the print() function or print keyword to output data to the standard output device (screen). This
function prints the object/string written in function.
EX:
Output Formatting:
It is a process of displaying the data/result of the program in a particular format(i.e the way user want to
display the output).In this we use “%,{}” in % we use %d to represent int ,%s to represent string ,%f or
%g for float values
Example:
Program to print person name, age, salary
name=”sai”
age=25
sal=500000
Output:
Type-1
print(name,age,sal)
sai 25 500000
Type-2
print(“Name is:”,name)
print(“Age is:”,age)
print(“Salary is:”,sal)
d=1900.23
f=44.23
print(a,b,c)
print(d,e,f)
output:
12.1345 2423.23 212.698
1900.23 1235.99 44.23
Type-1
print(format(a,’15f’),format(b,’15f’),format(c,’15f’))
print(format(d,’15f’),format(e,’15f’),format(f,’15f’))
output:
12.1345 24234.23 212.698
1900.23 1235.99 44.23
Type-2:
print(format(a,’15,.2f’),format(b,’15,.2f’),format(c,’15,.2f’))
print(format(d,’15,.2f’),format(e,’15,.2f’),format(f,’15,.2f’))
output:
12.13 24234.23 212.69
1900.23 1235.99 44.23
Justification
By default output will print at the right side.We use “<” to print left side and “^” to print at the center.
print(100,200)
output:
100 200
print(format(100,’10d’),format(200,’10d’))
output:
100 200
print(format(100,’<10d’),format(200,’<10d’))
output:
100 200
print(format(100,’^10d’),format(200,’^10d’))
output:
100 200
COMMENTS:
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
In Python, there are two types to give comments.
1. Single Line Comment
2. Multi Line Comment
Single Line Comment
To give comments in a single line it should starts with a # (Hash), and Python will ignore them:
Program:
# This is a comment
print(“WELCOME”)
Output:
WELCOME
# A floating point
salary = 1456.8
# A string
name = "sai"
print(age)
print(salary)
print(name)
Output:
45
1456.8
Sai
KEYWORDS
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.
c) Complex Numbers:
A Complex number is defined in python using a real component + and an imaginary component j. The letter
j must be used to denote the imaginary component.
a = 4+2j a = 4+2i
Program
print(type(a)) print(type(a))
Output <class 'complex'> SyntaxError: invalid syntax
2. Boolean Data Types:
The Boolean data types are either True or False. Boolean variables are defined by the True and False
keywords. The Keywords True and False have an uppercase first letter.
a = True a = False
Program
print(type(a)) print(type(a))
Output <class 'bool'> <class 'bool'>
Subsets of strings can be taken using the slice operator ( [ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end. The plus (+) sign is the string
concatenation operator and the asterisk (*) is the repetition operator.
Negative
-7 -6 -5 -4 -3 -2 -1
Indexing
Positive
0 1 2 3 4 5 6
Indexing
Data W E L C O M E
Program: Output:
str ="WELCOME" WELCOME
print(str) W
print(str[0] ) LCO
print(str[2:5] ) MOC
print(str[-2:-5:-1] ) LCOME
print(str[2:] ) WELCOMEWELCOME
print(str * 2) WELCOMECSE
print(str + "CSE")
Data Type Conversion:
Sometimes, you may need to perform conversions between the built-in types. To convert between types, you
simply use the type name as a function. For example, it is not possible to perform “2”+4 since one operand
is integer and the other is string type. To perform this we have convert string to integer i.e., int(“2”) + 4 = 6.
There are several built-in functions to perform conversion from one data type to another. These functions
return a new object representing the converted value.
Function Description
int(x [,base]) Converts x to an integer.
long(x [,base] ) Converts x to a long integer.
float(x) Converts x to a floating-point number.
Types of Operators:
Python language supports the following types of operators.
1. Arithmetic Operators +, -, *, /, %, **, //
2. Comparison (Relational) Operators = =, ! =, < >, <, >, <=, >=
3. Assignment Operators =, +=, -=, *=, /=, %=, **=, //=
4. Logical Operators and, or, not
5. Bitwise Operators &, |, ^, ~,<<, >>
6. Membership Operators in, not in
7. Identity Operators is, is not
Arithmetic Operators:
Program:
a = 20
b = 30
print(a<b) #True
print(a>b) #False
print(a!=b) #True
print(a==b) #False
print(a<=b) #True
print(a>=b) #False
Assignment Operators
Program:
a = 82
b = 27
a += b
print(a) #112
c = 25
d = 12
c -= d
print(c) #13
Logical Operators
Program:
a = 21
b=0
print(a and b) # False
print(a or b) # True
print(not b) # True
Bitwise Operators
Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
Program:
a=3
data = [1, 2, 3, 4, 5]
print(a in data) # True
print(a not in data) # False
7. Identity Operators
Identity operators compare the memory locations of two objects.
Program:
a = 20
b = 20
print(id(a)) # 1640508864
print(id(b)) # 1640508864
print(id(a) == id(b)) # True print(a is b) # True
print(a is not b) # False
Operator Description
() Parenthesis
** Exponentiation (raise to the power)
~x, +x, -x Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
VKR,VNB &AGKCOLLEGE OF ENGINEERING
Unit-1 Python programming
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression
Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first
and then replaces the previous value of the variable on the left hand side. All variables used in the
expression must be assigned values before evaluation is attempted.
Program:
a, b, c = 10, 22, 34
x=a*b+c
y=a-b*c
z=a+b+c*c-a
print("x=", x) # 254
print("y=", y) # -738
print("z=",z) # 1178
Modules:
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a module makes
the code easier to understand and use. It also makes the code logically organized.
Syntax:
import module
When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches for importing a module.
to import the module calc.py
Output:
12
Output:
4.0
720
The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the
module, it is not recommended to use *, else do so.
Example: Importing all names
Output
4.0
720
Output
4.0
720
Decision Making:
Decision making is anticipation of conditions occurring while execution of the program and specifying
actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to
determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the programming
languages:
Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero
or null, then it is assumed as FALSE value.
Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements.
if...else statements if statement can be followed by an optional else statement, which executes
when the boolean expression is FALSE.
nested if statements You can use one if or else if statement inside another if or else if
statement(s).
The if Statement
It is similar to that of other languages. The if statement contains a logical expression using which data is
compared and a decision is made based on the result of the comparison.
Syntax:
if condition:
statements
First, the condition is tested. If the condition is True, then the statements given after colon (:) are
executed. We can write one or more statements after colon (:).
Example:
a=10
b=15
if a < b:
print(“B is big”)
print(“B value is”,b)
Output:
B is big
B value is 15
statement(s)
Example:
a=48
b=34
if a < b:
print(“B is big”)
print(“B value is”, b)
else:
print(“A is big”)
print(“A value is”, a)
print(“END”)
Output:
A is big
A value is 48
END
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
else:
statement(s)
Decision Loops
In general, statements are executed sequentially: The first statement in a function is executed first, followed
by the second, and so on. There may be a situation when you need to execute a block of code several number
of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following
VKR,VNB &AGKCOLLEGE OF ENGINEERING
Unit-1 Python programming
Python programming language provides following types of loops to handle looping requirements.
Here, statement(s) may be a single statement or a block of statements.The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition
becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method of
grouping statements.
Example:
num =0
Output
num = 1
num = 2
num = 3
num = 4
num = 5
----------------------------------------------------------------------------------------------------
num = 0
while num < 5:
num += 1 # num += 1 is same as num = num + 1
print('num = ', num)
if num == 3: # condition before exiting a loop
break
Output
num = 1
num = 2
num = 3
----------------------------------------------------------------------------------------------------
num = 0
while num>=0:
num = int(input('enter any number .. -1 to exit: '))
if num >= 0:
count = count + 1 # this counts number of inputs
sum = sum + num # this adds input number cumulatively.
avg = sum/count
print('Total numbers: ', count, ', Average: ', avg)
Output
enter any number .. -1 to exit: 10
enter any number .. -1 to exit: 20
enter any number .. -1 to exit: 30
enter any number .. -1 to exit: -1
Total numbers: 3, Average: 20.0
The first element of the sequence is assigned to the variable written after ‘for’ and then the
statements are executed. Next, the second element of the sequence is assigned to the variable and then the
statements are executed second time. In this way, for each element of the sequence, the statements are
executed once. So, the for loop is executed as many times as there are number of elements in the sequence.
Nested Loop:
It is possible to write one loop inside another loop. For example, we can write a for loop
inside a while loop or a for loop inside another for loop. Such loops are called “nested loops”.
Example
for i in range(1,6):
for j in range(1,4):
if i==1 or j==1 or i==3 or i==5:
print("*",end=' ')
else:
print(" ",end=' ')
print("")
output
time module;
We have a method called time() in the time module in python, which can be used to get the current time. See
the following steps to calculate the running time of a program using the time() function of time module.
Store the starting time before the first line of the program executes.
Store the ending time after the last line of the program executes.
The difference between ending time and starting time will be the running time of the program.
Example:
import time
# starting time
start = time.time()
# end time
end = time.time()
Output:
0
1
2
3
4
5
6
7
8
9
Runtime of the program is 10.030879974365234
timeit module:
The timeit() method of the timeit module can also be used to calculate the execution time of any program in
python. The timeit() method accepts four arguments. Let's see what are these arguments:
1. setup, which takes the code which runs before the execution of the main program, the default value
is pass
2. stmt, is a statement which we want to execute.
3. timer, is a timeit.Timer object, we don't have to pass anything to this argument.
4. number, which is the number of times the statement will run.
Example:
import timeit
statement = """
for i in range(10):
factorial(i)
"""
Output:
Execution time is 7.536292599999996
Previous questions