0% found this document useful (0 votes)
40 views

Python Unit - 1

Uploaded by

garlapatikomal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Python Unit - 1

Uploaded by

garlapatikomal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit-1 Python programming

V.K.R, V.N.B & A.G.K COLLEGE OF ENGINEERING::GUDIVADA


(Approved by AICTE, New Delhi & Affiliated to JNTUK, Kakinada)
An ISO 9001:2015 Certified Institute
Gudivada , Krishna District, Andhra Pradesh - 521301

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.

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Python Development Life Cycle:


Python's development cycle is shorter than the traditional tools. In Python, there are no compile or link steps
-- Python programs simply import modules at runtime and use the objects they contain, because of this,
Python programs run immediately after changes are made, and in cases where dynamic module reloading
can be used, it's even possible to change and reload parts of a running program without stopping.

Fig.: Traditional Development Cycle Fig.: Python Development Cycle

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.

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Ex:
# Taking input from the user

name = input("Enter your name")

# 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:

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

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)

Nmes is: sai


Age is: 25
Salary is :500000
Type-3(using % here data type is important)
print(“Nae is:%s Age is:%d salary is:%g”%(name,age,sal))

Name is: sai Age is:25 salary is:500000


Type-4({} here vale is important)

print(“Name:{} Age:{} Salary:{}”.format(name,age,sal))

Name:sai Age:25 Salary:500000

In this we pass same value in the format function


print(“Name:{} Age:{} Salary:{}”.format(age,name,sal))

Name:25 Age:sai Salary:500000

print(“Name:{} Age:{} Salary:{}”.format(age,age,sal))

Name:25 Age:25 Salary:500000


Type-5(passing index value)
print(“Name:{0} Age:{1} Salary:{2}”.format(name,age,sal))

Name:sai Age:25 Salary:500000


Precision(for decimal values)
Price=135.6785
Print(format(price,’.2f’))
Output:
135.67
Field width:
a=12.134
b=2423.23
c=212.698

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

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

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Multi Line Comment


