0% found this document useful (0 votes)
5 views137 pages

PT2

Uploaded by

tanmistha2010
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)
5 views137 pages

PT2

Uploaded by

tanmistha2010
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
You are on page 1/ 137

Class - 1

Python Introduction
What is Python?
Python is a popular programming language (OOP). It was created by Guido van Rossum, and
released in 20th February, 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.
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.
Python Indentation
 Indentation refers to the spaces at the beginning of a code line.
 Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
 Python uses indentation to indicate a block of code.

Example:
if 5 > 2:
print("Five is greater than two!")
print(“Thank u for using Python”)
Python Variables
In Python, variables are created when you assign a value to it:

Example

Variables in Python:

x=5
y = "Hello, World!"

print(y)

Output: Hello, World!

Python has no command for declaring a variable.

Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:

Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore
it, and you have made a multiline comment.
Python Variables

Variables
Variables are containers for storing data values.

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type
after they have been set.
Example
x=4 # x is of type int
x = "Anu" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Get the Type


You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes?


String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'

Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a both are different variable

Python - Variable Names


Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). 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 underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 A variable name cannot be any of the Python keywords.
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

Remember that variable names are case-sensitive

Multi Words Variable Names


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"

Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Output: Orange
Banana
Cherry
Note: Make sure the number of variables matches the number of values, or else you will get
an error.

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Output : Orange
Orange
Orange

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.
Example
Packing a list:
fruits = ["apple", "banana", "cherry"]
Unpacking a list:
x, y, z = fruits
print(x)
print(y)
print(z)

Output :
apple
banana
cherry

Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:

Example:

x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Output:
Python is awesome

You can also use the + operator to output multiple variables:


Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Output:
Python is awesome

Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
For numbers, the + character works as a mathematical operator:
Example
x=5
y = 10
print(x + y)
Output: 15

In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:
Example
x=5
y = "John"
print(x + y)
===========================================================================
=======================

Class – 2
Python Data Types
Built-in Data Types

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence list, tuple, range
Types:
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

Getting the Data Type


You can get the data type of any object by using the type() function:

Example:

Print the data type of the variable x:

x=5

print(type(x))

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str


x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", frozenset
"cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType

Python Numbers
There are three numeric types in Python:

• int

• float

• complex

Variables of numeric types are created when you assign a value to them

Example:

x=1 # int

y = 2.8 # float

z = 1j # complex

To verify the type of any object in Python, use the type() function:

Example:

print(type(x))

print(type(y))

print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.

Example:

Integers:

x=1

y = 35656222554887711

z = -3255522

print(type(x))

print(type(y))

print(type(z))

Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Example

Floats:

x = 1.10

y = 1.0

z = -35.59

print(type(x))

print(type(y))

print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

Example:

Floats:
x = 35e3
y = 12E4

z = -87.7e100

print(x)

print(y)

print(z)

Output:

35000.0

120000.0

-8.77e+101

Complex
Complex numbers are written with a "j" as the imaginary part:

Example

Complex:

x = 3+5j

y = 5j

z = -5j

print(type(x))

print(type(y))

print(type(z))

Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:

Example

Convert from one type to another:


x = 1 # int

y = 2.8 # float

z = 1j # complex

#convert from int to float:

a = float(x)

#convert from float to int:

b = int(y)

#convert from int to complex:

c = complex(x)

print(a)

print(b)

print(c)

print(type(a))

print(type(b))

print(type(c))

Note: You cannot convert complex numbers into another number type.

Random Number
Python does not have a random() function to make a random number, but Python has a
built-in module called random that can be used to make random numbers:

Example
Import the random module, and display a random number between 1 and 9:

import random

print(random.randrange(1, 10))

Python Casting
Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

• int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)

• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)

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

Example

Integers:
x = int(1) # x will be 1

y = int(2.8) # y will be 2

z = int("3") # z will be 3

Example

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


Example

Strings:

x = str("s1") # x will be 's1'

y = str(2) # y will be '2'

z = str(3.0) # z will be '3.0'

Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")

print('Hello')

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:

Example

a = "Hello"

print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example

You can use three double quotes Or three single quotes::

a = """ A red circle with a diagonal line

through the middle, from top-left


to bottom right, used to indicate that

something is not permitted.

Commonly shown in conjunction

with other symbols to indicate

No Smoking, No Bikes, or similar.."""

print(a)

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a string
with a length of 1.

Square brackets can be used to access elements of the string.

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"

print(a[1])

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example

Loop through the letters in the word "banana":

for x in "banana":

print(x)

Output:
b

String Length
To get the length of a string, use the len() function.

Example

The len() function returns the length of a string:

a = "Hello, World!"

print(len(a))

Output: 13

===========================================================================
=================

Class – 3
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.

Example

Check if "free" is present in the following text:

txt = "The best things in life are free!"

print("free" in txt)

Output: True

Print only if "free" is present:


txt = "The best things in life are free!"

if "free" in txt:

print("Yes, 'free' is present.")

Check if NOT

To check if a certain phrase or character is NOT present in a string, we can use the keyword
not in.

Example

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"

print("expensive" not in txt)

print only if "expensive" is NOT present:

txt = "The best things in life are free!"

if "expensive" not in txt:

print("No, 'expensive' is NOT present.")

Python - Slicing Strings


Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the
string.

Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"

print(b[2:5])

Example
Get the characters from the start to position 5 (not included):

b = "Hello, World!"

print(b[:5])

Example

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"

print(b[2:])

Python Method/Function

i) Upper Case
upper()

Converts a string into upper case

Example:

The upper() method returns the string in upper case:

a = "Hello, World!"

print(a.upper())

ii) Lower Case


lower()

Converts a string into lower case

Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())
iii) Remove Whitespace
strip()

Returns a trimmed version of the string

Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.

Example:

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "

print(a.strip()) # returns "Hello, World!"


iv) Replace()
replace()

Returns a string where a specified value is replaced with a specified value

Example

The replace() method replaces a string with another string:

a = "Hello, World!"

print(a.replace("H", "J"))
v) Remove white space from all.
rstrip()

Returns a right trim version of the string

Remove any white spaces at the end of the string:

txt = " banana "

x = txt.rstrip()

print("of all fruits", x, "is my favorite")


vi) Capitalize first Letter
capitalize()
Converts the first character to upper case

Example

Upper case the first letter in this sentence:

txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)
vii) isdigit()
isdigit()

Returns True if all characters in the string are digits

Check if all the characters in the text are digits:

txt = "50800"

x = txt.isdigit()

print(x)
viii) isspace()
isspace()

Returns True if all characters in the string are whitespaces

Check if all the characters in the text are whitespaces:

txt = " "

x = txt.isspace()

print(x)
ix) lstrip()
lstrip()

Returns a left trim version of the string

Remove spaces to the left of the string:

txt = " banana "

x = txt.lstrip()
print("of all fruits", x, "is my favorite")
x) Centered string
center()

Returns a centered string

center()

Print the word "banana", taking up the space of 20 characters, with "banana" in the middle:

txt = "banana"

x = txt.center(20)

print(x)

Using the letter "O" as the padding character:

print(txt.center(50,”=”))
xi) Count()
count()

Return the number of times the value "apple" appears in the string:

txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)
xii) Find() -> return position
find()

Searches the string for a specified value and returns the position of where it was found

Find()

Where in the text is the word "welcome"?:

txt = "Hello, welcome to my world."

x = txt.find("welcome")

print(x)
xiii) Format specified values in string
format()

Formats specified values in a string

Python String format() Method

Insert the price inside the placeholder, the price should be in fixed point, two-decimal
format:

txt = "For only {price:.2f} dollars!"

print(txt.format(price = 49))

Output: For only 49.00 dollars!

Using different placeholder values:

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)

txt2 = "My name is {0}, I'm {1}".format("John",36)

txt3 = "My name is {}, I'm {}".format("John",36)


xiv) isalpha()
isalpha()

Returns True if all characters in the string are in the alphabet


xv) title ()
title()

Converts the first character of each word to upper case

Make the first letter in each word upper case:

txt = "Welcome to my world"

x = txt.title()

print(x)

Output: Welcome To My World”

Note that the first letter after a non-alphabet letter is converted into a upper case letter:

txt = "hello b2b2b2 and 3g3g3g"


x = txt.title()

print(x)

Output: Hello B2B2B2 And 3G3G3G


xvi) swapcase()
Swaps cases, lower case becomes upper case and vice versa

Make the lower case letters upper case and the upper case letters lower case:

txt = "Hello My Name Is PETER"

x = txt.swapcase()

print(x)
xvii) strip()
strip()

Returns a trimmed version of the string

Remove spaces at the beginning and at the end of the string:

txt = " banana "

x = txt.strip()

print("of all fruits", x, "is my favorite")


xviii) zfill()
zfill()

Fills the string with a specified number of 0 values at the beginning

Fill the string with zeros until it is 10 characters long:

txt = "50"

x = txt.zfill(10)

print(x)

===========================================================================
=======
Class -4
String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)

Output: Hello World

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

Escape Characters
To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by


double quotes:

Example:

You will get an error if you use double quotes inside a string that is surrounded by double
quotes:

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Example:
The escape character allows you to use double quotes when you normally would not be
allowed:

txt = "We are the so-called \"Vikings\" from the north."

Output: We are the so-called "Vikings" from the north.

Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

Example:

Print(“Name \t Class \t Roll \n Anu \t X \t 15”)

Python Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:
Example:

print(10 + 5)

Python divides the operators in the following groups:

1. Arithmetic operators

2. Assignment operators

3. Comparison operators

4. Logical operators

5. Identity operators

6. Membership operators

7. Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
Now we give code examples of arithmetic operators in Python. The code is given below
-
1. a = 32 # Initialize the value of a
2. b = 6 # Initialize the value of b
3. print('Addition of two numbers:',a+b)
4. print('Subtraction of two numbers:',a-b)
5. print('Multiplication of two numbers:',a*b)
6. print('Division of two numbers:',a/b)
7. print('Reminder of two numbers:',a%b)
8. print('Exponent of two numbers:',a**b)
9. print('Floor division of two numbers:',a//b)

Example of Floor division:

x = 15
y=2
print(x // y)
Output: 7
#the floor division // rounds the result down to the nearest whole number

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

Example:

a = 32 # Initialize the value of a

b=6 # Initialize the value of b

print('a=b:', a==b)

print('a+=b:', a+b)

print('a-=b:', a-b)

print('a*=b:', a*b)

print('a%=b:', a%b)

print('a**=b:', a**b)

print('a//=b:', a//b

a=b: False

a+=b: 38

a-=b: 26

a*=b: 192

a%=b: 2

a**=b: 1073741824

a//=b: 5

Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y
!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal x >= y


to

<= Less than or equal to x <= y

Now we give code examples of Comparison operators in Python. The code is given
below –

1. a = 32 # Initialize the value of a

2. b = 6 # Initialize the value of b

3. print('Two numbers are equal or not:',a==b)

4. print('Two numbers are not equal or not:',a!=b)

5. print('a is less than or equal to b:',a<=b)

6. print('a is greater than or equal to b:',a>=b)

7. print('a is greater b:',a>b)

8. print('a is less than b:',a<b)

Output:
Now we compile the above code in Python, and after successful compilation, we
run it. Then the output is given below -
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False

Python Logical Operators


Logical operators are used to combine conditional statements:
Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is x < 5 or x < 4


true

not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are x is y


the same object

is not Returns True if both variables are x is not y


not the same object

Example:

x = ["apple", "banana"]

y = ["apple", "banana"]

z=x

print(x is z)

# returns True because z is the same object as x

print(x is y)

# returns False because x is not the same object as y, even if they have the same content

print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True
because x is equal to y

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the x in y


specified value is present in the object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object

Example:

x = ["apple", "banana"]

print("banana" in x)

# returns True because a sequence with the value "banana" is in the list

Operator Precedence
Operator precedence describes the order in which operations are performed.

Example:

Parentheses has the highest precedence, meaning that expressions inside parentheses must
be evaluated first:

print((6 + 3) - (6 + 3))

Output:

print((6 + 3) - (6 + 3))

"""
Parenthesis have the highest precedence, and need to be evaluated first.
The calculation above reads 9 - 9 = 0
"""
Example:
Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:

print(100 + 5 * 3)

Output:

print(100 + 5 * 3)

"""
Multiplication has higher precedence than addition, and needs to be evaluated first.
The calculation above reads 100 + 15 = 115
"""
The precedence order is described in the table below, starting with the highest precedence
at the top: Rules are (BADMAS)
Full Form of BADMAS is‍Brackets, orders, division, multiplication, addition, subtraction)

Operator Description

() Parentheses

** Exponentiation

+x -x ~x Unary plus, unary minus, and


bitwise NOT

/ * // % division, Multiplication, floor


division, and modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR
| Bitwise OR

== != > >= < <= is is Comparisons, identity, and


not in not in membership operators

not Logical NOT

and AND

or OR

Example:

print(100 - 3 ** 3)

"""
Exponentiation has higher precedence than subtraction, and needs to be evaluated first.
The calculation above reads 100 - 27 = 73
"""
Example:
print(100 + 5 * 3)

"""
Multiplication has higher precedence than addition, and needs to be evaluated first.
The calculation above reads 100 + 15 = 115
"""
Example:

print(5 + 4 - 7 + 3)

"""
Additions and subtractions have the same precedence, and we need to calculate from left to
right.
The calculation above reads:
5+4=9
9-7=2

2+3=5
"""

===========================================================================
========================

Class – 5
Python If ... Else
Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

• Equals: a == b

• Not Equals: a != b

• Less than: a < b

• Less than or equal to: a <= b

• Greater than: a > b

• Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example:

If statement:

a = 33

b = 200

if b > a:

print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".

Indentation:
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.

elif

The elif keyword is Python's way of saying "if the previous conditions were not true, then try
this condition".

Example:

a = 33

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but the elif condition is true,
so we print to screen that "a and b are equal".

else

The else keyword catches anything which isn't caught by the preceding conditions.

a = 200

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

else:

print("a is greater than b")


Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.

Example:

One line if statement:

if a > b: print("a is greater than b")


Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:

Ternary Operators
Example:

One line if else statement:

a=2

b = 330

print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:
Example:

One line if else statement, with 3 conditions:

a = 330

b = 330

print("A") if a > b else print("=") if a == b else print("B")

Nested If
If with in a if is called nested if.

Follow the Example:

X=5

Y=9
# Example 1 : Number checker

num = 5

if num > 0:

print("The number is positive.")

else:

if num < 0:

print("The number is negative.")

else:

print("The number is zero.")

Python Print() Function


Python print

Example:

Print a message onto the screen:

print("Hello World")

Definition and Usage

The print() function prints the specified message to the screen, or other standard output
device.

The message can be a string, or any other object, the object will be converted into a string
before written to the screen.

Example:

Print more than one object:

print("Hello", "how are you?")

Example:

Print a tuple:

x = ("apple", "banana", "cherry")


print(x)

Output: ('apple', 'banana', 'cherry')

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.

Example

a = 33

b = 200

if b > a:

pass
Guess what will be output:
str1=”Python World”

print(str1*2)

??

Python User Input


User Input

Python allows for user input.

That means we are able to ask the user for input.

The method is a bit different in Python 3.6 than Python 2.7.

Python 3.6 uses the input() method.

Python 2.7 uses the raw_input() method.

The following example asks for the username, and when you entered the username, it gets
printed on the screen:

Example:

name=input("Enter your name : ")

age=input("Enter your age : ")


address=input("Enter your address ")

print("Your name is : ",name)

print("Your age is : ",age)

print("Your address is : ",address)

What does input () do in Python?

In Python, we use the input() function to take input from the user. Whatever you enter as
input, the input function converts it into a string. If you enter an integer value still input()
function converts it into a string.

The Python interpreter will not execute further lines until the user enters the input.

Example:

1. # Python program showing

2. # a use of input()

3. name = input("Enter your name: ") # String Input

4. age = int(input("Enter your age: ")) # Integer Input

5. marks = float(input("Enter your marks: ")) # Float Input

6. print("The name is:", name)

7. print("The age is:", age)

8. print("The marks is:", marks)

Some Example:
1) WAP to input an age and check whether he is child/teenage/young/old according to the
following criteria.

If age<13 then print child

If age between 13 to 19 then print teenage

If age between 20 to 49 then print young

If age between 50 to 120 then print old

Otherwise print not a valid age.


Example-1:

age=int(input("Enter an age "))

if age< 13:

print("Child")

elif age>=13 and age<=19:

print("Teenage")

elif age>=20 and age<50:

print("Young")

elif age>=50 and age<=120:

print("Old")

else:

print("Not a valid age")

Example-2:

WAP to input two numbers and print the sum.

num1=int(input("Enter 1st number "))

num2=int(input("Enter 2nd number "))

print("The addition of ",num1," and ",num2 ," is ",(num1+num2))

Example-3:

WAP to input a student’s name and his 3 subject’s number. Finally print his name, total,
average and grade.

Grade calculation:

If avg<35 grade will be fail

Avg between 35 and 44 grade 3rd division

Avg between 45 and 59 grade 2nd division


Avg between 60 to 75 grade 1st division

Otherwise grade will be excellent.

name=input("Enter a student's name ")

sub1=int(input("Enter 1st subject's number "))

sub2=int(input("Enter 2nd subject's number "))

sub3=int(input("Enter 3rd subject's number "))

tot=sub1+sub2+sub3

avg=int(tot/3)

if avg<35:

grade="Fail"

elif avg>=35 and avg<45:

grade="3rd Division"

elif avg>=45 and avg<60:

grade="2nd Division"

elif avg>=60 and avg<80:

grade="1st Division"

else:

grade="Excellent"

print("Name of the Student : ",name)

print("Total : ",tot," Average = :",avg,"% Grade = : ",grade)

#WAP to enter 3 number and find the largest

num1=int(input("Enter first number "))


num2=int(input("Enter second number "))

num3=int(input("Enter third number "))

if((num1>num2 and num1>num3) and (num1 !=num2 and num1 !=num3)):

print(num1," is greater")

elif ((num2>num1 and num2>num3) and (num2 !=num1 and num2 !=num3)):

print(num2," is greater")

elif ((num3>num1 and num3>num2) and (num3 !=num1 and num3 !=num2)):

print(num3," is greater")

else:

print(num1,",",num2,",",num3 ," Three are equals")

Output:

Enter first number: 1

Enter second number: 999

Enter third number: 687

999 is greater

=======================================================================

Class -6
Revision class
Revision previous class.

Class-7
Python placeholder
In Python, Placeholder is a word, characters or a string of characters to hold a
temporary place. The placeholder behaves as a dynamic place holder in such a way
that you can pass a particular value for that placeholder.

How to Use Placeholders in Python

In this article, we show how to use placeholders in Python to serve as placeholders for
data, such as objects.

So if you have a variable in Python or any other type of data type, you can create a
placeholder, usually in a print function to reserve a spot for this variable before
explicitly saying what the variable is.

The best way to see this is in actual code.

In the code below, we create 2 variables, desination1 and destination2.

We then print out these variables with a print function using placeholders.

You'll see exactly how this works below.

Example:

>>> destination1= "beach"

>>> destination2= "park"

>>> amount= 3

>>> print ("I went to the {} and {} {} times this week". format (destination1,
destination2, amount))

Output: I went to the beach and park 3 times this week

So, the above code is very simple.

We create 3 variables.

The first variable we create is destination1. We set this variable equal to "beach"

The second variable we create is destination2. We set this variable equal to "park"

The third variable we create is amount. We set this variable equal to 3.

We then create a print statement.

Every time you see {} in the print statement, this represents a placeholder.

What a placeholder does is it holds a place for a variable. When we do the substition,
the variable will appear in the place of {}.
You see this 3 times in the print statement, meaning 3 places for variables are
reserved.

After we are done with the print statement ending with quotes (either single or
double), we put .format(destination1, destination2, amount), representing the 3
variables in order that we want substituted for the placeholders.

In the end, this gives us the output statement, " I went to the beach and park 3 times
this week"

Placeholders are great things to use in Python code especially if you are dealing with
different types of data.

For example, to create this same method the conventional way without placeholders,
we would have the following print line, shown below.

Example:

>>> print ("I went to the " + destination1 + " and " + destination2 + " " +
str(amount) + " times this week")

I went to the beach and park 3 times this week

You can see what an extreme pain this is.

There's a lot of annoyances.

One thing is, we have to keep breaking the string apart every time we want to put in a
variable.

Second, we have to remember to put appropriate spaces between variables, which can
be very annoying.

Lastly, for strings taking in different data types, such as int, we have to explicitly make
the variable a string with the str() function, or else Python will throw an error.

So there's a lot of annoyances.

With placeholders, all of this foregone.

You simply put the placeholder, without any care to the different data types, close the
string, put . format() with the names of the variables within the format function, and
that is it.

So this is just a quick guide on the value of placeholders in Python.

Python String format() Method


The format() method is a powerful tool that allows developers to create formatted
strings by embedding variables and values into placeholders within a template string.
This method offers a flexible and versatile way to construct textual output for a wide
range of applications. Python string format() function has been introduced for
handling complex string formatting more efficiently. Sometimes we want to make
generalized print statements in that case instead of writing print statements every
time we use the concept of formatting.

Python String Format() Syntax

Syntax: { }.format(value)

Parameters:

 value : Can be an integer, floating point numeric constant, string, characters or


even variables.

Returntype: Returns a formatted string with the value passed as parameter in the
placeholder position.

String Format() in Python Example

A simple demonstration of Python String format() Method in Python.

name = "Ram"

age = 22

message = "My name is {0} and I am {1} years \

old. {1} is my favorite \

number.".format(name, age)

print(message)

or

print("My name is {0} and I am {1} years old ".format(name, age))

String format() with multiple placeholders


Multiple pairs of curly braces can be used while formatting the string in Python. Let’s
say another variable substitution is needed in the sentence, which can be done by
adding a second pair of curly braces and passing a second value into the method.
Python will replace the placeholders with values in order.
Syntax : { } { } .format(value1, value2)

Parameters : (value1, value2) : Can be integers, floating point numeric constants,


strings, characters and even variables. Only difference is, the number of values passed
as parameters in format() method must be equal to the number of placeholders
created in the string.

Example:

print("Ready everybody {},{},{},{} ".format("One","Two","Three","Start!"))

Ouput:

Ready everybody One,Two,Three,Start!

Type Specifying In Python


More parameters can be included within the curly braces of our syntax. Use the format
code syntax {field_name: conversion}, where field_name specifies the index
number of the argument to the str.format() method, and conversion refers to the
conversion code of the data type.

Using %s – string conversion via str() prior to formatting

Example:

print("%25s" % ("Python World"))

print("%-25s" % ("Python World"))

print("%.5s" % ("Python World"))

Output:

Python World

Python World

Pytho

The release of Python version 3.6 introduced formatted string literals, simply called “f-
strings.” They are called f-strings because you need to prefix a string with the letter
'f' to create an fstring. The letter 'f' also indicates that these strings are used for
formatting. Although there are other ways for formatting strings, the Zen of Python
states that simple is better than complex and practicality beats purity--and f-strings
are really the most simple and practical way for formatting strings. They are also
faster any of the previous more commonly used string.
This document will explain how to use the many options available with f-strings.
Alignment There are several ways to align variables in f-strings. The various alignment
options are as follows:

Formatting inside Placeholders


You have seen that it is possible to have Placeholder as empty, with a variable or an
index. It is also possible that you can apply Python String Formatting inside the
Placeholder.

Here is the list of formats

Forma
Description Example
t

print("The binary to decimal


value is : {:d}".format(0b0011))
It will give the output in
:d decimal format when used
inside the placeholder Output:
The binary to decimal value is :
3
print("The binary value is :
It will give the output in{:b}".format(17))
:b binary format when used
Output:
inside the placeholder
The binary value is : 111110100

print("The value is :
{:f}".format(40))

This will output a fixed- Output:


point number format. By
The value is : 40.000000
default, you will get the
output of any number with Example: Showing output upto
:f
six decimal places. In case 2 decimal places.
you need up to 2 decimal
print("The value is :
places, use it as. 2f i.e.. a
{:.2f}".format(40))
period (.) in front of 2f
Output:

The value is: 40.00

:o This will output octal print("The value is :


format {:o}".format(500))
Forma
Description Example
t

Output:

The value is : 764

print("The value is :
{:x}".format(500))
This will output hex format
:x
in lowercase Output:

The value is : 1f4

print("The value is :
{:X}".format(500))
This will output hex format
:X
in uppercase. Output:

The value is : 1F4

print("The value is :
{:n}".format(500.00))
This will output number
:n
format. Output:

The value is : 500

print("The value is : {:
%}".format(0.80))

Output:
This will give the output in
a percentage format. The value is : 80.000000%
By default it will give 6
decimal places for the This example shows how to skip
:% the decimal places by using
percentage output, in case
you don’t want any {:.0%} inside the placeholder.
decimal value you can use
print("The value is :
period with 0 i.e (:.0%).
{:.0%}".format(0.80))
Output:

The value is: 80%

print("The value is
This will output an
{:_}".format(1000000))
underscore as a thousand
:_
separator. It is available Output:
from python 3.6+.
The value is : 1_000_000
Forma
Description Example
t

print("The value is :
{:,}".format(1000000))

Output:
This will output comma as
:,
a thousands separator The value is : 1,000,000
The comma(,) is added , as a
thousand separator as shown in
the output.

This example shows how to add


space or padding before the
given number. The number 5
indicates the space count you
This will add a space want before the number.
: before any positive
numbers print("The value is:
{:5}".format(40))

Output:

The value is: 40

The example shows how to get


the output with a minus (-) sign
before the number using {:-}.
This will add a minus sign print("The value is:
:-
before negative numbers {:-}".format(-40))

Output:

The value is: -40

The example shows how to get


the output with a plus (+) sign
before the number using {:+}.
You can use plus sign to
:+ indicate the number is print("The value is: {:
positive +}".format(40))

Output:

The value is: +40

:= The equal to is used to The example shows how to get


Forma
Description Example
t

the output with a plus (+/-) sign


before equal to sign using {:=}.

place the +/- sign on the print("The value is


left side. {:=}".format(-40))

Output:

The value is -40

The example shows to use {:^}


to center align the text. The
number 10 is used to add 10
spaces to show the center-
aligned when the value is
replaced.

print("The value {:^10} is


positive value".format(40))

Output:
This will center align the
:^
final result The value 40 is a positive
value

Here, you can use 10 that will


add 10 spaces in the final text,
and the value to be replaced
will be center-aligned between
the 10 spaces. The spaces of 10
are added just to show the
center alignment of the
replaced value.

The space of 10 is added using


(:>10), and the value replaced
is right-aligned.

This will right-align the print("The value {:>10} is


:> positive value".format(40))
final result
Output:

The value 40 is positive


value
Forma
Description Example
t

The space of 10 is added using


(:<10), and the value replaces
is left aligned.

This will left align the final print("The value {:<10} is


:< positive value".format(40))
result
Output:

The value 40 is positive


value

Print the text in the middle/certain spaces.

print(f'{"My Grocery List":^30s}')

My grocery list will be printed after 30 spaces. Note : is the value seperator

Output:

My Grocery List

print(f'{"Welcome to SSPM":^100s}')

welcome to SSPM will be printed after 100 spaces.

Like : Welcome to SSPM

Print(“=”,50)

= sign will be printed 50 times.

Output: ==============================================

Example of “f-strings.”
The F-string offers a convenient way to embed Python expression inside string literals
for formatting. print(f"{val}for{val} is a portal for {val}.") print(f"Hello, My name is
{name} and I'm {age} years old.")

Name=”Rakesh Sharma”

Age=69
Rating=985.8721

Print(f”My name is {Name}, I’m {Age} years old and My rating is {Rating}”)

Output: My name is Rakesh Sharma, Im 69 years old and My rating is 985.8721

value=11/7

print(f"Normal number ",value)

print(f"Value = {value:.2f}")

print(f"Value = {value:.3f}")

print(f"Value = {value:3.5f}")

Output:

Normal number 1.5714285714285714

Value = 1.57

Value = 1.571

Value = 1.57143

%s is a placeholder for string datatype. Placeholder is the concept picked up from the
C language. They are used in format strings to represent a variable whose type will be
determined in runtime. Placeholders are represented as a character or a set of
characters used after a % symbol. % represents the placeholder and the following
character or set of characters represents the data type of the value that will replace
the placeholder. For integers, there’s %d, for float there’s %f, and for strings, there is
%s.

Example:

name="Mohit Dhar"

age=54

rating=6.75

print(f"My name is %s. I am %d years old. My rating is %.2f" %(name,age,rating))

Output: My name is Mohit Dhar. I am 54 years old. My rating is 6.75

name="Ramu Singh"

age=86

rat=695.6943
print("My name is {} and age is {}".format(name,age))

print("My name is {name} == {age}")

print(f"Name ...... {name} {age}")

print(f"MY NAME %s AGE IS %d RATING IS %.2f"% (name,age,rat))

Print today’s date


# Prints today's date with help

# of datetime library

import datetime

today = datetime.datetime.today()

print(f"{today:%B %d, %Y}")

Padding Variable Substitutions


Using string.format() method, you can add padding, space by using placeholders
inside your string.

Example:

In below example will add space inside the Placeholder using the format(). To add
space, you have to specify the number of spaces inside curly brackets after the
colon(:). So the Placeholder will look like {:5}.

print("I have {:5} dogs and {:5} cat".format(2,1))

Output:

I have 2 dogs and 1 cat

You can also give the index inside the placeholder for example: {0:5} where 0 will
refer to the first value inside format.

print("I have {0:5} dogs and {1:5} cat".format(2,1))

Output:

I have 2 dogs and 1 cat

print("Example of Padding {:5} function".format("Variable"))


Output: Example of Padding Variable function

====================================================
===================================

Class – 8 for Loops…


Example of for loop
Let me explain the syntax of the Python for loop better.
 The first word of the statement starts with the keyword “for” which signifies the
beginning of the for loop.
 Then we have the iterator variable which iterates over the sequence and can be
used within the loop to perform various functions
 The next is the “in” keyword in Python which tells the iterator variable to loop for
elements within the sequence
 And finally, we have the sequence variable which can either be a list, a tuple, or
any other kind of iterator.
 The statements part of the loop is where you can play around with the iterator
variable and perform various function

Python string is a sequence of characters. If within any of your programming applications,


you need to go over the characters of a string individually, you can use the for loop here.
Here’s how that would work out for you.
1. Print individual letters of a string using the for loop

word="anaconda"

for letter in word:

print (letter)

Output:

d
a

The reason why this loop works is because Python considers a “string” as a sequence
of characters instead of looking at the string as a whole.

2. Using the for loop to iterate over a Python list or tuple:


Lists and Tuples are iterable objects. Let’s look at how we can loop over the elements
within these objects now.

words= ["Apple", "Banana", "Car", "Dolphin" ]

for word in words:

print (word)

Output:

Apple

Banana

Car

Dolphin

Now, let’s move ahead and work on looping over the elements of a tuple
here.

nums = (1, 2, 3, 4)

sum_nums = 0

for num in nums:


sum_nums = sum_nums + num

print(f'Sum of numbers is {sum_nums}')

# Output
# Sum of numbers is 10

3. Nesting Python for loops


When we have a for loop inside another for loop, it’s called a nested for loop. There are
multiple applications of a nested for loop.

Consider the list example above. The for loop prints out individual words from the list.
But what if we want to print out the individual characters of each of the words within
the list instead?
This is where a nested for loop works better. The first loop (parent loop) will go over
the words one by one. The second loop (child loop) will loop over the characters of
each of the words.

words= ["Apple", "Banana", "Car", "Dolphin" ]

for word in words:


The following lines w
#This loop is fetching word from the list
A
print ("The following lines will print each letters of "+word) p
for letter in word: p
l
#This loop is fetching letter for the word e
print (letter)
The following lines w
print("") #This print is used to print a blank line
B
a
n
a
n
a

The following lines w


C
a
r

The following lines w


D
o
l
p
h
i
n
4. range() in for loop in Python

How to use Python range() in for loop? The range() function is typically used with for
loop to repeat a block of code for all values within a range. Let’s discuss different
scenarios of using the range() function with for loop in Python. By specifying start,
stop, and step parameters, By excluding the start and step parameters and excluding
step parameters. We will also discuss how to pass the negative step value in the
range() function.

# Syntax
for element in range(start,stop,step):
statements...
Here start and step are optional. But stop are mandatory.

As you can see, the range function has three parameters:


 start: where the sequence of integers will start. By default, it's 0.
 stop: where the sequence of integers will stop (without including this value).
 step: the value that will be added to each element to get the next element in the
sequence. By default, it's 1.

1. Quick Examples of using range() in the for loop


Following are quick examples of range() with the for loop.

# Example 1: range() with stop parameter


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

# Example 2: range() with start and stop parameters


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

# Example 3: range() with start,stop and step parameters


for i in range(1,10,2):
print(i)

# Example 4: range() with negative step


for i in range(20,10,-3):
print(i)
2. range() with for Loop Examples
Let’s specify start and stop parameters in the range() function and iterate them using
the for loop. This is typically used when you wanted to run a block of code a certain
number of times.

# range() with start and stop parameters


for i in range(1,10):
print(i,end=",")

# Output:
# 1,2,3,4,5,6,7,8,9,
Here, I have specified the start as 1 and the stop as 10 on range(). The for loop will
iterate from 0 to 9 with the default step value as 1.

3. Iterate for Loop range with Only Stop Value


Let’s specify only stop parameter in the range() function and iterate them using the for
loop. Here, by default, it uses the start param as 0 and the step value as 1.

# range() with stop parameter


for i in range(10):
print(i,end=",")

# Output:
# 0,1,2,3,4,5,6,7,8,9,
We specified the stop as 10. The for loop will iterate from 0 to 9. Inside the for loop, we
are displaying the values present in the range.

4. Iterate range() with All Parameters


Now, let’s specify all parameters start, stop, and step in the range() function with the
Python for loop and iterate the range values using the for loop. Note that here, I have
used the step value as 2, so it increments by 2.

# range() with start,stop and step parameters


for i in range(1,10,2):
print(i,end=",")

# Output:
# 1,3,5,7,9,

5. Iterate range() in Reverse


To decrement the range of values in for loop, use the negative value as a step
parameter. Let’s specify the negative step value in the range() function and iterate
them with for loop.
# range() with negative step
for i in range(20,10,-3):
print(i,end=",")

# Output:
# 20,17,14,11,
We have iterated from 20 to 10 (Reverse order) by decrementing 3 at each step. The
final iterated values are – 20,17,14 and 11.

Alternatively, to get a reverse range in Python, you can use the reversed() function in
combination with the range function. For example:

# Using reversed() & range()


for i in reversed(range(10)):
print(i)
This would print the numbers from 9 to 0 (inclusive)
break, continue and pass in Python
Using loops in Python automates and repeats the tasks in an efficient manner. But
sometimes, there may arise a condition where you want to exit the loop completely,
skip an iteration or ignore that condition. These can be done by loop control
statements. Loop control statements change execution from their normal sequence.
When execution leaves a scope, all automatic objects that were created in that scope
are destroyed. Python supports the following control statements:

 Break statement

 Continue statement

 Pass statement

Break Statement in Python


The break statement in Python is used to terminate the loop or statement in which it is
present. After that, the control will pass to the statements that are present after the
break statement, if available. If the break statement is present in the nested loop, then
it terminates only those loops which contain the break statement.

Syntax of Break Statement

The break statement in Python has the following syntax:

for / while loop:


# statement(s)
if condition:
break
# statement(s)
# loop end
Example:

for i in range(20):
if i==10:
break
else:
print(i)

Python continue statement

# Python program to
# demonstrate continue
# statement

# loop from 1 to 10
for i in range(1, 11):

# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
# of i
print(i, end = " ")

Output:
1 2 3 4 5 7 8 9 10

Pass statement in Python


As the name suggests pass statement simply does nothing. The pass statement in
Python is used when a statement is required syntactically but you do not want any
command or code to execute. It is like a null operation, as nothing will happen if it is
executed. Pass statements can also be used for writing empty loops. Pass is also used
for empty control statements, functions, and classes.

# Pass statement
s="welcome"
for i in s:
if i == 'c':
print('Pass executed')
pass
print(i)
Output:
w
e
l
Pass executed
c
o
m
e

For Loop Exercise


1) What will be display?

n=10

for i in range(10):

for j in range(n-i):

print("*",end="")

print()

2)

# WAP to reverse a string

str = input("Input a word to reverse: ")

for i in range(len(str) - 1, -1, -1):

print(str[i], end="")

print("\n")

3) # Reverse a number

n = int(input("Enter number: "))

rev = 0

while(n != 0):

rem = n % 10

rev = rev * 10 + rem

n = n // 10

print(rev)
# output

# 12534

4) Write a program to display the first 7 multiples of 7.

5) Write a program to filter even number from a list.

x={40,15,23,60,17,19,82}
for i in x:
if i%2==0:
print(i,end=" ")
Output:
40 82 60

Class-9 While loop…


What Is a While Loop in Python?
A while loop is a control flow statement that allows you to repeatedly execute a block
of code as long as a specific condition is true. It is commonly used when you don't
know the exact number of iterations in advance and need to keep executing the code
until the condition becomes false.

What Is the Syntax for a While Loop in Python?


The syntax of while loop in Python is as follows:

while condition:

# code block to be executed

n=1
while n<=10:
print(n)
n=n+1

Else With the While Loop in Python


You can also use the else clause with the while loop in Python. The code inside the else
block is executed only when the while loop condition becomes false.
count = 1
while count <= 5:
print(count)
count += 1
else:
print("Loop completed successfully!")
Output:
1
2
3
4
5
Loop completed successfully!

While true in Python


The while True condition in Python helps you declare an infinite loop that runs until it
encounters a break statement or is interrupted.

Example:

n=5
while True:
print("Python")
if n>10:
break
else:
n+=1

Python While Loop Interruptions


Sometimes, you don’t want the loop to execute completely. For those cases, Python
provides you with two statements to interrupt the execution of the while loop - break
and continue same like for loop.

Number Pattern Program in Python Using While Loop


You might have seen problems where you’re required to print number patterns such as
below:

These problems are nothing but Python while loop exercises. For example, the above
pattern can be printed using the following code:

Example:
n=1
while n <= 5:
print(str(n) * n)
n += 1
Output:
1
22
333
4444
55555

Example:
rows = 7
current_row = 1
while current_row <= rows:
print("*" * current_row)
current_row += 1
Output:
*
**
***
****
*****
******
*******
What Is the Difference Between a while Loop and a for Loop in
Python?
The main difference between a for and while loop in Python is the way they iterate. A
while loop continues executing as long as a condition remains true, whereas a for loop
iterates over a predefined sequence or collection of elements.

While loops are typically used when the number of iterations is not known in advance
or when a condition needs to be continuously monitored. On the other hand, for loops
are suitable for iterating over a known sequence, such as a list or a range of numbers.

Example:

import time
start = int(input('Enter countdown duration in seconds: '))
print(f'Blastoff in {start} seconds:')
count = start
while count >= 0:
time.sleep(1) # pauses for 1 second so humans can see the countdown
# there will be a 1s pause after 'blastoff in...' but less before 'BLASTOFF!'
print(f'T-{count}')
count -= 1
time.sleep(0.25)
print('BLASTOFF!')
Class-10 Exercise
We will solve some problems:

row=int(input("Enter number of rows : "))


k=0
Outpu
for i in range(1,row+1):
Enter number
for j in range(1,(row-i)+1):
*
print(end=" ")
***
while k!=(2*i-1):
****
print("*",end="")
*****
k=k+1
*******
k=0
print()

Exercise 1: Write a program in Python to display the Factorial of a number.


Hint 1

Input : 5

Expected output

Factorial is 120

Hint 1

Input : 6

Expected output

Factorial is 720

:: Solution ::

# Factorial of a number

n = int(input("Enter number: ")) # 5

if(n == 0 or n < 0):


print("Value of n should be greater than 1")

else:

fact = 1

while(n):

fact *= n

n = n-1

print(f"Factorial is {fact} ")

# output

# Factorial is 120

Using for loop with output

fact=1

n=int(input("Enter a number : "))


Output:
for i in range(1,n+1):
Enter a number : 5
if n<=1: 1 X 1 =1
print("Factorial is ",n) 1 X 2 =2
2 X 3 =6
else:
6 X 4 = 24
print(fact," X ",i," = ",end='') 24 X 5 = 120
fact=fact*i

print(fact)

Exercise 2 : Write a program in Python to swap to numbers.


#Example of Swap case

n=int(input("Enter first number "))

m=int(input("Enter 2nd number "))

temp=n

n=m

m=temp

print("N = ",n," M = ",m)


#without third variable

n=int(input("Enter first number "))

m=int(input("Enter 2nd number "))

n=n+m

m=n-m

n=n-m

print("N = ",n," M = ",m)

Exercise 3 : Write a program in Python to print Fibonacci series.


#Fibonacci series

n=int(input("Enter a range : "))

First_Val=0

Second_Val=1

for i in range(1,n):

if(n<=1): Output:
next=n Enter a range : 7
else: 0+1=1
next=First_Val+Second_Val 1+1=2
print(First_Val,"+ ",end='') 1+2=3

First_Val=Second_Val 2+3=5

print(Second_Val,"= ",end='') 3+5=8


5 + 8 = 13
Second_Val=next

print(next)

Exercise 4 : Write a program in Python to print prime number upto a range


flag=0

n=int(input("Enter a Range : "))


Enter a Range:
Prime no 2
Prime no 3

for i in range(2,n):

for j in range(2,i):

if i%j==0:

flag=1

break;

if flag==0:

print("Prime no "+str(i))

else:

flag=0

Exercise 5 : Write a program in Python to print Sum of square of first n


natural number

n=int(input("Enter a Number : "))


sum=0
c=0
for i in range(1,n+1): Enter a Num
c=c+1 1+4+9+16+
sum=sum+(i*i)
if(c!=n):
print(i*i,end='+')
print(i*i,end=' ')
print("=",sum)

Exercise 6 : Write a program to display the first 7 multiples of 7.


Hint 1
Use if and for loop with break
Expected output
Result: 0 7 14 21 28 35 42 49
# First 7 numbers multiple of 7
count = 0
for i in range(200):
if i%7 == 0:
print(i,end=" ")
count = count+1
if count == 8:
break

# output
# 0 7 14 21 28 35 42 49

Exercise 7: WAP to separate positive and negative number from a list.


n = [2,-7,-28,190,982,6,-97]

pos = []

neg = []
Original List are [2, -7, -28, 190, 98
for i in range(len(n)): 97]
if n[i]<1: Positive numbers are : [2, 190, 98
neg.append(n[i]) Negative numbers are : [-7, -28,
else:

pos.append(n[i])

print("Original List are ",n)

print("Positive numbers are : ",pos)

print("Negative numbers are : ",neg)

1) Exercise 8 : Write a program to filter even and odd number from a list.
2) Exercise 9 : Write a Python program to reverse a number.
3) Exercise 10 : Write a program to print n natural number in descending
order using a while loop.

Class-11 (Python - List Methods)

Python Lists
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:

Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

List Items
List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the
order of the items will not change.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:

Example
Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types


List items can be of any data type:

Example
String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


Now I will describe one by one …

Access List Items


List items are indexed and you can access them by referring to the index number:

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

Output: banana

1) append() method
Definition and Usage

The append() method appends an element to the end of the list.

fruits=["banana","cherry","apple"]

fruits.append("pineapple")
['banana', 'cher
print(fruits)

Note: append() takes exactly one argument.

Add a list to a list:


fruits=["banana","cherry","apple"]
['banana', 'cherr
cars=["Volvo","BMW","Ford"]

fruits.append(cars)

print(fruits)

2) Python List clear() Method


Remove all elements from the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']

fruits.clear()

3) Python List copy() Method


Copy the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']


['apple',
x = fruits.copy()
print(x)

4) Python List count() Method


Return the number of times the value "cherry" appears in the fruits list:

fruits = [‘cherry’, 'apple', 'banana', 'cherry']

x = fruits.count("cherry")

Output: 2
5) Python List extend() Method
Add the elements of cars to the fruits list:

Definition and Usage

The extend() method adds the specified list elements (or any iterable) to the end of
the current list.

fruits = ['apple', 'banana', 'cherry']

cars = ['Ford', 'BMW', 'Volvo']


['apple', 'banana', '
fruits.extend(cars)

6) Python List index() Method

Definition and Usage

The index() method returns the position at the first occurrence of the specified value.
What is the position of the value "cherry":

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")

Output: 2

7) Python List insert() Method


Definition and Usage

The insert() method inserts the specified value at the specified position.

Syntax

list.insert(pos, elmnt)

Parameter Values
Parameter Description

pos Required. A number specifying in which position to insert the value

elmnt Required. An element of any type (string, number, object etc.)

fruits = ['apple', 'banana', 'cherry'] Output:


fruits.insert(2, "orange") ['apple', 'banana', 'orange', 'c
print(fruits)

8) Python List pop() Method


Definition and Usage

The pop() method removes the element at the specified position.

Syntax

list.pop(pos)

Remove the second element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)

print(fruits)

9) Python List remove() Method


Definition and Usage

The remove() method removes the first occurrence of the element with the specified
value.

Remove the "banana" element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

print(fruits)
10) Python List reverse() Method
Definition and Usage

The reverse() method reverses the sorting order of the elements.

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

print(fruits)

11) Python List sort() Method


Definition and Usage

The sort() method sorts the list ascending by default.

You can also make a function to decide the sorting criteria(s).

Syntax

list.sort(reverse=True|False, key=myFunc)

Parameter Values

Parameter Description

reverse Optional. reverse=True will sort the list descending. Default is reverse

key Optional. A function to specify the sorting criteria(s)

Sort the list alphabetically:

cars = ['Ford', 'BMW', 'Volvo']


Output:
cars.sort() ['BMW', 'Ford', 'Volvo']
print(cars)

Sort the list descending:

cars = ['Ford', 'BMW', 'Volvo'] Output:


cars.sort(reverse=True) ['Volvo', 'Ford', 'BMW']
print(cars)
Class-12 (Python - List Methods Example)
1) Write a Python program to sum all the items in a list.
Ans:

number=[10,20,50,100,30]

tot=0 Output:

for i in number: Total is 210

tot=tot+i

print("Total is ",tot)

2. Write a Python program to multiply all the items in a list.


3. Write a Python program to get the largest number from a list.
Ans:

number=[10,20,50,100,30]

max=0
Output:
Largest number is : 100
for i in number:

if i>max:

max=i

print("Largest number is : ",max)

4. Write a Python program to get the smallest number from a list.


5) WAP to create a new list from fruits list where “apple” is present in the
existing list.
fruits = ["apple", "banana","red apple", "cherry", "kiwi", "mango","pineapple","green
apple","coconut"]

newlist=[] # create a blank list

for x in fruits:
Output:
if "apple" in x:
['apple', 'red apple', 'pineapple', '
newlist.append(x)

print(newlist)

6) WAP to Set the values in the new list to upper case/title/capitalize:


fruits = ["green apple", "banana", "red cherry", "kiwi", "unripe mango"]

newlist = [x.upper() for x in fruits]

print(newlist) Output:

for i in fruits: ['GREEN APPLE', 'BANANA', 'RED CHER

newlist.append(i.upper()) ['Green Apple', 'Banana', 'Red Cher

print(newlist)
['Green apple', 'Banana', 'Red cherr

newlist = [x.title() for x in fruits]

print(newlist)

newlist = [x.capitalize() for x in fruits]

print(newlist)

7) WAP to create positive and negative list from list1 having approximately
10 positive and negative nos.
8) WAP to count no of digit.

9) Calculate the sum of all numbers from 1 to a given number.

10) WAP to create a unique list and duplicate list numbers from a list having
duplicate values.
list1=[10,30,50,20,90,10,100,50,10,30]

unique=[]

dupli=[] Output:
for i in list1: Unique list: [10, 30, 50, 20, 90

if i not in unique: Duplicate list: [10, 50, 30

unique.append(i)

elif i not in dupli:

dupli.append(i)

print("Unique list : ",unique)

print("Duplicate list : ",dupli)

11) WAP to display output like below Output:


row=10 *
for i in range(0,row): **
***
****
for j in range(0,i+1):

print("*",end="")

print()

for i in range(row,0,-1):

for j in range(0,i-1):

print("*",end="")

print()

12) Check if the given string is a palindrome.


str1 = input("Enter a string: ")

str2 = str1[::-1]
Output:
if str1 == str2:
Enter a string: madam
print(str1, "is a palindrome")
Madam is a palindrome
else:

print(str1, "is not a palindrome")

Syntax of List index()


The syntax of the list index() method is:

list.index(element, start, end)

list index() parameters

The list index() method can take a maximum of three arguments:

 element - the element to be searched

 start (optional) - start searching from this index

 end (optional) - search the element up to this index


Find the index of the element
# vowels list

vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e' in vowels

index = vowels.index('e')

print('The index of e:', index)

# element 'i' is searched

# index of the first 'i' is returned

index = vowels.index('i')

print('The index of i:', index)

How to fix list index out of range using Index()


Here we are going to create a list and then try to iterate the list using the constant
values in for loops.

list1 = [1,2 ,3, 4, 5]

for i in range(6):

print(list1[i])

Follow the syntax of python index :


list1 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(list1[-1]) # display only mango

print(list1[:-1]) # display all items except mango

print(list1[::2]) # display alternate items 'apple', 'cherry', 'kiwi', 'mango'

print(list1[::-2]) # display alternate times in reverse order: 'mango', 'kiwi', 'cherry',


'apple'

print(list1[2::2]) # display 'cherry', 'kiwi', 'mango

Class-13 (Python Tuples)


A tuple is an ordered collection of elements of different data types. Furthermore, we
represent them by writing the elements inside the parenthesis separated by
commas. We can also define tuples as lists that we cannot change.

Here are some of the key features of Python tuples:


 Tuples are immutable, meaning they cannot be changed once they are
created. This makes them ideal for storing data that should not be modified,
such as database records.

 Tuples can have any number of items and they may be of different types
(integer, float, list, string, etc.).

 Tuples are created using parentheses, with the items separated by commas. For
example, (1, 2, 3) is a tuple of three integers.

 Tuples can be accessed by index, starting with 0. For example, the first item in
the tuple (1, 2, 3) is 1.

 Tuples can be sliced, just like lists. For example, (1, 2, 3)[1:] is a tuple of two
integers, 2 and 3.

 Tuples can be concatenated, just like lists. For example, (1, 2, 3) + (4, 5, 6) is
a tuple of six integers, 1, 2, 3, 4, 5, 6.

 Tuples can be used as keys in dictionaries. For example, {1: 'a', 2: 'b', 3: 'c'} is
a dictionary with three key-value pairs, where the keys are integers and the
values are strings.

 Tuples can be unpacked into variables. For example, (x, y, z) = (1, 2, 3) is a


tuple of three integers, and the variables x, y, and z are assigned the
values 1, 2, and 3, respectively.

Here are some of the key differences between Python tuples and lists:
Tuples Lists

Immutable Mutable

Faster than lists Slower than tuples

Uses less memory Uses more memory


Tuples are denoted by Lists are denoted by square
parenthesis brackets

Here is a table summarizing the key differences between tuples and lists:
As you can see, tuples are immutable, meaning they cannot be changed once they are
created. This makes them ideal for storing data that should not be modified, such as
database records. Lists, on the other hand, are mutable, meaning they can be changed
after they are created. This makes them ideal for storing data that needs to be
updated, such as a list of items in a shopping cart.

Another key difference between tuples and lists is that tuples are faster than lists. This
is because tuples are stored in a contiguous block of memory, while lists are stored in
a non-contiguous block of memory. This means that accessing elements in a tuple is
faster than accessing elements in a list.

Finally, tuples use less memory than lists. This is because tuples are stored in a more
compact format than lists. This means that using tuples can help to improve the
performance of your program.

In general, tuples should be used when you need to store data that should not be
modified and when you need to improve the performance of your program. Lists
should be used when you need to store data that needs to be updated.

Disadvantages of tuples
 We cannot add an element to tuple but we can add element to list.

 We can't sort a tuple but in a list we can sort by calling "list. sort()" method.

 We can't remove an element in tuple but in list we can remove element.

 We can't replace an element in tuple but you can in a list.

Tuples creating
Create a Python Tuple With one Element

In Python, creating a tuple with one element is a bit tricky. Having one element within
parentheses is not enough.

We will need a trailing comma to indicate that it is a tuple,

x=("apple")

print(type(x)) # <class 'str'>

x=("apple",)

print(type(x)) # <class 'tuple'>


x="apple",

print(type(x)) # <class 'tuple'>

N.B.: If you want to create a single element tuple then you give a comma, after the
element otherwise it will treat as string.

var1 = ("Hello") # string

var2 = ("Hello",) # tuple

Python Tuples Methods


In Python ,methods that add items or remove items are not available with tuple. Only
the following two methods are available.

Some examples of Python tuple methods:

my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p')) # prints 2

print(my_tuple.index('l')) # prints 3

Change Tuples Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.

Example of Tuples Values

Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Output: ('apple', 'kiwi', 'cherry')

Add Items into Tuples


Since tuples are immutable, they do not have a built-in append() method, but there
are other ways to add items to a tuple.

1. Convert into a list: Just like the workaround for changing a tuple, you can convert
it into a list, add your item(s), and convert it back into a tuple.

Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
tuples=("apple","banana","orange")

list1=list(tuples)

list1.append("Pine Apple")

list1.insert(1,"Cherry")

tuples=tuple(list1)

print(tuples)

Output: ('apple', 'Cherry', 'banana', 'orange', 'Pine Apple')

Remove Items from Tuples


Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can use the
same workaround as we used for changing and adding tuple items:

Example
Convert the tuple into a list, remove "orange", and convert it back into a tuple:

tuples=("apple","banana","orange","mango")

list1=list(tuples)

list1.remove("orange")

tuples=tuple(list1)

print(tuples)

Output: ('apple', 'banana', 'mango')

The del keyword can delete the tuple completely:

Example
tuples=("apple","banana","orange","mango")

del tuples

print(tuples) #this will raise an error because the tuple no longer exists

Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called
"packing" a tuple:
Example
Packing a tuple:

fruits = ("apple", "banana", "cherry")


But, in Python, we are also allowed to extract the values back into variables. This is
called "unpacking":

Unpacking a tuple:

Example

fruits = ("apple", "banana", "cherry")


(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

Output:

apple

banana

cherry

Note: The number of variables must match the number of values in the tuple, if not,
you must use an asterisk to collect the remaining values as a list.

Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the
variable name and the values will be assigned to the variable as a list:

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)

print(yellow)

print(red)

Output:

apple

banana

['cherry', 'strawberry', 'raspberry']

Class-14 (Python Set)


A set is a collection which is unordered, unchangeable*, and unindexed

* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.

Example

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Duplicates Not Allowed


Sets cannot have two items with the same value.

Example

Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}


print(thisset)

The set() Constructor


It is also possible to use the set() constructor to make a set.

Example

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets


print(thisset)

Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or m

difference_update() Removes the items in this set that are also included in an
specified set

discard() Remove the specified item


intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in oth
set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and anoth

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Python Set copy() Method


Example

Copy the fruits set:

fruits = {"apple", "banana", "cherry"}


x = fruits.copy()
print(x)

Python Set difference() Method


Example

Return a set that contains the items that only exist in set x, and not in set y:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
Output: {'cherry', 'banana'}

Python Set difference_update() Method

Example

Remove the items that exist in both sets:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.difference_update(y)

print(x)

Output: {'cherry', 'banana'}

Definition and Usage

The difference_update() method removes the items that exist in both sets.

The difference_update() method is different from the difference() method, because


the difference() method returns a new set, without the unwanted items, and
the difference_update() method removes the unwanted items from the original set.

Python Set discard() Method


Example

Remove "banana" from the set:

fruits = {"apple", "banana", "cherry"}

fruits.discard("banana")

print(fruits)

Definition and Usage

The discard() method removes the specified item from the set.

This method is different from the remove() method, because the remove() method will
raise an error if the specified item does not exist, and the discard() method will not.

Python Set intersection() Method


Example

Return a set that contains the items that exist in both set x, and set y:

x={"apple","banana","cherry","python"}
y={"google","microsoft","python","banana"}

z=x.intersection(y)

print(z)

Output: {'python', 'banana'}

Python Set pop() Method


Example

Remove a random item from the set:

fruits = {"apple", "banana", "cherry"}

fruits.pop()

print(fruits)

Output: {'cherry', 'apple'} / {'apple', 'banana'}

Python Set symmetric_difference() Method


Example

Return a set that contains all items from both sets, except items that are present in
both sets:

x={"apple","banana","cherry","python"}

y={"google","microsoft","python","banana"}

z=x.symmetric_difference(y)

print(z)

Output: {'cherry', 'apple', 'microsoft', 'google'}

Python Set union() Method


Example

Return a set that contains all items from both sets, duplicates are excluded:

x={"apple","banana","cherry","python"}

y={"google","microsoft","python","banana"}

z=x.union(y)

print(z)

Output: {'banana', 'google', 'python', 'microsoft', 'apple', 'cherry'}

Definition and Usage


The union() method returns a set that contains all items from the original set, and all
items from the specified set(s).

You can specify as many sets you want, separated by commas.

It does not have to be a set, it can be any iterable object.

If an item is present in more than one set, the result will contain only one appearance
of this item.

Python Set update() Method


Example

Insert the items from set y into set x:

x={"apple","banana","cherry","python"}

y={"google","microsoft","python","banana"}

x.update(y)

print(x)

Output: {'google', 'banana', 'python', 'microsoft', 'apple', 'cherry'}

Test on Python
Python List, Tuple & Set exam

Python Dictionaries

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

Example:

Create and print a dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using
the key name.

Example

Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Output: Ford

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:

Example:

Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Dictionary Length
To determine how many items a dictionary has, use the len() function:

Example

Print the number of items in the dictionary:

print(len(thisdict))

Output: 3

Dictionary Items - Data Types


The values in dictionary items can be of any data type:

Example

String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

Output: {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}

The dict() Constructor


It is also possible to use the dict() constructor to make a dictionary.

Example

Using the dict() method to make a dictionary:

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)

Change Values
You can change the value of a specific item by referring to its key name:

Example

Change the "year" to 2018:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a
value to it:

Example

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Removing Items
There are several methods to remove items from a dictionary:

Example

The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Output: {'brand': 'Ford', 'year': 1964}

Python - Loop Dictionaries


thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964
}

for x in thisdict:

print(x)

Output: brand
model
year

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict:

print(thisdict[x])

Output: Ford
Mustang
1964

Example

You can use the keys() method to return the keys of a dictionary:

for x in thisdict.keys():
print(x)

Output: brand
model
year

Loop through both keys and values, by using the items() method:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x, y in thisdict.items():
print(x, y)

Output: brand Ford


model Mustang
year 1964

Python - Nested Dictionaries


myfamily = {

"child1" : {

"name" : "Emil",

"year" : 2004

},

"child2" : {

"name" : "Tobias",

"year" : 2007

},

"child3" : {

"name" : "Linus",

"year" : 2011

print(myfamily)

Output: {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year':
2007}, 'child3': {'name': 'Linus', 'year': 2011}}

Python Collections (Arrays)


There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows duplicate


members.

 Set is a collection which is unordered, unchangeable*, and unindexed. No


duplicate members.
 Dictionary is a collection which is ordered** and changeable. No duplicate
members.

Python Dictionary Methods


Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.

Method Description

clear() Removes all the elements from


the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the


specified keys and value

get() Returns the value of the specified


key

items() Returns a list containing a tuple


for each key value pair

keys() Returns a list containing the


dictionary's keys

pop() Removes the element with the


specified key

popitem() Removes the last inserted key-


value pair

setdefault( Returns the value of the specified


) key. If the key does not exist:
insert the key, with the specified
value

update() Updates the dictionary with the


specified key-value pairs

values() Returns a list of all the values in


the dictionary

Method clear()
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict)

thisdict.clear()

print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made
in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

Example

Make a copy of a dictionary with the copy() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Python Dictionary fromkeys() Method


Example:

Create a dictionary with 3 keys, all with the value 0:

x = ('key1', 'key2', 'key3')


y=0

thisdict = dict.fromkeys(x, y)

print(thisdict)

Output: {'key1': 0, 'key2': 0, 'key3': 0}

Python Dictionary get() Method


Get the value of the "model" item:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.get("model")

print(x)
Output: Mustang

Python Dictionary items() Method


Definition and Usage

The items() method returns a view object. The view object contains the key-value pairs
of the dictionary, as tuples in a list.

The view object will reflect any changes done to the dictionary, see example below.

Example:

Return the dictionary's key-value pairs:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x)

Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

When an item in the dictionary changes value, the view object also gets updated:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

car["year"] = 2018

print(x)

Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2018)])

