0% found this document useful (0 votes)
22 views53 pages

Introduction to Python Programming

This document provides an introduction to Python, detailing its history, features, applications, and various versions. It explains Python's execution model, interpreter modes, and fundamental concepts such as indentation, comments, tokens, and operators. Additionally, it covers variable creation and the structure of Python code, emphasizing its versatility as a programming language.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views53 pages

Introduction to Python Programming

This document provides an introduction to Python, detailing its history, features, applications, and various versions. It explains Python's execution model, interpreter modes, and fundamental concepts such as indentation, comments, tokens, and operators. Additionally, it covers variable creation and the structure of Python code, emphasizing its versatility as a programming language.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CHAPTER-1

INTRODUTION TO PYTHON
1.1 Introduction and overview
 General-purpose Object Oriented Programming language.
 High-level language
 Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
 It is derived from programming languages such as ABC, Modula 3, small talk, Algol- 68.
 It is Open Source Scripting language.
 It is Case-sensitive language (Difference between uppercase and lowercase letters).
 One of the official languages at Google.

1.2 Features of Python:


 Interpreted: Python source code is compiled to byte code as a .pyc file, and this byte code
can be interpreted by the interpreter.
 Interactive
 Object Oriented Programming Language
 Easy & Simple
 Portable
 Scalable: Provides improved structure for supporting large programs.
 Integrated
 Expressive Language
 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.

1.3 Python Applications

Python is a general purpose programming language that makes it applicable in almost all domains
of software development. Python as a whole can be used to develop any type of applications.

Here, we are providing some specific application areas where python can be applied.
 Web Applications
 Desktop GUI Applications
 Software Development
 Scientific and Numeric
 Business Applications
 Console Based Application
 Audio or Video based Applications

1.4 Python Versions


Page 1
Python Software Foundation (PSF) used to support two major versions, Python 2.x & Python 3.x. PSF
supported Python 2 because a large body of existing code could not be forward ported to Python 3. So,
they supported Python 2 until January 2020, but now they have stopped supporting it.

Python 3.0 was released on December 3rd, 2008. It was designed to rectify certain flaws in the earlier
version. This version is not completely backward-compatible with previous versions. However, many of
its major features have since been back-ported to the Python 2.6.x and 2.7.x version series. Releases of
Python 3 include utilities to facilitate the automation of Python 2 code translation to Python 3.

The following table lists all the important versions of Python:


Version Release Date Important Features
Python 0.9.0 February 1991  Classes with inheritance exception handling
 Functions
 Modules

Python 1.0 January 1994  Functional programming tools (lambda, map, filter and
reduce).
 Support for complex numbers.
 Functions with keyword arguments

Python 2.0 October 2000  List comprehension.


Python 2.7.0 - EOL - July 2010  Cycle-detecting garbage collector.
Jan 2020  Support for Unicode. Unification of data types and classes

Python 3 December 2008  Backward incompatible.


Python 3.6 December 2016  print keyword changed to print() function
Python 3.6.5 March 2018  raw_input() function depreciated
 Unified str/Unicode types.
 Utilities for automatic conversion of Python 2.x code

Python 3.7.0 May 2018  New C API for thread-local storage


 Built-in breakpoint()
 Data classes
 Context variables

Python 3.8 October 2019  Assignment Expression


 Positional-only parameters
 Parallel file system cache for compiled bytecode files

Python 3.9 - Current October 2020  Dictionary Merge & Update Operators
Version  New removeprefix() and removesuffix() string methods
 Builtin Generic Types

1.5 Python Code Execution:

Page 2
Python’s traditional runtime execution model: Source code you type is translated to byte code,
which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted.

1.6 Python Interpreter:


Names of some Python interpreters are:
 PyCharm
 Python IDLE
 The Python Bundle
 pyGUI
 Sublime Text etc.
1.7 There are two modes to use the python interpreter:
i. Interactive Mode (Command line mode)
ii. Script Mode
i. Interactive Mode:
 Interactive mode is a command line shell which gives immediate feedback for
