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

Python Programming

Unit 1 of the Python programming course covers the basics of Python, including its history, syntax, and data types. It introduces key concepts such as variables, operators, control structures, and the differences between interactive and script modes. The unit also explains the use of Python for various applications, emphasizing its simplicity and versatility.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Programming

Unit 1 of the Python programming course covers the basics of Python, including its history, syntax, and data types. It introduces key concepts such as variables, operators, control structures, and the differences between interactive and script modes. The unit also explains the use of Python for various applications, emphasizing its simplicity and versatility.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Unit -1 python programming

UNIT I BASICS OF PYTHON


Introduction to Python Programming – Python Interpreter and Interactive
Mode– Variables and
Identifiers – Arithmetic Operators – Values and Types – Statements.
Operators – Boolean Values
– Operator Precedence – Expression – Conditionals: If-Else Constructs –
Loop
Structures/Iterative Statements – While Loop – For Loop – Break
Statement-Continue statement –
Function Call and Returning Values – Parameter Passing – Local and
Global Scope – Recursive Function.
Introduction to Python Programming :

Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.

It is used for:

● web development (server-side),


● software development,
● mathematics,
● system scripting.

What can Python do?

● Python can be used on a server to create web applications.


● Python can be used alongside software to create workflows.
● Python can connect to database systems. It can also read and modify files.
● Python can be used to handle big data and perform complex mathematics.
● Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a functional way.

Good to know

● The most recent major version of Python is Python 3, which we shall be using in this tutorial.
However, Python 2, although not being updated with anything other than security updates, is
still quite popular.
● In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which
are particularly useful when managing larger collections of Python files.

Python Syntax compared to other programming languages

● Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
● Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.

Example
print("Hello, World!")

Python Interpreter and Interactive Mode:

Python interpreter:

Interpreter: To execute a program in a high-level language by translating it one line ata time.

Compiler: To translate a program written in a high-level language into a low-level language


all at once, in preparation for later execution.
Compile Interpret
r er
Compiler Takes Entire program as input Interpreter Takes Single instruction as
input
Object Cod
Intermediate Object Code is Generated No Intermediate is
e
Generated
Conditional Control Statements are Conditional Control are
Executes faster Statements Executes slower
Memory Requirement is More(Since
Memory Requirement is Less
Object Code is Generated)
Every time higher level is
Program need not be compiled every time
program converted into lower level
program
Errors are displayed after entire program is Errors are displayed for every instruction
checked interpreted (if any)
Example : C Compiler Example : PYTHON

Modes of python interpreter:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.
1. Interactive mode
2. Script mode
Interactive mode:
❖ Interactive Mode, as the name suggests, allows us to interact with OS.
❖ When we type Python statement, interpreter displays the result(s)
immediately. Advantages:
❖ Python, in interactive mode, is good enough to learn, experiment or explore.
❖ Working in interactive mode is convenient for beginners and for testing small pieces of
code.
Drawback:
❖ We cannot save the statements and have to retype all the statements once again
to re-run them. In interactive mode, you type Python programs and the interpreter
displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to
enter code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!

This is an example of a print statement. It displays a result on the screen. In this case, the result
is the words.
Script mode:
In script mode, we type python program in a file and then use interpreter to execute
the content of the file.
Scripts can be saved to disk for future use. Python scripts
have the extension .py, meaning that the
filename ends with.py

Save the code with filename.py and run the interpreter in script mode to execute the
script.

Interactive mode Script


mode
A way of using the Python interpreter by A way of using the Python interpreter to read
typing commands and expressions at the and execute statements in a script.
prompt.
Can’t save and edit the code Can save and edit the code
If we want to experiment with the If we are very clear about the code,
code, we can use interactive mode. we can use script mode.
we cannot save the statements for further use we can save the statements for further use
and we have to retype all the statements to re and we no need to retype all the statements
-run them. to re-run them.
We can see the results immediately. We can’t see the code immediately.
Integrated Development Learning Environment(IDLE):
Is a graphical user interface which is completely written in Python.

