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

Python Tutorials

The document provides an introduction to Python, covering its creation, uses, and advantages, such as its readability and versatility across platforms. It explains Python's syntax, variable creation, data types, and how to handle strings, including comments and slicing. Additionally, it discusses variable naming conventions and type conversion, emphasizing Python's dynamic typing and built-in functions.

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

Python Tutorials

The document provides an introduction to Python, covering its creation, uses, and advantages, such as its readability and versatility across platforms. It explains Python's syntax, variable creation, data types, and how to handle strings, including comments and slicing. Additionally, it discusses variable naming conventions and type conversion, emphasizing Python's dynamic typing and built-in functions.

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/ 90

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:
ExampleGet your own Python Server
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
Unpack a list:
fruits = ["apple", "banana", "cherry"]
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


ExampleGet your own Python Server

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: {'apple', 'google'}

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

You might also like