Python Dictionary keys() Method


Return the keys:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x)

print(x) #before the change


car["color"] = "white"
print(x) #after the change

Output: dict_keys(['brand', 'model', 'year'])

dict_keys(['brand', 'model', 'year', 'color'])

dict_keys(['brand', 'model', 'year', 'color'])

Python Dictionary pop() Method


Example

Remove "model" from the dictionary:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.pop("model")

print(car)

Output: {'brand': 'Ford', 'year': 1964}

Python Dictionary popitem() Method


Remove the last item from the dictionary:

car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964,

"color": "White"

}
car.popitem()

print(car)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Python Dictionary setdefault() Method


Get the value of the "color" item, if the "color" item does not exist, insert "color" with
the value "white":

car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.setdefault("color", "White")

print(x)

print(car)

Output: White

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}

Python Dictionary update() Method


Definition and Usage

The update() method inserts the specified items to the dictionary.

The specified items can be a dictionary, or an iterable object with key value pairs.

Insert an item to the dictionary:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.update({"color": "White"})

print(car)

Output : {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}


Python Dictionary values() Method
car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.values()

print(x)

Output: dict_values(['Ford', 'Mustang', 1964])

The values() method returns a view object. The view object contains the values of the
dictionary, as a list.

The view object will reflect any changes done to the dictionary.