each statement, while running previously fed statements in active memory. As
new lines are fed into the interpreter, the fed program is evaluated both in part and
in whole.
 Without passing python script file to the interpreter, directly execute code to
Python (Command line).

Example:
>>>6+3

Output: 9

Page 3
Fig: Interactive Mode

>>> 5
5
>>> print(5*7)
35
>>> "hello" * 2
'hellohello'

Note: >>> is a command the python interpreter uses to indicate that it is ready.
The interactive mode is better when a programmer deals with small pieces of code.

ii. Script Mode: In this mode source code is stored in a file with the .py extension and use
the interpreter to execute the contents of the file. To execute the script by the interpreter,
you have to tell the interpreter the name of the file.

Example:
if you have a file name [Link] , to run the script you have to follow the following steps:

Step-1: Open the text editor


Step-2: Write the python code and save the file with .py file extension.

Fig: Python Shell

Page 4
Step-3: Output will be displayed on python shell window.

Fig. : IDLE (Python GUI)

1.8 Indentation and Comments:


 Python provides no braces to indicate blocks of code for class and function
definition or flow control.
 Maximum line length should be maximum 79 characters.
 Blocks of code are denoted by line indentation, which is rigidly enforced.
[Link]:
 Python indentation refers to adding white space before a statement to a particular
block of code. In another word, all the statements with the same space to the right,
belong to the same code block.
 The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount.
for example –
if True:
print(“True”)
else:
print(“False”)
b. Comments:
Comments are not executed. Comments explain a program and make a program
understandable and readable. All characters after the # and up to the end of the
physical line are part of the comment and the Python interpreter ignores them.

Page 5
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment

i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values

ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.

Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’

Page 6
PYTHON
FUNDAMENTALS

2.1 Python Character Set :


It is a set of valid characters that a language recognize.
Letters: A-Z, a-z
Digits : 0-9
Special Symbols
Whitespace
2.2 TOKENS
Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators

1. Keyword: Reserved words in the library of a language. There are 33 keywords


in python.

False class finally is return break


None continue for lambda try except
True def from nonlocal while in
and del global not with raise
as elif if or yield
assert else import pass

All the keywords are in lowercase except 03 keywords (True, False, None).

Page 7
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.

Rules for identifiers:

 It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore.
 It cannot start with a digit.
 Keywords cannot be used as an identifier.
 We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
 _ (underscore) can be used in identifier.
 Commas or blank spaces are not allowed within an identifier.

3. Literal: Literals are the constant value. Literals can be defined as a data that is given
in a variable or constant.

Literal

String Literal
Numeric Boolean Special
Collections

int float complex

True False None

A. Numeric literals: Numeric Literals are immutable.


Eg.
5, 6.7, 6+9j

Page 8
B. String literals:

String literals can be formed by enclosing a text in the quotes. We can use both single as well as
double quotes for a String.
Eg:

"Aman" , '12345'

Escape sequence characters:


\\ Backslash
\’ Single quote
\” Double quote
\a ASCII Bell
\b Backspace
\f ASCII Formfeed
\n New line charater
\t Horizontal tab

C. Boolean literal: A Boolean literal can have any of the two values: True or False.

D. Special literals: Python contains one special literal i.e. None.

None is used to specify to that field that is not created. It is also used for end of lists in
Python.

E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.

Page 9
Operators:

 The operator is a symbol that performs a specific operation between two operands, according
to one definition.
 An operator performs the operation on operands.

Types of Operators in Python

Operators are divided into 7 categories in Python according to their type of operation.

Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.

Page
10
Assignment Operators

Assignment operators are used to assign values to variables. Following is a table


which shows all Python assignment operators.

Comparison Operators

These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.

Page
11
Logical Operators

Python logical operators are used to combile two or more conditions and check the
final result. There are following logical operators supported by Python language.

5. IDENTITY OPERATORs in Python

These operators compare the left and right operands and check if they are equal, the same object, and have the same
memory location.