It is bundled with the default implementation of the python language and also comes
with optional part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.

Python shell to display output with syntax highlighting.

Variables and Identifiers :


Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or
an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.

Identifier Naming

Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-z), upper-
case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable, that
variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Arithmetic Operators:

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication and division.
There are 7 arithmetic operators in Python :
1. Addition
2. Subtraction
3. Multiplication

34
4. Division
5. Modulus
6. Exponentiation
7. Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.
Example :

val1 = 2

val2 = 3

# using the addition operator

res = val1 + val2

print(res)

Output :
5
2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract the second
value from the first value.
Example :

val1 = 2

val2 = 3

# using the subtraction operator

res = val1 - val2

print(res)

Output :
-1
3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find the product
of 2 values.
Example :

val1 = 2

35
val2 = 3

# using the multiplication operator

res = val1 * val2

print(res)

Output :
6
4. Division Operator : In Python, / is the division operator. It is used to find the quotient when first
operand is divided by the second.
Example :

val1 = 3

val2 = 2

# using the division operator

res = val1 / val2

print(res)

Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator. It is used to find the remainder when
first operand is divided by the second.
Example :

val1 = 3

val2 = 2

# using the modulus operator

36
res = val1 % val2

print(res)

Output :
1
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to raise the first
operand to power of second.
Example :

val1 = 2

val2 = 3

# using the exponentiation operator

res = val1 ** val2

print(res)

Output :
8
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the floorof the
quotient when first operand is divided by the second.
Example :

val1 = 3

val2 = 2

# using the floor division

res = val1 // val2

print(res)

Output :

37
1

Values and Types :


Value:

Value can be any letter, number or string.


Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:

Numbers:

❖ Number data type stores Numerical Values.


❖ This data type is immutable [i.e. values/items cannot be changed].
❖ Python supports integers, floating point numbers and complex numbers. They are defined
as,

Sequence:
❖ A sequence is an ordered collection of items, indexed by positive integers.
❖ It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) datatypes

38
There are three types of sequence data type available in Python, they are

1. Strings
2. Lists
3. Tuples

Strings:

A String in Python consists of a series or sequence of characters - letters,


numbers, and special characters.
Strings are marked by quotes:
● Single quotes(' ') E.g., 'This a string in single quotes'
● double quotes(" ") E.g., "'This a string in double quotes'"
● triple quotes(""" """)E.g., """This is a paragraph. It is made up of
multiple lines and sentences."""
Individual character in a string is accessed using a subscript(index).
Characters can be accessed using indexing and slicing operations
.Strings are Immutable i.e the contents of the string cannot be
changed after it is created.

Indexing:

39
Positive indexing helps in accessing the string from the beginning
● Negative subscript helps in accessing the string from the end.
● Subscript 0 or –ven(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
● Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”
Operations on string:

i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>>print(s[2] ❖ Accessing th ite i th
)o position0
>>>print(s[6]) ❖ Accessing e m n e
O position2
th ite i th

e m n e

Slicing( p ending >>>print(s[2:]) - Displaying items from


osition -1) od morning nd
2 till last.
Slice operator is >>>print(s[:4]) st
- Displaying items from 1
used to extract Good rd
part of a data position till 3 .
type
Concatenation >>>print(s+"friends") -Adding and printing
good morning friends the characters of two strings.

Repetition >>>print(s*2) Creates new strings,


good morning concatenating multiple
good morning copies of the same string

40
in, not in >>> s="good morning" Using membership operators to
(membership >>>"m" in s True check a particular character is in
operator) >>> "a" not in s string or not. Returns true if
True present.

Lists
❖ List is an ordered sequence of items. Values in the list are called elements /items.
❖ It can be written as a list of comma-separated items (values) between square brackets[].
❖ Items in the lists can be of different datatypes.

Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion

41
Creating a list >>>list1=["python", 7.79, 101, Creating the list with
"hello”] elements of different
>>>list2=["god",6.78,9] data types.
Indexing >>>print(list1[0]) python ❖ Accessing the item in
>>>list1[2] the position0
101 ❖ Accessing the item in
the position2
Slicing( >>>print(list1[1:3]) - Displaying items from
ending position -1) [7.79, 101] 1st till2nd.
Slice operator is - Displaying items from
>>>print(list1[1:]) [7.79, 101,
used to extract st
'hello'] 1 position till last.
part of a string, or
some part of a
list
Python

Concatenation >>>print( list1+list2) -Adding and the


['python', 7.79, 101, 'hello', 'god', printing items of two
lists.
6.78, 9]
Repetition >>>list2*3 Creates new strings,
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating
6.78, 9] multiple
copies of the same string
Updating the list >>>list1[2]=45 Updating the list using index
>>>print( list1) value
[‘python’, 7.79, 45, ‘hello’]
Inserting an element >>>list1.insert(2,"program") Inserting an element in
>>> print(list1) nd
2 position
['python', 7.79, 'program',
45, 'hello']
Removing an >>>list1.remove(45) Removing an element by
element >>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']

42
Tuple:
❖ A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
❖ A tuple is an immutable list.i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
❖ Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.

Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with
"hello”) elements of different data
types.
Indexing >>>print(t[0]) python ❖ Accessing the item in
>>>t[2 the position0
] 101 ❖ Accessing the item in
the position2
Slicing( po ending >>>print(t[1:3]) ❖ Displaying items
sition -1) (7.79, 101) from1st till2nd.

Concatenation >>>t+("ram", 67) ❖ Adding tuple elements


('python', 7.79, 101, 'hello', 'ram', at the end of another tuple
67)
elements
Repetition >>>print(t*2) ❖ Creates new strings,
('python', 7.79, 101, 'hello',
concatenating multiple copies
'python', 7.79, 101, 'hello')
of the
same string

Altering the tuple data type leads to error. Following error occurs when user tries to do.

43
>>>t[0]="a"

Trace back (most recent call last):

File "<stdin>", line 1, in < module>

Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
Dictionaries:

❖ Lists are ordered sets of objects, whereas dictionaries are unorderedsets.


❖ Dictionary is created by using curly brackets. i,e.{}
❖ Dictionaries are accessed via keys and not via their position.
❖ A dictionary is an associative array (also known as hashes). Any key of the dictionary
is associated (or mapped) to a value.
❖ The values of a dictionary can be any Python data type. So dictionaries are unordered
key-value- pairs(The association of a key and a value is called a key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings,
tuples and lists.

Creating a >>> food = {"ham":"yes", "egg" : Creating the dictionary with


dictionary "yes", "rate":450 } elements of different
>>>print(food) data types.
{'rate': 450, 'egg': 'yes',
'ham': 'yes'}
Indexing >>>>print(food["rate"]) Accessing the item with keys.
450
Slicing( ending >>>print(t[1:3]) Displaying items from 1st till 2nd.
position -1) (7.79, 101)

If you try to access a key which doesn't exist, you will get an error message:
>>>words = {"house" : "Haus", "cat":"Katze"}
>>>words["car"]
Traceback (most recent call last): File
"<stdin>", line 1, in <module>KeyError:
'car'
Data type Compile time Run time

int a=10 a=int(input(“enter a”))


float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))

44
STATEMENTS AND EXPRESSIONS:
Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying avalue.
>>> n = 17

>>>print (n)
Here, The first line is an assignment statement that gives a value to n. The
second line is a print statement that displays the value of n.
Expressions:
-An expression is a combination of values, variables, and operators.

- A value all by itself is considered an expression, and also a variable.


- So the following are all legal expressions:
>>> 42

42

>>> a=2

>>>a+3+2 7

>>> z=("hi"+"friend")

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program. In


python, input () function is available for input.
Syntax for input() is:

variable = input (“data”)

40
Example:
>>> x=input("enter the name:")
enter the name: george

>>>y=int(input("enter the number"))


enter the number 3
#python accepts string as default data type. Conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:

i t( i / t t/ i bl )