Example

When a values is changed in the dictionary, the view object also gets updated:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

car["year"] = 2018

print(x)

Output: dict_values(['Ford', 'Mustang', 2018])

Python Functions
1) Python program to find the area and perimeter of a circle
Here, we are going to learn how to calculate the area and perimeter of a circle in
Python?

Area of Circle
It is the area occupied by the circle. Given by the formula,

Area = π*R*R
Value of π = 3.14, R is the radius of a circle.

Perimeter of Circle
Perimeter of Circle: Also known as the circumference. It is given by the formula,

Perimeter = 2*π*R

Value of π = 3.14, R is the radius of a circle.

We will use these formulas for finding the area and perimeter of the circle with a given
radius. The value of π can either be used directly or can be extracted using
the pi value in the math library in Python.

Program to find area and perimeter of a circle

# Python program to find the

# area and perimeter of circle in python

# Initialising the value of PI

PI = 3.14

# Getting input from user

R = float(input("Enter radius of the circle: "))

# Finding the area and perimeter of the circle

area = (PI*R*R)

perimeter = (2*PI*R)

# Printing the area and perimeter of the circle

print("The area of circle is", area)

print("The perimeter of circle is", perimeter)

Output

RUN 1:

Enter radius of the circle: 1.2

The area of circle is 4.521599999999999