To give comments in a multi line it should starts with a """ (Double quotes 3 times), and Python will
ignore them:
Program:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Output:
Hello, World!
Variables:
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you have to reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
Rules for creating variables in Python:
 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
 Variable names are case-sensitive (name, Name and NAME are three different variables).
 The reserved words(keywords) cannot be used naming the variable.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable. For example –
Program:
# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "sai"

print(age)
print(salary)
print(name)

Output:
45
1456.8
Sai

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Multiple Assignments to variables:


Python allows you to assign a single value to several variables simultaneously.
For example –
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables.
For example –
a, b, c = 1, 2.5, ”sai”
Here, both integer and float objects with values 1 and 2.5 are assigned to variables a and b respectively, and
one string object with the value "sai" is assigned to the variable c.

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.

and elif if print


as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
Standard Data Types:
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 following data types:
1. Numeric Data types
2. Boolean Data type
3. Character Data type
1. Numeric Data Types:
Number data types store numeric values. Number objects are created when you assign a value to them.
Python supports four different numerical types:
a) int (signed integers)
b) float (floating point real values)
c) complex (complex numbers)
a) int (signed integers)
Integers are one of the data types. An integer is a whole number, negative, positive or zero. In
python, integer variables are defined by assigning a whole number to a variable.

a=5 a = -56 a = 5454878785648324


Program
print(type(a)) print(type(a)) print(type(a))
Output <class 'int'> <class 'int'> <class 'int'>
b) Floating Point Numbers:
Floats are decimal, positive, negative and zero. Floats can also be represented by numbers in scientific
notation which contain exponents.
Either a lower case ‘e’ or an uppercase ‘E’ can be used to define floats in scientific notation. In python, a
float can be defined using a decimal point (.) when a variable is assigned.
a = 6.23 a = -5.2154548987884 a = 5.02E+23
Program
print(type(a)) print(type(a)) print(type(a))
Output <class 'float'> <class 'float'> <class 'float'>
VKR,VNB &AGKCOLLEGE OF ENGINEERING
Unit-1 Python programming

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'>

3. Character Data Types:


Strings are sequence of letters, numbers, symbols and spaces. In python, strings can be almost any length
and can contain spaces. Strings are assigned in python using single quotation ' ' or double quotation " ".

str1 = 'X' str1 = 'sai' str1 = "X" str1 = "sai"


Program
print(type(str1)) print(type(str1)) print(type(str1)) print(type(str1))
Output <class 'str'> <class 'str'> <class 'str'> <class 'str'>

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.

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

complex(real [,imag]) Creates a complex number.


str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary, d must be a sequence of (key, value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

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:

Operator Description Example


+ Addition Adds values on either side of the operator. c=a+b
- Subtraction Subtracts right hand operand from left hand operand. c=a–b
* Multiplication Multiplies values on either side of the operator c=a*b
/ Division Divides left hand operand by right hand operand c=b/a
Divides left hand operand by right hand operand and
% Modulus c=b%a
returns remainder
Performs exponential (power) calculation on
** Exponent c = a**b
operators
The division of operands where the result is the
// Floor Division quotient in which the digits after the decimal point c = a//b
are removed.
Program: Output:
a = 21 Addition is 31
b = 10 Subtraction is 11
print("Addition is", a + b) Multiplication is 210
print("Subtraction is ", a - b) Division is 2
print("Multiplication is ", a * b) Modulus is 1
print("Division is ", a / b) Power value is 8
print("Modulus is ", a % b) Floor Division is 2
a, b = 2, 3
print("Power value is ", a ** b)
a = 10
b=4
print("Floor Division is ", a // b)

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Comparison (Relational) Operators

Operator Description Example


If the values of two operands are equal, then the
== (a == b) is not true.
condition becomes true.
If values of two operands are not equal, then condition
!= (a != b) is true.
becomes true.
If values of two operands are not equal, then condition (a <> b) is true. This is
<>
becomes true. similar to != operator.
If the value of left operand is greater than the value of
> (a > b) is not true.
right operand, then condition becomes true.
If the value of left operand is less than the value of right
< (a < b) is true.
operand, then condition becomes true.
If the value of left operand is greater than or equal to the
>= (a >= b) is not true.
value of right operand, then condition becomes true.
If the value of left operand is less than or equal to the
<= (a <= b) is true.
value of right operand, then condition becomes true.

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

Operator Description Example


Assigns values from right side operands to c = a + b assigns value of
=
left side operand a + b into c
+= It adds right operand to the left operand and
c += a  c = c + a
Add AND assign the result to left operand
-= It subtracts right operand from the left
c -= a  c = c - a
Subtract AND operand and assign the result to left operand
*= It multiplies right operand with the left
c *= a  c = c * a
Multiply AND operand and assign the result to left operand
/= It divides left operand with the right
c /= a  c = c / a
Divide AND operand and assign the result to left operand
%= It takes modulus using two operands and
c %= a  c = c % a
Modulus AND assign the result to left operand
Performs exponential (power) calculation
**=
on operators and assign value to the left c **= a  c = c ** a
Exponent AND
operand
//= It performs floor division on operators and
c //= a  c = c // a
Floor Division assign value to the left operand

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Program:
a = 82
b = 27
a += b
print(a) #112
c = 25
d = 12
c -= d
print(c) #13

Logical Operators

Operator Description Example


And If both the operands are true then condition (a and b) is
Logical AND becomes true. true.
Or If any of the two operands are non-zero then
(a or b) is true.
Logical OR condition becomes true.
not Not (a and b) is
Used to reverse the logical state of its operand.
Logical NOT false.

Program:
a = 21
b=0
print(a and b) # False
print(a or b) # True
print(not b) # True

Bitwise Operators

Operator Description Example


& Operator copies a bit to the result if it
Binary AND exists in both operands.
| It copies a bit if it exists in either
Binary OR operand.
a = 61
^ It copies the bit if it is set in one
b = 13
Binary XOR operand but not both.
c = a&b
~
It is unary and has the effect of print(c) # 12
Binary Ones
'flipping' bits. d = a|b
Complement
print(d) # 61
The left operands value is moved left
<< e = ~a
by the number of bits specified by the
Binary Left Shift print(e) # -61
right operand.
The left operands value is moved
>>
right by the number of bits specified
Binary Right Shift
by the right operand.

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.

Operator Description Example

Evaluates to true if it finds a variable in x in y, here in results in a 1 if


In
the specified sequence and false otherwise. x is a member of sequence y.
Evaluates to true if it does not finds a x not in y, here not in results
not in variable in the specified sequence and in a 1 if x is not a member of
false otherwise. sequence y.

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.

Operator Description Example


Evaluates to true if the variables on
x is y, here is results in 1 if
is either side of the operator point to the
id(x) equals id(y).
same object and false otherwise.
Evaluates to false if the variables on x is not y, here is not results
is not either side of the operator point to the in 1 if id(x) is not equal to
same object and true otherwise. id(y).

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

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.

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

<> == != Equality operators


= %= /= //=
Assignment operators
-= += *= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
Expression:
An expression is a combination of variables constants and operators written according to the syntax of
Python language. In Python every expression evaluates to a value i.e., every expression results in some value
of a certain type that can be assigned to a variable. Some examples of Python expressions are shown in the
table given below.
Algebraic Expression Python Expression
axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c

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.

Example: create a simple module


# A simple module, calc.py

def add(x, y):


return (x+y)

def subtract(x, y):


return (x-y)

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Import Module in Python – Import statement


We can import the functions, classes defined in a module to another module using the import statement in
some other Python source file.

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

# importing module calc.py


import calc
print(calc.add(10, 2))

Output:
12

The from import Statement


Python’s from statement lets you import specific attributes from a module without importing the module as a
whole.
Example: Importing specific attributes from the module

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

Output:
4.0
720

Import all Names – From import * Statement


The * symbol used with the from import statement is used to import all the names from a module to a
current namespace.
Syntax:
from module_name import *

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

# importing sqrt() and factorial from the


# module math
from math import *

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

Output
4.0
720

Importing and renaming module


We can rename the module while importing it using the as keyword.

Example: Renaming the module

# importing sqrt() and factorial from the


# module math
import math as gfg

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(gfg.sqrt(16))
print(gfg.factorial(6))

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.

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

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

The if ... else statement


An else statement can be combined with an if statement. An else statement contains the 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 most only one else statement following if.
Syntax:
if expression:
statement(s)
else:
VKR,VNB &AGKCOLLEGE OF ENGINEERING
Unit-1 Python programming

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

The elif Statement


The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon
as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.

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

diagram illustrates a loop statement:

Python programming language provides following types of loops to handle looping requirements.

Loop Type Description


Repeats a statement or group of statements while a given condition is
while loop
TRUE. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the
for loop
code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for loop.

The while Loop


A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.
Syntax:
The syntax of a while loop in Python programming language is:
while expression:
statement(s)

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.

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Example:
num =0

while num < 5:


num = num + 1
print('num = ', num)

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 < 5:


num += 1 # num += 1 is same as num = num + 1
if num > 3: # condition before exiting a loop
continue
print('num = ', num)
Output
num = 1
num = 2
num = 3

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Program To Print Sum ,Average Using While Loop


num=0
count=0
sum=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 for loop:


The for loop is useful to iterate over the elements of a sequence. It means, the for loop can be used to
execute a group of statements repeatedly depending upon the number of elements in the sequence. The for
loop can work with sequence like string, list, tuple, range etc.
for var in sequence:
statement (s)

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

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

Program to check whether the given number is prime number or not


num=int(input(“enter a positive number”)
if num>1:
for i in range(2,num):
if(num%i)==0:
print(num,”is a prime number”)
else:
print(num,”is not a prime number”)
else:
print(num,”is not a prime number”)
output:
enter a positive number 1
1 is not a prime number

Calculate Time taken by a Program to Execute:


In this we are going to calculate the total time taken to execute a programmer a programmer we have to
write a program that takes less time to execute the program with efficiently and accurately. For this we are
going to use two methods “time module”, “timeit module”

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()

# program body starts


for i in range(10):
print(i)

# sleeping for 1 sec to get 10 sec runtime


time.sleep(1)

# program body ends

# end time
end = time.time()

# total time taken


print(f"Runtime of the program is {end - start}")

VKR,VNB &AGKCOLLEGE OF ENGINEERING


Unit-1 Python programming

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

setup_code = "from math import factorial"

statement = """
for i in range(10):
factorial(i)
"""

print(f"Execution time is: {timeit.timeit(setup = setup_code, stmt = statement, number = 10000000)}")

Output:
Execution time is 7.536292599999996

Previous questions

1) Summarize the precedence of mathematical operators in Python?


2) Illustrate various conditional statements used in Python programming?
3) Write a Python program to demonstrate explicit type conversion.
4) Demonstrate the use of break and continue keywords in looping structure using a code
snippet.
5) Explain about the python programming language and program development
cycle?
6) explain about the type conversions with examples?
7) what are the different types of logical operators with example?
8) write a program to print the given number is prime or not using for loop?
9) write a program that checks whether the given number is even or not using if else
statement?
10) Explain the factorial of a given number using recursive?

VKR,VNB &AGKCOLLEGE OF ENGINEERING

You might also like