Example :

number1 = 5

number2 = 5

number3 = 10

print(number1 is number2) # check if number1 is equal to number2

print(number1 is not number3) # check if number1 is not equal to number3

Page
12
Output :

True

True

6. MEMBERSHIP OPERATORs in Python

These operators search for the value in a specified sequence and return True or False accordingly. If the value is found
in the given sequence, it gives the output as True; otherwise False. The not in operator returns true if the value specified
is not found in the given sequence. Let’s see an example:

Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. These operators
are used to compare binary numbers.

Example :
number1 = 4 # 0100 in binary
number2 = 3 # 0011 in binary
print("& operation- ", number1 & number2) # AND
print("| operation- ", number1 | number2) # OR
Page
13
print("^ operation- ", number1 ^ number2) # XOR
print("~ operation- ", ~number2) # negation
print("<< operation- ", number1 << 1) # shift left by 1 bit
print(">> operation- ", number1 >> 1) # shift right by 1bit

Output :
& operation- 0
| operation- 7
^ operation- 7
~ operation- -4
<< operation- 8
>> operation- 2

Statements
A line which has the instructions or expressions.

Expression:
An expression is a collection of values, variables, operators and function calls that can be
evaluated by python interpreters if the expression is valid.

Page
14
Operator Precedence
The Python interpreter executes operations of higher precedence operators first in any
given logical or arithmetic expression. Except for the exponent operator (**), all other
operators are executed from left to right.
Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division,


Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, Comparisons, Identity, Membership
not in operators

not Logical NOT

and Logical AND

or Logical OR

Associativity of Python Operators


When two operators have the same precedence, associativity helps to determine the order of
operations.
Associativity is the order in which an expression is evaluated that has multiple operators of the
same precedence. Almost all the operators have left-to-right associativity.
Example :
# Left-right associativity
# Output: 3
print(5 * 2 // 3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))

Page
15
4. Separator or punctuator : , ; , ( ), { }, [ ]

2.3 Mantissa and Exponent Form:

A real number in exponent form has two parts:


 mantissa
 exponent
Mantissa : It must be either an integer or a proper real constant.
Exponent : It must be an integer. Represented by a letter E or e followed by integer value.

Valid Exponent form Invalid Exponent form


123E05 2.3E (No digit specified for exponent)
1.23E07
0.24E3.2 (Exponent cannot have fractional part)
0.123E08
23,455E03 (No comma allowed)
123.0E08
123E+8
1230E04
-0.123E-3
163.E4
.34E-2
4.E3

Page
16
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)

2.4 Variable/Label in Python:


Definition: Named location that refers to a value and whose value can be used and processed
during program execution.
Variables in python do not have fixed locations. The location they refer to changes every time
their values change.

Creating a variable:

A variable is created the moment you first assign a value to it.

Example:

x=5

y = “hello”

Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.

x = 4 # x is of type int
x = "python" # x is now of type str
print(x)

Rules for Python variables:

 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 underscore (A-z, 0-9,
and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

Page
17
Python allows assign a single value to multiple

variables. Example: x = y = z = 5

You can also assign multiple values to multiple variables. For example −

x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12
 Lvalue and Rvalue:
An expression has two values. Lvalue and Rvalue.
Lvalue: the LHS part of the expression
Rvalue: the RHS part of the expression
Python first evaluates the RHS expression and then assigns to LHS.
Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p,q,r)
Now the result will be:
6 6 12

Page
18
OUTPUT using print( ) statement:
Syntax:
print(object, sep=<separator string >, end=<end-string>)

object : It can be one or multiple objects separated by comma.


sep : sep argument specifies the separator character or string. It separate the objects/items.
By default sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ).
Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30

Page
19
 If you want to know the type of variable, you can use type( ) function :
Syntax:
type (variable-name)

Example:
x=6

type(x)
The result will be:
<class ‘int’>

You can delete single or multiple variables by using del statement.


Example:
del x
del y, z

2.5 Input from a user:

input( ) method is used to take input from the user.


Example:
print("Enter your name:")
x = input( )
print("Hello, " + x)

 input( ) function always returns a value of string type.

Reading a number from a user:


x= int(input(“Enter an integer number”))

Page
20
Type Casting:
To convert one data type into another data type.

Casting in python is therefore done using constructor functions:


 int( ) - constructs an integer number from an integer literal, a float literal or a string literal.

Example:
x = int(1) # x will be 1 y =
int(2.8) # y will be 2 z =
int("3") # z will be 3

 float( ) - constructs a float number from an integer literal, a float literal or a string literal.

Example:
x = float(1) # x will be 1.0 y
= float(2.8) # y will be 2.8 z =
float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

 str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.

Example:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Reading a number from a user:


x= int(input(“Enter an integer number”))

Page
21
DATA HANDLING

3.1 Data Types in Python:


Python has Two data types –

1. Primitive Data Type (Numbers, String)


2. Collection Data Type (List, Tuple, Set, Dictionary)

Data Types

Primitive Collection
Data Type Data Type

Number String

List Tuple Set Dictionary


int float complex

1. Primitive Data Types:


a. Numbers: Number data types store numeric values.

There are three numeric types in Python:

 int
 float
 complex

Example:
w=1 # int
y = 2.8 # float
z = 1j # complex

Page
22
 integer : There are two types of integers in python:
 int
 Boolean

 int: int or integer, is a whole number, positive or negative, without decimals.


Example:

x=1
y = 35656222554887711
z = -3255522
 Boolean: It has two values: True and False. True has the value 1 and False has the
value 0.
Example:

>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True

 float : float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the power
of 10.
Example:

x = 1.10
y = 1.0
z = -35.59
a = 35e3
b = 12E4
c = -87.7e100

Page
23
 complex : Complex numbers are written with a "j" as the imaginary part.
Example:

>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>[Link]
5.0
>>>[Link]
9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.

b. String: Sequence of characters represented in the quotation marks.


 Python allows for either pairs of single or double quotes. Example: 'hello' is the same
as "hello" .
 Python does not have a character data type, a single character is simply a string with a
length of 1.
 The python string store Unicode characters.
 Each character in a string has its own index.
 String is immutable data type means it can never change its value in place.

2. Collection Data Type:


 List
 Tuple
 Set
 Dictionary

Page
24
3.2 MUTABLE & IMMUTABLE Data Type:
 Mutable Data Type:
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
 Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: integer, float, Boolean, string and tuple.

3.3 Basic Operators in Python:


i. Arithmetic Operators
ii. Relational Operator
iii. Logical Operators
iv. Bitwise operators
v. Assignment Operators
vi. Other Special Operators
o Identity Operators
o Membership operators

i. Arithmetic Operators: To perform mathematical operations.

RESULT
OPERATOR NAME SYNTAX
(X=14,
Y=4)
+ Addition x+y 18

_ Subtraction x–y 10

* Multiplication x*y 56

/ Division (float) x/y 3.5

// Division (floor) x // y 3

% Modulus x%y 2

** Exponent x**y 38416

Page
25
Example:
>>>x= -5
>>>x**2
>>> -25

ii. Relational Operators: Relational operators compare the values. It either


returns True or False according to the condition.

RESULT
OPERATOR NAME SYNTAX
(IF X=16,
Y=42)
False
> Greater than x>y
True
< Less than x<y
False
== Equal to x == y
True
!= Not equal to x != y
False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y

iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.

OPERATOR DESCRIPTION SYNTAX


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x

Examples of Logical Operator:

The and operator: The and operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands

Page
26
a. Relational expressions as operands:

X Y X and Y
False False False
False True False
True False False
True True True

>>> 5>8 and 7>3


False
>>> (4==4) and (7==7)
True

b. numbers or strings or lists as operands:


In an expression X and Y, if first operand has false value, then return first operand X as a
result, otherwise returns Y.

>>>0 and 0 X Y X and Y