The perimeter of circle is 7.536


RUN 2:

Enter radius of the circle: 35.63

The area of circle is 3986.2202660000007

The perimeter of circle is 223.7564

Explanation

In the above code, we have initialized the value of PI with 3.14. Then asked the user
for an input for the value of R. Using the formulas, we calculated the value of area and
perimeter and printed it.

2. Python Program to find the area of triangle

Perimeter of Triangle
a=int(input("Side 1 : "))

b=int(input("Side 2 : "))

c=int(input("Side 3 : "))

perimeter=a + b + c

print("Perimeter of Triangle : ",perimeter)

Area of Triangle

1. # Three sides of the triangle is a, b and c:

2. a = float(input('Enter first side: '))

3. b = float(input('Enter second side: '))

4. c = float(input('Enter third side: '))

5.

6. # calculate the semi-perimeter

7. s = (a + b + c) / 2

8.

9. # calculate the area

10. area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

11. print('The area of the triangle is %0.2f' %area)


Area Perimeter
Circle Area = π*R*R perimeter = (2*PI*R)
area=0.5 * b * h perimeter=a + b + c
Triangle Area of a triangle = (s*(s-a)*(s-b)*(s-c))-
1/2

Calculate the Parameter and Area of different Shapes using functions

Program:

1. # defining functions