Example:
>>> print ("Hello")
Hello

Operators:

Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator

Types of Operators:
-Python language supports the following types of operators
● Arithmetic Operators
● Comparison (Relational)Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
● Identity Operators

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

Assume, a=10 and b=5

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the


operators power 20

// Floor Division - The division of operands where the result 5//2=2


is the quotient in which the digits after the decimal point
are removed

Examples O
u
a=10 t
b=5 print("a+b=",a+b) print("a-b=",a- p
b) print("a*b=",a*b)
u
print("a/b=",a/b) print("a%b=",a%b)
print("a//b=",a//b) t:
print("a**b=",a**b) a
+
b
=
1
5
a
-
b
=
5

a*b= 50

42
a =
/ 0
b a
= /
2. /
0 b
a =
% 2
b a**b= 100000

Comparison (Relational)Operators:
● Comparison operators are used to compare values.
● It either returns True or False according to the condition. Assume, a=10 and b=5

Operator Description Example

== If the values of two operands are equal, then the condition (a == b) is

43
becomes true. not true.

!= If values of two operands are not equal, then condition becomes (a!=b)
true. is true

> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.

< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.

<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.

Example
O
a=10 u
b=5 print("a>b=>",a>b) t
print("a>b=>",a<b) p
print("a==b=>",a==b) u
print("a!=b=>",a!=b) t:
print("a>=b=>",a<=b) a
print("a>=b=>",a>=b) >
b
=
>
T
r
u
e
a
>
b
=
>
F
a
l
s
e
a
=
=
b
=

44
> b
F =
a >
l F
s a
e l
a! s
= e
b a
= >
> =
T b
r =
u >
e T
a r
> u
= e

Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example

= Assigns values from right side operands to left side c=a+b


operand assigns
value of a +
b into c

+= Add AND It adds right operand to the left operand and assign the c += a is
result to leftoperand equivalent
to c
=c+a
-= It subtracts right operand from the left operand and c -= a is
Subtract assign the result to left operand equivalent
AND to c
= c -a
*= Multipl It multiplies right operand with the left operand and c *= a is
AN y assign the result to left operand equivalent
D to c
= c *a
/= Divide It divides left operand with the right operand and assign c /= a is
AN the result to left operand equivalent
D to c
= c /ac
/= a is
equivalent
to c
= c /a

45
%= Modulu It takes modulus using two operands and assign the c %= a is
AN s result to left operand equivalent
D to c
=c%a
**= Exponent Performs exponential (power) calculation on c **= a is
AND operators and assign value to the left equivalent
operand to c
= c ** a
//= Floor It performs floor division on operators and assign value c //= a is
Divisio to the left operand equivalent
n to c
= c // a

46
Example Output
Line 1 -
a =21
Value of c
b =10 is 31 Line 2
c=0 - Value of
c=a+b c is 52 Line
print("Line 1 - Value of c is ",c) c += a 3 - Value
print("Line 2 - Value of c is ", c) c *= a of c is 1092
print("Line 3 - Value of c is ",c) c /= a Line 4 -
print("Line 4 - Value of c is ", c) c = 2 Value of c
c %=a is 52.0 Line
print("Line 5 - Value of c is ",c) c **= a 5 - Value
print("Line 6 - Value of c is ",c) c //= a of c is2
print ("Line 7 - Value of c is ", c) Line 6 - Value of
c is 2097152
Line 7 - Value of
c is99864

47
Logical Operators:
-Logical operators are the and, or, not operators.

Output
x
Example a
a = True b = False n
print('a and b is', a and b) print('a or d
b is' ,a or b) print('not a is', not a) y
i
s
F
a
l
s
e
x
o
r
y
i
s
T
r
u
e
n
o
t
x
i
s
F
a
l
s
e

Bitwise Operators:
● A bitwise operation operates on one or more bit patterns at the level of individual bits
Example: Let x = 10 (0000 1010 in
binary)and

y = 4 (0000 0100 in binary)


48
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 L
c=0 i
# 12 = 0000 1100 n
c = a & b;
e
2
-
V
a
l
u
e
o
f
c
i
s
6
1
L
i
n
e
3
-
V
a
l
u
e
o
f
c
i
s
4
9
L
i
n
e
4

49
- e s
V o -
a f 6
l c 1
u i
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a|b; # 61 = 00111101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c c = a^b;
# 49 = 00110001
print "Line 3 - Value of c is ", c c =~a; # - print "Line 4 - Value of c is ", c
61 = 11000011 c = a<<2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111
print "Line 6 - Value of c is ", c

Membership Operators:

❖ Evaluates to find a value or a


variable is in the specified
sequence of string, list, tuple,
dictionary or not.
❖ Let, x=[5,3,6,4,1]. To check
particular item in list or not, in
and not in operators areused.

Example:
x=[5,3,6,4,1]
>>>5 in x

True
>>>5 not in x

False

50
Identity Operators:
i) They are used to check if two values (or variables) are located on the
same partof the memory.

Example
O
x =5 u
y =5 t
x2 = 'Hello' y2= 'Hello' p
print(x1 is not y1) print(x2 is y2) u
t
F
a
l
s
e
T
r
u
e

51
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation

depends on the order of operations.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names


for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators


-For mathematical operators, Python follows mathematical convention.
-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,
Subtraction) is a useful way to remember the rules:
ii) Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1)is 4, and (1+1)**(5-2) is8.
• You can also use parentheses to make an expression easier to read,asin(minute
* 100) / 60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and2
*3**2 is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction. So
2*3-1 is 5, not 4, and 6+4/2 is 8, not5.
• Operators with the same precedence are evaluated from left to right (except
exponentiation).