0 false false X
>>>0 and 6 false true X
0 true false Y
>>>‘a’ and ‘n’
true true Y
’n’
>>>6>9 and ‘c’+9>5 # and operator will test the second operand only if the first operand
False # is true, otherwise ignores it, even if the second operand is wrong

The or operator: The or operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands

a. Relational expressions as operands:

X Y X or Y
False False False
False True True
True False True
True True True

>>> 5>8 or 7>3


True
>>> (4==4) or (7==7)
True

Page
27
b. numbers or strings or lists as operands:
In an expression X or Y, if first operand has true value, then return first operand X as a
result, otherwise returns Y.

X Y X or Y
false false Y
false true Y
true false X
true true X

>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’
’a’

The not operator:


>>>not 6
False
>>>not 0
True
>>>not -7
False

iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.

OPERATO DESCRIPTION SYNTA


R X
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Page
28
Examples:
Let Outpu
a = 10
t: 0
b=4
14
print(a & b)
-11
print(a | b) 14
2
print(~a)
40
print(a ^ b)
print(a >> 2)

print(a << 2)

v. Assignment operators: Assignment operators are used to assign values to the variables.

OPERA
TOR DESCRIPTION SYNTAX

= Assign value of right side of expression to left side operand x=y+z


Add AND: Add right side operand with left side operand and a+=b
+=
then assign to left operand a=a+b
Subtract AND: Subtract right operand from left operand and then a-=b a=a-
-=
assign to left operand b
Multiply AND: Multiply right operand with left operand and then a*=b
*=
assign to left operand a=a*b

Page
29
Divide AND: Divide left operand with right operand and then a/=b
/=
assign to left operand a=a/b
Modulus AND: Takes modulus using left and right operands and a%=b
%=
assign result to left operand a=a%b
Divide(floor) AND: Divide left operand with right operand and a//=b
//=
then assign the value(floor) to left operand a=a//b
Exponent AND: Calculate exponent(raise power) value using a**=b
**=
operands and assign value to left operand a=a**b
Performs Bitwise AND on operands and assign value to a&=b
&=
left operand a=a&b
Performs Bitwise OR on operands and assign value to left a|=b
|=
operand a=a|b
Performs Bitwise xOR on operands and assign value to a^=b
^=
left operand a=a^b
Performs Bitwise right shift on operands and assign value to left a>>=b
>>=
operand a=a>>b
Performs Bitwise left shift on operands and assign value to left a <<=b a=
<<=
operand a << b
vi. Other Special operators: There are some special type of operators like-

a. Identity operators- is and is not are the identity operators both are used to check if
two values 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 True if the operands are not identical
is not

Example:
Let
a1 = 3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming'
a3 = [1,2,3]
b3 = [1,2,3]

print(a1 is not b1)

Page
30
print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)

Output:
False
True
False
Example:
>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False

b. Membership operators- in and not in are the membership operators; used to


test whether a value or variable is in a sequence.

in True if value is found in the sequence


not in True if value is not found in the sequence

Example:
Let
x = 'Digital India'
y = {3:'a',4:'b'}

print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)

Boolean expressions
A boolean expression is an expression that is either true or false. The following examples use the operator ==, which
compares two operands and produces True if they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False

Page
31
FLOW OF CONTROL

The flow control statements are divided into three categories

1. Conditional statements
2. Iterative statements.
3. Transfer statements

DECISION MAKING (Conditional Statements)

Decision making is about deciding the order of execution of statements based on certain conditions. Decision structures
evaluate multiple expressions which produce TRUE or FALSE as outcome.
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the
program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

There are three types of conditions in python:


1. if statement
2. if-else statement
3. elif statement

Page
32
1. if statement: It is a simple if statement. When condition is true, then code which is associated
with if statement will execute.
Syntax of the if statement
if condition:
statement 1
statement 2
statement n

Example:
a=40
b=20
if a>b:
print(“a is greater than b”)
print('Next lines of code')

2. if-else statement (Alternative execution):