2. def p_circle(radius):

3. para = 2 * 3.14 * radius

4. print("Parameter of Circle:", para)

5.

6. def p_rectangle(height, width):

7. para = 2 * (height + width)

8. print("Parameter of Rectangle:", para)

9.

10. def p_square(side):

11. para = 4 * side

12. print("Parameter of Square:", para)

13.

14. def a_circle(radius):

15. area = 3.14 * radius * radius


16. print("Area of Circle:", area)

17.

18. def a_rectangle(height, width):

19. area = height * width

20. print("Area of Rectangle:", area)

21.

22. def a_square(side):

23. area = side * side

24. print("Area of Square:", area)

25.

26. # printing the starting line

27. print("WELCOME TO A SIMPLE MENSURATION PROGRAM")

28.

29. # creating options

30. while True:

31. print("\nMAIN MENU")

32. print("1. Calculate Parameter")

33. print("2. Calculate Area")

34. print("3. Exit")

35. choice1 = int(input("Enter the Choice:"))

36.

37. if choice1 == 1:

38. print("\nCALCULATE PARAMETER")

39. print("1. Circle")

40. print("2. Rectangle")

41. print("3. Square")

42. print("4. Exit")

43. choice2 = int(input("Enter the Choice:"))


44.

45. if choice2 == 1:

46. radius = int(input("Enter Radius of Circle:"))

47. p_circle(radius)

48.

49. elif choice2 == 2:

50. height = int(input("Enter Height of Rectangle:"))

51. width = int(input("Enter Width of Rectangle:"))

52. p_rectangle(height, width)

53.

54. elif choice2 == 3:

55. side = int(input("Enter Side of Square:"))

56. p_square(side)

57.

58. elif choice2 == 4:

59. break

60.

61. else:

62. print("Oops! Incorrect Choice.")

63.

64. elif choice1 == 2:

65. print("\nCALCULATE AREA")

66. print("1. Circle")

67. print("2. Rectangle")

68. print("3. Square")

69. print("4. Exit")

70. choice3 = int(input("Enter the Choice:"))

71.
72. if choice3 == 1:

73. radius = int(input("Enter Radius of Circle:"))

74. a_circle(radius)

75.

76. elif choice3 == 2:

77. height = int(input("Enter Height of Rectangle:"))

78. width = int(input("Enter Width of Rectangle:"))

79. a_rectangle(height, width)

80.

81. elif choice3 == 3:

82. side = int(input("Enter Side of Square:"))

83. a_square(side)

84.

85. elif choice3 == 4:

86. break

87.

88. else:

89. print("Oops! Incorrect Choice.")

90.

91. elif choice1 == 3:

92. break

93.

94. else:

95. print("Oops! Incorrect Choice.")

Python Functions (User Defina Function)


A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a User Define Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello Everybody, My first Function")
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello Everybody, My first Function")

my_function()

Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full
name:
Example
def my_function(fname):
print( "Hello " +fname )

my_function(“Arko”)
my_function("Anwesha")
my_function("Tanmistha")
my_function("Sayan")

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information
that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning
that if your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

Example

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Recursion
Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a


function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a very
efficient and mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself


("recurse"). We use the k variable as the data, which decrements (-1) every time we
recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best
way to find out is by testing and modifying it.

Example

Recursion Example
Example of recursion function (which will be repeatedly called by itself; until
it zero).

def factorial(n):

if n>0:

ans=n*factorial(n-1)

print(ans)

else:

ans=1

return ans

a=6

print("Factorial of ",a," is",factorial(a))

Output :
1

24

120

720

Factorial of 6 is 720

# Example of factorial

n=int(input("Enter a number "))

fact=1

for i in range(1,n+1):

print(fact,"x ",end='')

fact*=i

print(i,"=",fact)

print("Factorial of ",n," is ",fact)


=================Output:===========================

Enter a number 5

1x1=1

1x2=2

2x3=6

6 x 4 = 24

24 x 5 = 120

Factorial of 5 is 120

Keyword arguments allow us to employ any order, whereas default


arguments assist us to deal with the absence of values. And finally, in
Python, arbitrary arguments come in handy when we don't know how
many arguments are needed in the program at that moment.

Example of default Argument


Example 1

def nsquare(x, y = 2):

return (x*x + 2*x*y + y*y)

print("The square of the sum of 2 and 2 is : ", nsquare(2))

print("The square of the sum of 2 and 3 is : ", nsquare(2,4))

Output:
The square of the sum of 2 and 2 is : 16
The square of the sum of 2 and 3 is : 36

Example-2
def greet(name="Paglu"):
print(f"Hello, {name}!")

greet()
greet("Bob")

Output:
Hello, Paglu!
Hello, Bob!

Example-3

def add(x, y=10):


return x + y

print(add(5))

print(add(5, 20))
Output:
15
25
Example-4

Note – A default value can be set for any number of arguments in a function.
However, if we have a default argument, we must likewise have default
values for all the arguments to their right. Non-default arguments, in other
words, cannot be followed by default arguments.

Example –5
def function(a= 24, b, c):
print('Values are:')
print(a)
print(b)
print(c)

function(6,7)

File "", line 1


SyntaxError: non-default argument follows default argument

Keyword Arguments:
We have already learned how to use default arguments values,

functions can also be called using keyword arguments.

Arguments which are preceded with a variable name followed by a '=' sign (e.g.
var_name=") are called keyword arguments

Example 1:

def fn(a,b):
print ("a = ",a)
print ("b = ",b)

fn(b=1,a=2)
fn(1,2)
Output:
a = 2
b = 1
a = 1
b = 2

Example-2

def marks(english, math = 85, science = 80):

print('Marks in : English is - ', english,', Math - ',math, ', Science - ',science)

marks(71, 77)

marks(65, science = 74)

marks(science = 70, math = 90, english = 75)

Output: Marks in : English is - 71 , Math - 77 , Science - 80

Marks in : English is - 65 , Math - 85 , Science - 74

Marks in : English is - 75 , Math - 90 , Science - 70

Explanation:
Line 1: The function named marks has three parameters, there is no default value in
the first parameter (english) but remaining parameters have default values (math =
85, science = 80).

Line 3: The parameter english gets the value of 71, math gets the value 77 and
science gets the default value of 80.

Line 4: The parameter english gets the value of 65, math gets the default value of 85
and science gets the value of 74 due to keyword arguments.

Line 5: Here we use three keyword arguments and the parameter


english gets the value 75,
math gets the value 90
and science gets the value 70.
Arbitrary Argument Lists:
The arbitrary argument list is an another way to pass arguments to a function. In the
function body, these arguments will be wrapped in a tuple and it can be defined with
*args construct. Before this variable, you can define a number of arguments or no
argument.

Example -1:

def func1(*args):

for i in args:

print(i)

func1(20, 40, 60)

func1(80, 100)

Example-2:

def fn(*n):

s=0

for i in n:

s+=i

return s

print("Sum is ",fn(1,2,3,4))

Output: Sum is 10

UDF Examples:
1. Return multiple values from a function

def calculation(a, b):

addition = a + b

subtraction = a - b

# return multiple values separated by comma

return addition, subtraction

# get result in tuple format

res = calculation(40, 10)

print(res)
2. Create a function with a default argument

# function with default argument

def show_employee(name, salary=9000):

print("Name:", name, "salary:", salary)

show_employee("Ben", 12000)

show_employee("Jessa")

Output:
Name: Ben salary: 12000

Name: Jessa salary: 9000

3. Create a recursive function

def factorial(n):

if n==0:

return 1

else:

return( n*factorial(n-1))

a=5

print("Factorial of ",a," is",factorial(a))

4. WAP to find the factorial using recursive function

def recursion(k):

if(k > 0):

result = k + recursion(k - 1)

print(result)

else:

result = 0

return result
print("\n\nRecursion Example Results")

recursion(6)

5. Find the maximum no

def max(n,m):

if n>m:

return n

else:

return m

x=int(input("Enter 1st numbers "))

y=int(input("Enter 2nd numbers "))

print("Maximum number among ",x,y," is ",max(x,y))

6. Find the length of a string using UDF

def Check(string):

c=0

l=len(string)

for i in string:

c=c+1

return c

s=input("Enter a string ")

print("Length of string is ",Check(s))

7. WAP to enter a sentence and print how many vowels are there.

def Check_Vowel(txt):

c=0

for i in txt:

if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':

c=c+1
return c

x=input("Enter a sentence ")

n=Check_Vowel(x)

print("Number of vowels are ",n)

8. WAP to enter a sentence and print each vowel how many times is there.

Lambda / Anonymous Function

In Python, a lambda function is a special type of function without the function


name.
How to Use Lambda Functions in Python

An anonymous function in Python is a function without a name. It can be immediately


invoked or stored in a variable.

Anonymous functions in Python are also known as lambda functions.

A lambda function can take any number of arguments, but can only have one
expression.

Python Lambda Function Declaration


We use the lambda keyword instead of def to create a lambda function. Here's the
syntax to declare the lambda function:

lambda argument(s) : expression

Lambda function:
Example-1:

greet = lambda : print('Hello World')

# call lambda function

greet()

Output: Hello World

Example 2:
x=lambda a,b,c : a*b*c

print(x(2,5,10))

Output : 100

Example 3:

# Code to demonstrate how we can use a lambda function for adding 4 numbers

add = lambda num: num + 4

print( add(6) )

Example 3:

Multiply = lambda x, y : (x * y)

print(Multiply(4, 5))

Output: 20

Example 4:

1. # Python code to show the reciprocal of the given number to highlight the differe
nce between def() and lambda().

2. def reciprocal( num ):

3. return 1 / num

4.

5. lambda_reciprocal = lambda num: 1 / num

6.

7. # using the function defined by def keyword

8. print( "Def keyword: ", reciprocal(6) )

9.

10. # using the function defined by lambda keyword

11. print( "Lambda keyword: ", lambda_reciprocal(6) )

Output:

Def keyword: 0.16666666666666666

Lambda keyword: 0.16666666666666666


What Is the Difference Between Lambda and Regular Functions in Python?
Here are some differences between lambda functions and regular functions in Python:

LAMBDA FUNCTIONS REGULAR FUNCTIONS

Defined using the lambda


keyword Defined using the def keyword

Can be written in one line Requires more than one line of code

Return statement must be defined when returning


No return statement required values

Can be used anonymously Regular functions must be given a name

Python Arrays

Note: Python does not have built-in support for Arrays, but Python Lists can be used
instead.

What is an Array?

An array is a special variable, which can hold more than one value at a time. Arrays
are used to store multiple values in one single variable:

If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what
if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by
referring to an index number.

Access the Elements of an Array


You refer to an array element by referring to the index number.
Example

Get the value of the first array item:

cars = ["Ford", "Volvo", "BMW"]

x = cars[0]

print(x)

Output: Ford

Looping Array Elements


You can use the for in loop to loop through all the elements of an array.

Example

Print each item in the cars array:

cars = ["Ford", "Volvo", "BMW"]

for x in cars:
print(x)

Output:

Ford
Volvo
BMW
Rest is same as like as List.

Python classes/objects
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:

class MyClass:
x=5

p1 = MyClass() # create an object of MyClass


print(p1.x) # 5 will be display

The __init__() Function

All classes have a function called __init__(), which is always executed when the class is
being initiated.
Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created:

Example
Create a class named Person, use the __init__() function to assign values for name and
age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("Rakesh",67)

print(p1.name)
print(p1.age)

Output: Rakesh
67

Note: The __init__() function is called automatically every time the class is
being used to create a new object.

Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
Let us create a method in the Person class:
Example
Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.display()

The self Parameter


The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be
the first parameter of any function in the class:

Example
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Example-2:

class Person:
def input(self): # input objects value
name=input("Enter a name ")
age=int(input("Enter an age "))
self.name=name
self.age=age

def display(self): # display objects value


print("Your name is ",self.name)
print("Your age is ",self.age)
p1=Person()
p1.input()
p1.display()

Modify Object Properties


You can modify properties on objects like this:
Example
Set the age of p1 to 40:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)