52
Examples:

a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 A=6+4- m=-43||8&&0||-2
a=9-4+6-1 1+6 m=- 43||0||-2
a=5+6-1 a=11- A=10-1+6 m=1||-2 m=1
1 a=10 A=9+6 A=15

● Membership Operators
● Identity Operators

Let us have a look on all operators one by one.

Boolean VALUES:
The truth values of an expression is stored as a python data type called bool. There are only two
such values in this data type. True and False.
Boolean Data Types
In the below program we find out the data types of True and False Boolean values.
Example
print(True)
print(type(True))
print(False)
print(type(False))
Output
Running the above code gives us the following result −
True
<class 'bool'>
False
<class 'bool'>

Boolean expression

61
Boolean expression is an expression that evaluates to a Boolean value. It almost always involves a
comparison operator. In the below example we will see how the comparison operators can give us
the Boolean values. The bool() method is used to return the truth value of an ex[resison.
Example
Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.
Below we have examples which use numbers streams and Boolean values as parameters to the bool
function. The results come out us true or false depending on the parameter.

Expression:

An expression is a combination of operators and operands that is interpreted to produce some


other value. In any programming language, an expression is evaluated as per the precedence of its
operators. So that if there is more than one operator in an expression, their precedence decides
which operation will be performed first. We have many different types of expressions in Python.
Let’s discuss all types along with some exemplar codes :
1. Constant Expressions: These are the expressions that have constant values only.
Example:
● Python3

# Constant Expressions

x = 15 + 1.3

print(x)

Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators,
and sometimes parenthesis. The result of this type of expression is also a numeric value. The
operators used in these expressions are arithmetic operators like addition, subtraction, etc. Here
are some arithmetic operators in Python:

perator
s Syntax Functioning

+ x+y Addition

62
– x–y Subtraction

Multiplicatio
* x*y n

/ x/y Division

// x // y Quotient

% x%y Remainder

Exponentiati
** x ** y on

3. Integral Expressions: These are the kind of expressions that produce only integer results after
all computations and type conversions.
Example:
● Python3

# Integral Expressions

a = 13

b = 12.0

c = a + int(b)

print(c)

Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.
Example:
● Python3

# Floating Expressions

63
a = 13

b=5

c=a/b

print(c)

Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both
sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and
then compared as per relational operator and produce a boolean output in the end. These
expressions are also called Boolean expressions.
Example

# Relational Expressions

a = 21

b = 13

c = 40

d = 37

p = (a + b) >= (c - d)

print(p)

Output
True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9.
As we know it is not correct, so it will return False. Studying logical expressions, we also come
across some logical operators which can be seen in logical expressions most often. Here are some
logical operators in Python:

Operato Syntax Functioning

64
r

P and It returns true if both P and Q are true otherwise


and Q returns false

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false

Example:
Let’s have a look at an exemplar code :

P = (10 == 9)

Q = (7 > 5)

# Logical Expressions

R = P and Q

S = P or Q

T = not P

print(R)

print(S)

print(T)

Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are performed at
bit level.
Example:

65
# Bitwise Expressions

a = 12

x = a >> 2

y = a << 1

print(x, y)

Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single
expression, and that will be termed as combinational expressions.
Example:

# Combinational Expressions

a = 16

b = 12

c = a + (b >> 1)

print(c)

Output
22
But when we combine different types of expressions or use multiple operators in a single
expression, operator precedence comes into play.

Conditional Statements:
Conditional if
Alternative if… else

66
Chained if…elif…else
Nested if….else

Conditional (if):
conditional (if) is used to test a condition, if the condition is true the
statements inside if will be executed.
syntax:

Flowchart:

Program to provide bonus mark if the output


category is
sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery
m=m+5 G/S S
print(“mark is”,m) mark is 90

67
Alternative (if-else):

In the alternative the condition must be true or false. In this else statement can be
combined with if statement. The else statement contains the block of code that executes
when the condition is false. If the condition is true statements inside the if get executed
otherwise else part gets executed. The alternatives are called branches, because they are
branches in the flow of execution.
syntax:

Flowchart:

Examples:

1. odd or even number


2. positive or negative number
3. leap year or not

Odd or even number Output


n=eval(input("enter a number")) enter a number4
if(n%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive
number") else:
print("negative number")
leap year or not Output
y=eval(input("enter a year")) enter a year2000
if(y%4==0): leap year
print("leap
year") else:
print("not leap year")

68
Chained conditionals (if-elif-else)
The elif is short for else if.
● This is used to check more than one condition.

● If the condition1 is False, it checks the


condition2 of the elif block. If all the
conditions are False, then the else part
is executed.

● Among the several if...elif...else part, only one


part is executed according to the condition.

The if block can have only one else block.


syntax: But it can have multiple elif blocks.
▪ The way to express a computation like
that is a chained conditional.

Flowchart:

69
70
student mark system Output
mark=eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")

Nested conditionals
One conditional can also be nested within another. Any number of condition can be
nested inside one another. In this, if the condition is true it checks another if condition1. If
both the conditions are true statement1 get executed otherwise statement2 get execute. if
the condition is false statement3 gets executed

Syntax

71
Flowchart:

Example:

1. greatest of three numbers


2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a
b=eval(input(“enter the value of b”)) 9 enter the value of
c=eval(input(“enter the value of c”)) a 1 enter the value
if(a>b): of a 8

if(a>c):

print(“the greatest no
is”,a)

else
if(b>c):

print(“the greatest no

else
print(“the greatest no

positive negative or zero output


n=eval(input("enter the value of
enter the value of n:-9
n:")) if(n==0):
h i
print("the number is zero")
else:
72
else:

print("the number is negative")

2.Iteration Or Control Statements.

i. sta
te
ii. whi
le
iii. for
iv.
re
State:
Transition from one process to another process under specified condition with in a time is
called
state.
While loop:
While loop statement in Python is used to repeatedly executes set of statement
as long as a given condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if
the test expression is True. After one iteration, the test expression is checked again.
This process continues until the test expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while start with indentation and the first unintended line marks
the end.

Syntax:

Flow chart:

73
Examples:

1. program to find sum of n numbers:


2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not

Sum of n numbers: output


n=eval(input("enter enter n
n")) i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

Factorial of a numbers: output


n=eval(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)

Sum of digits of a number: output


n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 6
a=n%10
sum=sum+a
n=n//10
print(sum)

74
Reverse the given number: output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)

Armstrong number or not


n=eval(input("enter a number")) outputa number153
enter
org=n The given number is Armstrong number
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is
Armstrong number")
else:
print("The given number is not
Armstrong number")

n=eval(input("enter
Palindrome or not a number")) enter
outputa number121
org=n The given no is palindrome
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is
palindrome") else:
print("The given no is not palindrome")

75
For loop:

for in range:

We can generate a sequence of numbers using range() function.


range(10) will generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.

syntax

Flowchart:

For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over
a

sequence is called traversal. Loop continues until we reach the last element in
the sequence. The body of for loop is separated from the rest of the code using
indentation.

76
Sequence can be a list, strings or tuples

s.no sequences example output


R
1. For loop in string for i in "Ramu":
A
print(i)
M
U

2
2. For loop in list for i in [2,3,5,6,9]:
3
print(i)
5
6
9
for i in (2,3,1): 2
3. For loop in tuple
print(i) 3
1

Examples:

1. Program to print Fibonacci series.


2. check the no is prime or not
Fibonacci series output

77
check the no is prime or not output
n=eval(input("enter a number")) enter a no:7
for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")

3.Loop Control
Structures BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of the loop
completely.

78
Syntax:
break

Flowchart

example Output
for i in "welcome": w
if(i=="c"): e
brea l
k
print(i
)

79
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the
loop.
Syntax: Continue

Flowchart

Example: Output

for i in "welcome": if(i=="c"): w


continue print(i) e
l
o
m
PASS e

80
It is used when a statement is required syntactically but you don’t want any code to
execute.
It is a null statement, nothing happens when it is executed.

Syntax:
pas
s
brea
k
Example Output
for i in w
“welcome”: if e
(i == “c”): l
pas c
s o
print( m
i) e

Difference between break and continue

break continue

It terminates the current loop and It terminates the current iteration


executes the remaining statement and transfer the control to the next
outside the loop. iteration in the loop.

synta syntax:
x: continue
break
for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
brea continue
k print(i)
print(i)

81
w w
e e
l l
o
m
e

82
else statement in loops:

else in for loop:

If else statement is used in for loop, the else statement is executed when the loop has
reached the

limit.
The statements inside for loop and statements inside else will also execute.

example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6

else in while loop:


If else statement is used within while loop , the else part will be executed when the
condition become false.
The statements inside for loop and statements inside else will also execute.
Program output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5

Function:


Fruitful function
 Void function
A function that returns
Return a value is called fruitful function.
values
 Parameters
Example:

Root=sqrt
Local (25) global
and
Example:
 scope Function
def add():

83
a=10
b=20
c=a+b
return c
c=add()
print(c)

Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2
variables return a+b–
return expression return
8– return value

Need For Function:

• When the program is too complex and large they are divided into parts. Each part
is separately coded and combined into single program. Each subprogram is called
as function.
• Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
• Functions are used to avoid rewriting same code again and again in a program.
• Function provides code re-usability
• The length of the program is reduced.

Types of function:
Functions can be classified into two categories:

84
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.

85
Built in function Description

>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object

>>>range(2,8,1) [2, #returns range of given values


3, 4, 5, 6, 7]
>>>round(7.8) 8.0 #returns rounded integer of the given number

>>>chr(5) #returns a character (a string) from an integer


\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) 5 # returns integer from string or float

>>>pow(3,5) 243 #returns power of given number

>>>type( 5.6) #returns data type of object to which it belongs


<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name:") # reads and returns the given string
enter name : George

ii) User Defined Functions:


• User defined functions are the functions that programmers create for their requirement
anduse.
• These functions can then be combined to form module which can be used in other
programs by importing them.
• Advantages of user defined functions:
● Programmers working on large project can divide the workload by making different
functions.
● If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.

• defdefinition:
Function keyword(Sub
is used to define a function.
program)
• Give the function name after def keyword followed by parentheses in which arguments are
given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement

86
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1 statement2…
statement n return[expression]

Example:
def
my_add(a,b):
c=a+b
return
c

Function Calling: (Main Function)

Once we have defined a function, we can call it from another function,


program or even the Pythonprompt.
To call a function we simply type the function name with appropriate arguments.
Example:
x=5
y=4

my_add(x,y)

Flow of Execution:

• The order in which statements are executed is called the flow of execution
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.

Function Prototypes:

i. Function without arguments and without return type


ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type

87
i) Function without arguments and without return type
o In this type no argument is passed through the function call and no output is
return to main function
o The sub function will read the input values perform the operation and print
the result in the same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main
function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is
return to the main function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is
return to the main function
Without Return
Type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter print(c)
b")) c=a+b a=int(input("enter
print(c) a"))
add() b=int(input("enter
b")) add(a,b)
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15

With return type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enterb")) return
c=a+b c
return c a=int(input("enter
c=add() a"))
print(c) b=int(input("enter
b")) c=add(a,b)
print(c)
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15

88
89
Parameters And Arguments:

Parameters:
● Parameters are the value(s) provided in the parenthesis when we write function header.
● These are the values required by function to work.
● If there is more than one value required, all of them will be listed in parameter list
separated by
comma.
● Example: defmy_add(a,b):
Arguments :
● Arguments are the value(s) provided in function call/invoke statement.
● List of arguments should be supplied in same way as parameters are listed.
● Bounding of parameters to arguments is done 1:1, and so there should be same
number and type of arguments as mentioned in parameter list.
● Example:my_add(x,y)
RETURN STATEMENT:
● The return statement is used to exit a function and go back to the place from where it
was called.
● If the return statement has no arguments, then it will not return any values. But exits from
function.
Syntax:

return[expression]

Example:

def my_add(a,b):
c=a+b

return
c x=5
y=4

print(my_add(x,y))

Output:

ARGUMENT TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments

90
Required Arguments :The number of arguments in the function call should match
exactly with the function definition.

defmy_details( name, age ):


print("Name: ", name)

print("Age ", age)

return

91
Output:
Name: georgeAge56

Keyword Arguments:

Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.

def my_details( name, age ):


print("Name: ", name)
print("Age ", age)
return

Output:
Name: georgeAge56

DefaultArguments:

Assumes a default value if a value is not provided in the function call for that
defmy_details( name, age=40 ):

print("Name: ", name)


print("Age ", age) return

my_details(name="george")

argument.
Output:
Name: georgeAge40

Variable lengthArguments

If we want to specify more arguments than specified while defining the function,
variable length arguments are used. It is denoted by * symbol before parameter.

def my_details(*name ):
print(*name)

my_details("rajan","rahul","micheal", ärjun")

Output:
rajanrahulmichealärjun

92
Local and Global Scope

Global Scope

The scope of a variable refers to the places that you can see or access a variable.
A variable with global scope can be used anywhere in the program.
It can be created by defining a variable outside the function.
Example output
a=50
def add():
b=20
Global Variable
c=a+b
70
print
© Local Variable

def sub():
b=30
c=a-b 20
print
50
©
print(a)

93
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20
70
c=a+b
Local Variable
print©
def sub():
20
b=30

c=a-b Local Variable

print error
© error
print(a
)
print(b)

Function Composition:

Function Composition is the ability to call one function from within another function
It is a way of combining functions such that the result of each function is passed as
the argument of the next function.
In other words the output of one function is given as the input of another
function is known as function composition.

find sum and average using output


function
composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter
b:")) sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)

94
Recursion
A function calling itself till it reaches the base value - stop point of function
call. Example: factorial of a given number using recursion

Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)

n=eval(input("enter no. to
find fact:"))
fact=fact(n)
print("Fact is",fact)

Explanation

Examples:

1. sum of n numbers using recursion


2. exponential of a number using recursion

95
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)
n=eval(input("enter no. to find sum: "))
sum=sum(n)
print("Fact is",sum)

96
97
98

You might also like