When the condition is true, then code associated with if statement will execute, otherwise code associated
with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)

3. elif statement (Chained Conditionals): It is short form of else-if statement. If the previous conditions
were not true, then do this condition". It is also known as nested if statement.
Syntax:
if condition-1:
statement 1
elif condition-2:
statement 2
elif condition-3:
statement 3
...
else:
statement

Page
33
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")

Nested conditionals
In Python, the nested if-else statement is an if statement inside another if-else statement. It is allowed in
Python to put any number of if statements in another if statement. One conditional can also be nested within
another. We could have written the three-branch example like this:
Syntax :
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block
Example :
num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))

if num1 >= num2:


if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)

Page
34
Loop: Execute a set of statements repeatedly until a particular condition is satisfied.

There are two types of loops in python:


1. while loop
2. for loop

while loop: With the while loop we can execute a set of statements as long as a condition is true. It
requires defining an indexing variable.
Example: To print table of number 2
i=2
while i<=20:
print(i)
i+=2

1. for loop : The for loop iterate over a given sequence (it may be list, tuple or string).

Note: The for loop does not require an indexing variable to set beforehand, as the for command
itself allows for this.

primes = [2, 3, 5, 7]
for x in primes:
print(x)

Page
35
The range( ) function:

it generates a list of numbers, which is generally used to iterate over with for loop.
range( ) function uses three types of parameters, which are:

 start: Starting number of the sequence.


 stop: Generate numbers up to, but not including last number.
 step: Difference between each number in the sequence.

Python use range( ) function in three ways:

a. range(stop)

b. range(start, stop)

c. range(start, stop, step)

Note:

 All parameters must be integers.


 All parameters can be positive or negative.
a. range(stop): By default, It starts from 0 and increments by 1 and ends up to stop,
but not including stop value.

Example:

for x in range(4):
print(x)

Output:

0
1
2
3

b. range(start, stop): It starts from the start value and up to stop, but not including
stop value.

Example:

for x in range(2, 6):


print(x)

Page
36
Output:

2
3
4
5

c. range(start, stop, step): Third parameter specifies to increment or decrement the value by
adding or subtracting the value.

Example:

for x in range(3, 8, 2):

print(x)

Output:

3
5
7

Page
37
JUMP or TRANSFER STATEMENTS:
There are two jump statements in python:
1. break
2. continue

1. break statement : With the break statement we can stop the loop even if it is true.
Example:
in while loop in for loop
i = 1 languages = ["java", "python",
while i < "c++"] for x in languages:
6: if x ==
print(i) "python":
if i == break
3: print(x)
break
i += 1
Output: Output:
1 java
2
3

Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.
2. continue statement : With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example:
in while loop in for loop
i = 0 languages = ["java", "python",
while i < "c++"] for x in languages:
6: i += 1 if x ==
if i == "python":
3: continue
continu print(x)
e
print(i)
Output: Output
1 : java
2 c++
4
5
6

Page
38
Loop else statement:
The else statement of a python loop executes when the loop terminates normally. The else
statement of the loop will not execute when the break statement terminates the loop.
The else clause of a loop appears at the same indentation as that of the loop keyword while or
for.

Syntax:
for loop while loop

for <variable> in <sequence>: while <test condition>:


statement-1 statement-1
statement-2 statement-2
. .
. .
else: else:
statement(s) statement(s)

Nested Loop :
A loop inside another loop is known as nested loop.
Syntax:
for <variable-name> in <sequence>:
for <variable-name> in <sequence>:
statement(s)
statement(s)

Example:

for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")

Page
39
Programs related to Conditional, looping and jumping statements
1. Write a program to check a number whether it is even or odd.
num=int(input("Enter the number: ")) if
num%2==0:
print(num, " is even number")
else:
print(num, " is odd number")

2. Write a program in python to check a number whether it is prime or not.