p1.age = 40

print(p1.age)
p1.myfunc()

The pass Statement


class definitions cannot be empty, but if you for some reason have a class definition
with no content, put in the pass statement to avoid getting an error.
Example
class Person:
pass

Python Exercise
1) #Swap a list first and last element of the list.
class no:
def swap(self,n):
size=len(n)
temp=n[0]
n[0]=n[size-1]
n[size-1]=temp
return n

p=no()
list1=[10,90,40,70,30]
print("Original list ",list1)
p.swap(list1)
print("Interchanged firstg and last element ",list1)

#Pyramid print
alpha=65
n=26
for i in range(0,n):
print(" "*(n-i),end="")
for j in range(0,i+1):
print(chr(alpha),end=" ")
alpha+=1
print()
alpha=65
Output:

A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ
ABCDEFGHIJK
ABCDEFGHIJKL
ABCDEFGHIJKLM
ABCDEFGHIJKLMN
ABCDEFGHIJKLMNO
ABCDEFGHIJKLMNOP
ABCDEFGHIJKLMNOPQ
ABCDEFGHIJKLMNOPQR
ABCDEFGHIJKLMNOPQRS
ABCDEFGHIJKLMNOPQRST
ABCDEFGHIJKLMNOPQRSTU
ABCDEFGHIJKLMNOPQRSTUV
ABCDEFGHIJKLMNOPQRSTUVW
ABCDEFGHIJKLMNOPQRSTUVWX
ABCDEFGHIJKLMNOPQRSTUVWXY
ABCDEFGHIJKLMNOPQRSTUVWXYZ

#Reverse Pyramid
n=int(input("Enter a range "))
for i in range(n,0,-1):
for j in range(n-i):
print(" ",end="")
for k in range(2*i-1):
print("*",end="")
print()
Output:
*********
*******
*****
***
*

Inheritance

Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties
from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:

Example
Create a class named Person, with firstname and lastname properties, and
a printname method:

#Example of Python Inheritance


class Person: # Parent class
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

class Student(Person): # Child class Student inherit Parent class Person


pass

a=Person("Harish","Gupta")
a.printname()

x = Student("Mike", "Olsen")
x.printname()

#Example of Inheritance
class Animal:
def __init__(self,name,habit):
self.name=name
self.habit=habit
def display(self):
print(self.name,self.habit)

class Mamal(Animal):
def __init__(self,name,habit):
super().__init__(name,habit)
def input(self):
nm=input("Enter a animal name ")
age=int(input("Enter its age "))
self.nm=nm
self.age=age
def printname(self):
print(self.nm,self.age)

obj=Animal("Tiger","Ferocious")
obj.display()

obj1=Mamal("Dog","Domestic")
obj1.display()
obj1.input()
obj1.printname()

Python Turtle

1) # Python program to draw square


# using Turtle Programming

import turtle

x = turtle.Turtle()

for i in range(4):

x.forward(50)

x.right(90)
turtle.done()

2) # Python program to draw star


# using Turtle Programming

import turtle

star = turtle.Turtle()

star.right(75)

star.forward(100)

for i in range(4):

star.right(144)

star.forward(100)

turtle.done()

3) Python program to draw Circle with fill color


import turtle

x=turtle.Turtle()

s=turtle.Screen()

s.bgcolor("white")

x.fillcolor("red")

x.begin_fill()

x.circle(100)

x.end_fill()

x.hideturtle()

turtle.done()
4) Python program to draw Square
import turtle #Inside_Out

wn = turtle.Screen()

wn.bgcolor("light green")

skk = turtle.Turtle()

skk.color("blue")

def sqrfunc(size):

for i in range(4):

skk.fd(size)

skk.left(90)

size = size + 5

sqrfunc(6)

sqrfunc(26)

sqrfunc(46)

sqrfunc(66)

sqrfunc(86)

sqrfunc(106)

sqrfunc(126)

sqrfunc(146)

5) # Python program to draw Spiral Helix Pattern using Turtle


Programming

import turtle
loadWindow = turtle.Screen()

turtle.speed(2)

for i in range(100):

turtle.circle(5*i)

turtle.circle(-5*i)

turtle.left(i)

turtle.exitonclick()

6) # Python program to draw Rainbow Benzene using Turtle


Programming
import turtle

colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']

t = turtle.Pen()

turtle.bgcolor('black')

for x in range(360):

t.pencolor(colors[x%6])

t.width(x//100 + 1)

t.forward(x)

t.left(59)

Polymorphism

Python Polymorphism

The word "polymorphism" means "many forms", and in programming it refers to


methods/functions/operators with the same name that can be executed on many
objects or classes.
Function Polymorphism

An example of a Python function that can be used on different objects is


the len() function.

String :

For strings len() returns the number of characters:

Example:

x = "Hello World!"

print(len(x))

Tuple :

For tuples len() returns the number of items in the tuple:

Example

mytuple = ("apple", "banana", "cherry")

print(len(mytuple))

Dictionary :

For dictionaries len() returns the number of key/value pairs in the dictionary:

Example

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

print(len(thisdict))

Class Polymorphism
Polymorphism is often used in Class methods, where we can have multiple classes with
the same method name.

For example, say we have three classes: Car, Boat, and Plane, and they all have a
method called move():

Example:
Different classes with the same method:
#Example of polymorphism

class Car:

def __init__(self,brand,name):

self.brand=brand

self.name=name

def move(self):

print("Drive : ",self.brand,self.name)

class Boat:

def __init__(self,brand,name):

self.brand=brand

self.name=name

def move(self):

print("Sail : ",self.brand,self.name)

class Plane:

def __init__(self,brand,name):

self.brand=brand

self.name=name

def move(self):

print("Plane : ",self.brand,self.name)

Car1=Car("Ford, ","Mustang")

Boat1=Boat("Sailing Boat, ","Ship")

Plane1=Plane("Boeing, ","Air India")


for x in (Car1,Boat1,Plane1):

x.move()

Inheritance Class Polymorphism


What about classes with child classes with the same name? Can we use polymorphism
there?

Yes. If we use the example above and make a parent class called Vehicle, and
make Car, Boat, Plane child classes of Vehicle, the child classes inherits
the Vehicle methods, but can override them:

Example

Create a class called Vehicle and make Car, Boat, Plane child classes of Vehicle:

Example :

#Example of Inheritance Class Polymorphism

class Vehical:

def __init__(self,brand,name):

self.brand=brand

self.name=name

def move(self):

print("Move : ")

class Car(Vehical):

def move(self):

print("Drive : ",end="")

class Boat(Vehical):

def move(self):

print("Sail : ",end="")

class Plane(Vehical):

def move(self):
print("Plane : ",end="")

Car1=Car("Ford, ","Mustang")

Boat1=Boat("Sailing Boat, ","Ship")

Plane1=Plane("Boeing, ","Air India")

for x in (Car1,Boat1,Plane1):

x.move()

print(x.brand,end="")

print(x.name)

Module

Python Modules
What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file extension .py:

Example:

Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the


syntax: module_name.function_name.

Step1: Save the file Largest.py

def check(n,m):

if n>m:

return n

else:

return m

result=check(0,0)

Step 2: Open Python editor and write the following code

import Largest

print("Largest number is ",Largest.check(100,500))

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Note : Above program you can re-naming like below:

import Largest as big

print("Big one is ",big.check(555,222))

Import From Module


You can choose to import only parts from a module, by using the from keyword.

Example:

def Addition(n,m):
return n+m

def Subtraction(n,m):

return n-m

def Multi(n,m):

return n*m

def Division(n,m):

return n-m

Now if you want to import only parts from module i.e., if you want to call
Addition/Subtraction/Multi/Division function from above module then:

import MyModule as mm

print(mm.Multi(n=50,m=100))

or

print(mm.Addition(50,100))

and so on.

Note: When importing using the from keyword, do not use the module name
when referring to elements in the module. Example:

mm.Addition(20,40)

mm.Division(100,5)

You might also like