num=int(input("Enter the number: "))
for i in range(2,num):
if num%i==0:
print(num, "is not prime number")
break;
else:
print(num,"is prime number")
3. Write a program to check a year whether it is leap year or not.
year=int(input("Enter the year: ")) if year
%100==0 and year%400==0:
print("It is a leap year") elif
year%4==0:
print("It is a leap year")
else:
print("It is not leap year")

4. Write a program in python to convert °C to °F and vice versa.


a=int(input("Press 1 for C to F \n Press 2 for F to C \n"))
if a==1:
c=float(input("Enter the temperature in degree Celsius: "))
f= (9/5)*c+32
print(c, "Celsius = ",f," Fahrenheit")
elif a==2:
f=float(input("Enter the temperature in Fahrenheit: "))
c= (f-32)*5/9
print(f, "Fahrenheit = ",c," Celsius")
else:
print("You entered wrong choice")

Page
40
5. Write a program to check a number whether it is palindrome or not.
num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10

res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome") else:
print("Number is not Palindrome")

6. A number is Armstrong number or not.


num=input("Enter a number : ")
length=len(num)
n=int(num)
num=n
sum=0 while
n>0:
rem=n%10
sum=sum+rem**length
n=n//10
if num==sum:
print(num, "is armstrong number") else:
print(num, "is not armstrong number")

7. To check whether the number is perfect number or not


num=int(input("Enter a number : "))
sum=0
for i in range(1,num):
if(num%i==0):

Page
41
sum=sum+i

Page
42
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")

8. Write a program to print Fibonacci series.


n=int(input("How many numbers : "))
first=0
second=1
i=3
print(first, second, end=" ")
while i<=n:
third=first+second
print(third, end=" ")
first=second
second=third
i=i+1

9. To print a pattern using nested loops


for i in range(1,5): 1
for j in range(1,i+1): 1 2
print(j," ", end=" ") 1 2 3
print('\n') 1 2 3 4
Python exit() function

In python, we have an in-built exit( ) function which is used to exit a python program. When it
encounters the exit( ) function in the system, it terminates the execution of the program completely.
Example :

for val in range(0,5):


if val == 3:
print(exit)
exit( )
print(val)

After writing the above code (python exit() function), Ones you will print “ val ” then the
output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced
to exit, and it will print the exit message too.
Page
43
FUNCTIONS IN
PYTHON
Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.

Types of Functions:
There are two types of functions in python:

1. Library Functions (Built in functions)


2. Functions defined in modules
3. User Defined Functions

Built in functions

Functions defined in modules


Types of functions

User defined functions

1. Library Functions: These functions are already built in the python library.

2. Functions defined in modules: These functions defined in particular modules. When you want
to use these functions in program, you have to import the corresponding module of that function.

3. User Defined Functions: The functions those are defined by the user are called user defined
functions.

1. Library Functions in Python:


These functions are already built in the library of python. The Python interpreter has a number of
functions and types built into it that are always available. They are listed here in alphabetical order.

For example: type( ), len( ), input( ) etc.


2. Functions defined in modules:
a. Functions of math module:

Page
44
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>[Link](49)
7.0
2 ceil( ) Returns the upper integer >>>[Link](81.3)
82
3 floor( ) Returns the lower integer >>>[Link](81.3)
81
4 pow( ) Calculate the power of a number >>>[Link](2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>[Link](-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>[Link](3)
20.085536923187668

b. Function in random module:


random module has a function randint( ).
 randint( ) function generates the random integer values including start and end values.
 Syntax: randint(start, end)
 It has two parameters. Both parameters must have integer values.
Example:
import random
n=[Link](3,7)

*The value of n will be 3 to 7.

3. USER DEFINED FUNCTIONS:


The syntax to define a function is:
def function-name ( parameters) :
#statement(s)
Where:

 Keyword def marks the start of function header.


 A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They are optional.
 A colon (:) to mark the end of function header.
 One or more valid python statements that make up the function body. Statements must have same
indentation level.
Page
45
 An optional return statement to return a value from the function.

Example:

def display(name):

print("Hello " + name + " How are you?")


Function Parameters:
A functions has two types of parameters:

1. Formal Parameter: Formal parameters are written in the function prototype and function header of the
definition. Formal parameters are local variables which are assigned values from the arguments when the
function is called.

2. Actual Parameter: When a function is called, the values that are passed in the call are called actual
parameters. At the time of the call each actual parameter is assigned to the corresponding formal parameter in
the function definition.

Example :
def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Calling the function:
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.

Syntax:
function-name(parameter)
Example:
ADD(10,20)

OUTPUT:
Sum = 30.0

Page
46
How function works?

def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)

… .. …
… .. …

The return statement:


The return statement is used to exit a function and go back to the place from where it was called.
There are two types of functions according to return statement:

a. Function returning some value (non-void function)


b. Function not returning any value (void function)
a. Function returning some value (non-void function) :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x

Example-2 Function returning multiple values:


def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a
tuple print(S)

OUTPUT:

Page
47
(7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)

OUTPUT:
7 7 11

b. Function not returning any value (void function) : The function that performs some operationsbut
does not return any value, called void function.
def message():
print("Hello")

m=message()
print(m)

OUTPUT:
Hello
None

Scope and Lifetime of variables:

Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables
defined inside a function is not visible from outside. Hence, they have a local scope.

There are two types of scope for variables:

1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function. In this scope,
The lifetime of variables inside a function is as long as the function executes. They are destroyed once we
return from the function. Hence, a function does not remember the value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a variable is the
period throughout which the variable exits in the memory.

Page
48
Example:
def my_func():
x = 10
print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)
OUTPUT:

Value inside function: 10


Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the function my_func()changed the value of x
to 10, it did not affect the value outside the function.

This is because the variable x inside the function is different (local to the function) from the one outside.
Although they have same names, they are two different variables with different scope.

On the other hand, variables outside of the function are visible from inside. They have a global
scope.

We can read these values from inside the function but cannot change (write) them. In order to modify the value
of variables outside the function, they must be declared as global variables using the keyword global.

RECURSION:
Definition: A function calls itself, is called recursion.

Python program to find the factorial of a number using recursion:


Program:
def factorial(n): if
n == 1:
return n
else:
return n*factorial(n-1)

num=int(input("enter the number: ")) if


num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num = = 0:
print("The factorial of 0 is 1")
Page
49
else:
print("The factorial of ",num," is ", factorial(num))

OUTPUT:
enter the number: 5
The factorial of 5 is 120

Python program to print the Fibonacci series using recursion: Program:


def fibonacci(n): if
n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))

num=int(input("How many terms you want to display: ")) for i in


range(num):
print(fibonacci(i)," ", end=" ")

OUTPUT:
How many terms you want to display: 8 0 1
1 2 3 5 8 13

Page
50
lambda Function:
lambda keyword, is used to create anonymous function which doesn’t have any name.

While normal functions are defined using the def keyword, in Python anonymous functions are defined using the
lambda keyword.

Syntax:

Lambda
lambdafunctions can have
arguments: any number of arguments but only one expression. The expression is evaluated and
expression
returned. Lambda functions can be used wherever function objects are required.

Example:

value = lambda x: x * 4
print(value(6))
Output:
24
In the above program, lambda x: x * 4 is the lambda function. Here x is the argument and x * 4 is the
expression that gets evaluated and returned.

Programs related to Functions in Python topic:


1. Write a python program to sum the sequence given below. Take the input n from the user.
1 1 1 1
1+ + + + ⋯ + 𝑛!
1! 3!

2!
Solution:
def fact(x):
j=1 res=1
while j<=x:
res=res*j
j=j+1
return res

Page
51
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)

2. Write a program to compute GCD and LCM of two numbers


def gcd(x,y):
while(y):
x, y = y, x % y
return x

def lcm(x, y):


lcm = (x*y)//gcd(x,y)
return lcm
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
print("The G.C.D. of", num1,"and", num2,"is", gcd(num1, num2))

Page 52
Page 53

You might also like