Pps Unit 2 Notes (Complete)
Pps Unit 2 Notes (Complete)
Pps Unit 2 Notes (Complete)
Python is a cross-platform programming language, which means that it can run on multiple
platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET
virtual machines. It is free and open-source.
Online Interpreter:
1. http://codepad.org/
2. https://replit.com/
IDE:
Thonny IDE: https://thonny.org/
The Thonny IDE comes with the latest version of Python bundled in it. So you don't have to
install Python separately.
InstallPython Separately:
Download the latest version from python.org.
1. Run Python in Immediate mode
Once Python is installed, typing python in the command line will invoke the interpreter in
immediate mode. We can directly type in Python code, and press Enter to get the output.
Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a
calculator. To exit this mode, type quit () and press enter.
2. Run Python in the Development Environment (IDE)Integrated
We can use any text editing software to write a Python script file.
We just need to save it with the .py extension. But using an IDE can make our life a lot
easier. IDE is a piece of software that provides useful features like code hinting, syntax
highlighting and checking, file explorers, etc. to the programmer for application
development.
By the way, when you install Python, an IDE named IDLE is also installed. You can use
it to run Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.
Now you can create a new file and save it with .py extension. For example, hello.py
Write Python code in the file and save it. To run the file, go to Run > Run Module or simply
click F5.
Your first Python Program
A simple program that displays “Hello, World!”. It's often used to illustrate the syntax of the
language.
Source Code
In this program, we have used the built-in print() function to print the string Hello, world! on
our screen.
a=5
print ('The value of a is', a)
Output
The value of a is 5
print (1, 2, 3, 4)
print (1, 2, 3, 4, sep='*')
print (1, 2, 3, 4, sep='#', end='&')
Output
1234
1*2*3*4
1#2#3#4&
The sep separator is used between the values. It defaults into a space character.After all
values are printed, end is printed. It defaults into a new line.
Python Input
To allow flexibility, we might want to take the input from the user. In Python, we have
the input () function to allow this. The syntax for input () is:
input ([prompt])
>>>int ('10')
10
>>>float ('10')
10.0
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str. format () method. This method is visible to any string object.
>>>x = 5; y = 10
>>>print ('The value of x is {} and y is {}’. format (x, y))
The value of x is5and y is10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
Output
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
We can also format strings like the old sprintf() style used in C programming language. We
use the % operator to accomplish this.
>>>x = 12.3456789
>>>print('The value of x is %3.2f' %x)
The value of x is12.35
>>>print('The value of x is %3.4f' %x)
The value of x is12.3457
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
The number of keywords can slightly vary from one version to another version of
python.
You can always get the list of keywords in your current version by typing the
following in the prompt.
>>>import keyword
>>>print(keyword.kwlist)
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore _. Names like myClass, and var_1 are valid
example.
An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid
name.
Keywords cannot be used as identifiers.
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
An identifier can be of any length.
Python Statement, Indentation and Comments
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement.
Multi-line statement
In Python, the end of a statement is marked by a newline character.
But we can make a statement extend over multiple lines with the line continuation
character (\).
For example:This is an explicit line continuation
a=1+2+3+\
4+5+6+\
7+8+9
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuationimplicitly. Same is the case
with [ ] and { }.
For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a
block of code. Python, however, uses indentation.
Generally, four whitespaces are used for indentation and are preferred over tabs.
The enforcement of indentation in Python makes the code look neat and clean. This results in
Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes
the code more readable. For example:
if True:
print('Hello')
a=5
and
ifTrue: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
Python Comments
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers to better understand a
program.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
We can have comments that extend up to multiple lines.
One way is to use the hash(#) symbol at the beginning of each line. For example:
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as a multi-
line comment as well.
"""This is also a
perfect example of
multi-line comments"""
number = 10
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
Note: In Python, we don't actually assign values to the variables. Instead, Python gives the
reference of the object(value) to the variable.
Assigning values to Variables in Python
website = "google.com"
print(website)
Output
google.com
In the above program, we assigned a value apple.com to the variable website. Then, we
printed out the value assigned to website i.e. google.com
website = "google.com"
print(website)
Output
google.com
microsoft.com
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "same"
print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables x, y and z.
Python Constants
A Python Constant is a variable whose value cannot be changed throughout the program.
Certain values are fixed and are universally proven to be true. These values cannot be changed
over time. Such types of values are called as Constants. We can think of Python Constants as a
bag full of fruits, but these fruits cannot be removed or changed with other fruits.
Note – Unlike other programming languages, Python does not contain any constants. Instead,
Python provides us a Capitalized naming convention method. Any variable written in the Upper
case is considered as a Constant in Python.
1. Python Constants and variable names should contain a combination of lowercase (a-z) or
capital (A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT = 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized when
declaring a constant.
5. We should come up with a catchy name for the python constants. VALUE, for example,
makes more sense than V. It simplifies the coding process.
Assigning Values to Constants
Constants are typically declared and assigned in a module in Python. In this case, the module is
a new file containing variables, functions, and so on that is imported into the main file.
Constants are written in all capital letters with underscores separating the words within the
module. We create a separate file for declaring constants. We then use this file to import the
constant module in the main.py file from the other file.
Python Literals
The data which is being assigned to the variables are called as Literal.
In Python, Literals are defined as raw data which is being assigned to the variables or
constants.
Let us understand this by looking at a simple example,
Here, we have declared a variable ‘str’, and the value assigned to it ‘How are you, Sam?’ is a
literal of type string.
Python supports various different types of Literals. Let us look at each one of them in
detail.
Numeric Literals
Numeric Literals are values assigned to the Variables or Constants which cannot be changed
i.e., they are immutable. There are a total of 3 categories in Numeric Literals. They are –
Integer, Float, and Complex.
Example
Output
To generate real and imaginary components of complex numbers, we utilize real literal (c.real)
and imaginary literal (c.imag), respectively.
String Literals
A string literal is a series of characters surrounded by quotation marks. For a string, we can use
single, double, or triple quotations. We can write multi-line strings or display them in the
desired format by using triple quotes. A single character surrounded by single or double
quotations is also known as a character literal.
Example
Output
Boolean Literals
A Boolean Literal has either of the 2 values – True or False. Where True is considered as 1 and
False is considered as 0.
Example
Output
True indicates a value of 1 in Python, while False represents a value of 0. Because 1 equals
True, the value of boolean1 is True. And as 1 does not equal False, the value of boolean2 is
False. Similarly, we can utilize True and False as values in numeric expressions.
Data Types, Expressions, Statements, and Control Flow: Introduction to
Python, statements, comments, keywords, variables, operators, data types,
type casting, Control Statements: If, If-else, nested If-else, break, continue,
pass, Looping Statements: range, while loop, for loop, nested loops, input and
output.
Data Types
Data Types
Example: “Welcome”
Example:
String1 = "Welcome"
print(type(String1)) # <class 'str'>
# display string
print(String1) # ' Welcome '
String1[1] = ‘q’
You can store positive and negative integer numbers of any length
such as 235, -758, 235689741.
You can also store integer values other than base 10 such as
Binary (base 2)
Octal (base 8)
Hexadecimal numbers (base 16)
# decimal int 16 with base 8
octal_num = 0o20
print(octal_num) # 16
print(hexadecimal_num) # 16
print(binary_num) # 16
# exponential float
num1 = 1.22e4
print(num1) # 12200.0
print(type(num1)) # class 'float'
Complex data type
A complex number is a number with a real and an imaginary
component represented as a+bj where a and b contain integers
or floating-point values.
print(x) # (9+8j)
print(y) # (10+4.5j)
print(z) # (11.2+1.2j)
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.
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:
List Length
To determine how many items a list has, use the len() function:
print(len(list1))
list2 = [1, 5, 7, 9, 3]
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
print(list1[-1])
Program:
# display list
print(my_list[0]) # 'xyz'
my_list[1] = "wwe"
print(my_list[1]) # 'wwe'
Example:
print(tuple1)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate
values.
Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example:
print(tuple1)
Tuple Length
To determine how many items a tuple has, use the len() function:
print(len(tuple1))
Create Tuple with One Item
To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as a tuple.
tuple1 = ("apple",)
print(type(tuple))
#NOT a tuple
tuple1 = ("apple")
print(type(tuple))
tuple2 = (1, 5, 7, 9, 3)
# create a tuple
print(my_tuple[2]) # 56
# slice a tuple
Tuple is immutable
# create a tuple
my_tuple[1] = 35
print(my_tuple)
In a dictionary, duplicate keys are not allowed, but the value can
be duplicated. If we try to insert a value with a duplicate key, the
old value will be replaced with the new value.
Program 1:
# create a dictionary
my_dict = {1: "arun", 2: "ravi", 3: "rohan"}
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
print(my_dict[1]) # ali
Program 2:
# Python program for demonstrating dictionaries.
my_dict = {"Name": "Tom", "Age": 50, "Movie": "Mission
Impossible"}
print(my_dict)
Output:
print(my_dict["Name"])
print(my_dict["Age"])
print(my_dict["Movie"])
Output:
Tom
50
Mission Impossible
Count Length
To determine how many items a dictionary has, use
the len() function:
print(len(my_dict))
Print(type(my_dict))
<class 'dict'>
my_set.add(300)
my_set.remove(100)
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them,
and cannot be referred to by index or key.
Unchangeable
Example
Duplicate values will be ignored:
my_set = {"apple", "banana", "cherry", "apple"}
print(my_set)
Note: The values True and 1 are considered the same value in sets,
and are treated as duplicates:
Output:
{True, 2, 'banana', 'cherry', 'apple'}
Note: The values False and 0 are considered the same value in sets,
and are treated as duplicates:
print(my_set)
Output:
{False, True, 'cherry', 'apple', 'banana'}
Length of a Set
print(len(my_set))
Data Types
print(set1)
print(set2)
print(set3)
type()
sets are defined as objects with the data type 'set':
print(type(my_set))
Frozenset
The frozenset data type is used to create the immutable Set. Once
we create a frozenset, then we can’t perform any changes on it.
# creating frozenset
f_set = frozenset(my_set)
print(type(f_set)) # class 'frozenset'
x = 25
y = 20
z=x>y
print(z) # True
print(type(z)) # class 'bool'
The bytes data type represents a group of byte numbers just like an
array.
We use the bytes() constructor to create bytes type, which also
returns a bytes object. Bytes are immutable (Cannot be changed).
Use bytes data type if we want to handle binary data like images,
videos, and audio files.
Example
Example:
a = [999, 314, 17, 11, 78] # Gives error range must be in 0 to 256
b = bytes(a)
print(type(b))
# ValueError: bytes must be in range(0, 256)
bytearray
The bytearray data type same as the bytes type except bytearray
mutable (we can modify its elements).
Example:
# create a bytearray
list1 = [9, 17, 11, 78]
b_array = bytearray(list1)
print(b_array)
print(type(b_array)) # class 'bytearray'
# modifying bytearray
b_array[1] = 99
print(b_array[1]) # 99
# iterate bytearray
for i in b_array:
print(i, end=" ") # 9 99 11 78
Example:
Example:
number = input("Enter roll number ")
name = input("Enter age ")
print("\n")
print('Roll number:', number, 'Name:', name)
print("Printing type of a input values")
print("type of number", type(number))
print("type of name", type(name))
Split input string using split() get the value of individual input.
Now, access list elements using a for loop and range() function.
number_list = []
n = int(input("Enter the list size "))
print("\n")
for i in range(0, n):
print("Enter number at index", i, )
item = int(input())
number_list.append(item)
print("User list is ", number_list)
If the user tries to enter multiline input, it reads only the first line.
Because whenever the user presses the enter key, the input function
reads information provided by the user and stops execution.
We can use a loop. In each iteration of the loop, we can get input
strings from the user and join them. You can also concatenate each
input string using the + operator separated by newline (\n).
Output in Python
Python has a built-in print() function to display output to the
standard output device like screen and console.
Example 1: Display output on screen
# take input
name = input("Enter Name: ")
# Display output
print('User Name:', name)
Example 2: Display Output by separating each value
Output Formatting
You can display output in various styles and formats using the
following functions.
str.format()
repr()
str.rjust(), str.ljust() , and str.center().
str.zfill()
The % operator can also use for output formatting
str.format(*args, **kwargs)
The str is the string on which the format method is called. It can
contain text or replacement fields delimited by braces {}.
Each replacement field contains either the numeric index of a
positional argument present in the format method or the name
of a keyword argument.
The format method returns a formatted string as an output. Each
replacement field gets replaced with the actual string value of the
corresponding argument present in the format method. i.e., args.
Example
print('FirstName - {0}, LastName - {1}'.format('Virat', 'Kohli'))
Note: Here {0} and {1} is the numeric index of a positional argument
present in the format method. i.e., {0} = Virat and {1} = Kohli.
Anything that not enclosed in braces {} is considered a plain literal
text.
Exercise
Exercise 1: Accept numbers from a user
Exercise 2: Display three string “Name”, “Is”, “James” as
“Name**Is**James”
Exercise 3: Convert Decimal number to octal using print() output
formatting
Exercise 4: Display float number with 2 decimal places using print()
Exercise 5: Accept a list of 5 float numbers as an input from the user
Exercise 6: Write all content of a given file into a new file by
skipping line number 5
Exercise 7: Accept any three string from one input() call
Exercise 8: Format variables using a string.format() method.
Exercise 9: Check file is empty or not
Exercise 10: Read line number 4 from the following file
Expected Output
Enter three string Virat Sachin Dhoni
Name1: Virat
Name2: Sachin
Name3: Dhoni
str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)
Given
totalMoney = 1000
quantity = 3
price = 450
Expected Output: I have 1000 dollars so I can buy 3 football for
450.00 dollars.
quantity = 3
totalMoney = 1000
price = 450
statement1 = "I have {1} dollars so I can buy {0} football for {2:.2f}
dollars."
print(statement1.format(quantity, totalMoney, price))
Control Flow Statements
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Conditional statements
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
If statement in Python
If the condition is True, then the True block of code will be executed,
and if the condition is False, then the block of code is skipped, and the
controller moves to the next line
Syntax
if condition:
statement 1
statement 2
statement n
Program
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
If – else statement
The if-else statement checks the condition and executes the if block
of code when the condition is True, and if the condition is False, it
will execute the else block of code.
Syntax
if condition:
statement 1
else:
statement 2
Program
password = input('Enter password ')
if password == "galgotias@#29":
print("Correct password")
else:
print("Incorrect Password")
Using for loop, we can iterate any sequence or iterable variable. The
sequence can be string, list, dictionary, set, or tuple.
Syntax of while-loop
while condition :
body of while loop
Example: Calculate the sum of first ten numbers.
num = 10
sum = 0
i=1
while i <= num:
sum = sum + i
i=i+1
print("Sum of first 10 number is:", sum)
The break statement is used inside the loop to exit out of the loop.
It is useful when we want to terminate the loop as soon as the
condition is fulfilled instead of doing the remaining iterations.
It reduces execution time. Whenever the controller encountered a
break statement, it comes out of that loop immediately.
Example of using a break statement
for num in range(10):
if num > 5:
print("stop processing.")
break
print(num)
Continue statement in python
Examples
The elif keyword is Python's way of saying "if the previous conditions
were not true, then try this condition".
Examples
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("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.
And
The and keyword is a logical operator, and is used to combine
conditional statements:
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine
conditional statements:
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the
result of the conditional statement:
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is
called nested if statements.
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
a = 33
b = 200
if b > a:
pass
Loop
While Loop
FOR LOOP
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Note: The for loop does not require an indexing variable to set
beforehand.
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the
"outer loop":
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Data Types
Data Types
Example: “Welcome”
Example:
String1 = "Welcome"
print(type(String1)) # <class 'str'>
# display string
print(String1) # ' Welcome '
String1[1] = ‘q’
You can store positive and negative integer numbers of any length
such as 235, -758, 235689741.
You can also store integer values other than base 10 such as
Binary (base 2)
Octal (base 8)
Hexadecimal numbers (base 16)
# decimal int 16 with base 8
octal_num = 0o20
print(octal_num) # 16
print(hexadecimal_num) # 16
print(binary_num) # 16
# exponential float
num1 = 1.22e4
print(num1) # 12200.0
print(type(num1)) # class 'float'
Complex data type
A complex number is a number with a real and an imaginary
component represented as a+bj where a and b contain integers
or floating-point values.
print(x) # (9+8j)
print(y) # (10+4.5j)
print(z) # (11.2+1.2j)
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.
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:
List Length
To determine how many items a list has, use the len() function:
print(len(list1))
list2 = [1, 5, 7, 9, 3]
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
print(list1[-1])
Program:
# display list
print(my_list[0]) # 'xyz'
my_list[1] = "wwe"
print(my_list[1]) # 'wwe'
Example:
print(tuple1)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate
values.
Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example:
print(tuple1)
Tuple Length
To determine how many items a tuple has, use the len() function:
print(len(tuple1))
Create Tuple with One Item
To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as a tuple.
tuple1 = ("apple",)
print(type(tuple))
#NOT a tuple
tuple1 = ("apple")
print(type(tuple))
tuple2 = (1, 5, 7, 9, 3)
# create a tuple
print(my_tuple[2]) # 56
# slice a tuple
Tuple is immutable
# create a tuple
my_tuple[1] = 35
print(my_tuple)
In a dictionary, duplicate keys are not allowed, but the value can
be duplicated. If we try to insert a value with a duplicate key, the
old value will be replaced with the new value.
Program 1:
# create a dictionary
my_dict = {1: "arun", 2: "ravi", 3: "rohan"}
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
print(my_dict[1]) # ali
Program 2:
# Python program for demonstrating dictionaries.
my_dict = {"Name": "Tom", "Age": 50, "Movie": "Mission
Impossible"}
print(my_dict)
Output:
print(my_dict["Name"])
print(my_dict["Age"])
print(my_dict["Movie"])
Output:
Tom
50
Mission Impossible
Count Length
To determine how many items a dictionary has, use
the len() function:
print(len(my_dict))
Print(type(my_dict))
<class 'dict'>
my_set.add(300)
my_set.remove(100)
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them,
and cannot be referred to by index or key.
Unchangeable
Example
Duplicate values will be ignored:
my_set = {"apple", "banana", "cherry", "apple"}
print(my_set)
Note: The values True and 1 are considered the same value in sets,
and are treated as duplicates:
Output:
{True, 2, 'banana', 'cherry', 'apple'}
Note: The values False and 0 are considered the same value in sets,
and are treated as duplicates:
print(my_set)
Output:
{False, True, 'cherry', 'apple', 'banana'}
Length of a Set
print(len(my_set))
Data Types
print(set1)
print(set2)
print(set3)
type()
sets are defined as objects with the data type 'set':
print(type(my_set))
Frozenset
The frozenset data type is used to create the immutable Set. Once
we create a frozenset, then we can’t perform any changes on it.
# creating frozenset
f_set = frozenset(my_set)
print(type(f_set)) # class 'frozenset'
x = 25
y = 20
z=x>y
print(z) # True
print(type(z)) # class 'bool'
The bytes data type represents a group of byte numbers just like an
array.
We use the bytes() constructor to create bytes type, which also
returns a bytes object. Bytes are immutable (Cannot be changed).
Use bytes data type if we want to handle binary data like images,
videos, and audio files.
Example
Example:
a = [999, 314, 17, 11, 78] # Gives error range must be in 0 to 256
b = bytes(a)
print(type(b))
# ValueError: bytes must be in range(0, 256)
bytearray
The bytearray data type same as the bytes type except bytearray
mutable (we can modify its elements).
Example:
# create a bytearray
list1 = [9, 17, 11, 78]
b_array = bytearray(list1)
print(b_array)
print(type(b_array)) # class 'bytearray'
# modifying bytearray
b_array[1] = 99
print(b_array[1]) # 99
# iterate bytearray
for i in b_array:
print(i, end=" ") # 9 99 11 78
Example:
x = 10
y=5
z=2
# != Not Equal to
print(x != y) # True
print(10 != x) # False
Assignment operators
In Python, Assignment operators are used to assigning value to the
variable. Assign operator is denoted by = symbol.
a=4
b=2
a += b
print(a) # 6
a=4
a -= 2
print(a) # 2
a=4
a *= 2
print(a) # 8
a=4
a /= 2
print(a) # 2.0
a=4
a **= 2
print(a) # 16
a=5
a %= 2
print(a) # 1
a=4
a //= 2
print(a) # 2
Logical operators
Logical operators are useful when checking a condition is true or not.
Python has three logical operators. All logical operator returns a boolean
value True or False depending on the condition in which it is used.
Logical and
# Logical and
if a > 0 and b > 0:
# both conditions are true
print(a * b)
else:
print("Do nothing")
Logical or
# Logical and
if a > 0 or b < 0:
# at least one expression is true so conditions is true
print(a + b) # 6
else:
print("Do nothing")
# Logical not
if not a:
# a is True so expression is False
print(a)
else:
print("Do nothing")
Membership operators
In operator
Not in operator
Program:
Use the Identity operator to check whether the value of two variables
is the same or not.
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:
is Operator:
Program 1: is operator
x = 10
y = 11
z = 10
print(x is y) # it compare memory address of x and y
print(x is z) # it compare memory address of x and z
Program 2: is operator
x = ["mango", "grapes"]
y = ["mango", "grapes"]
z=x
print(x is z)
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 between "is" and "==": this comparison
returns True because x is equal to y
is not Operator:
The is not the operator returns boolean values either True or False. It Return
True if the first value is not equal to the second value. Otherwise, it returns
False.
x = 10
y = 11
z = 10
print(x is not y) # it campare memory address of x and y
print(x is not z) # it campare memory address of x and z
Bitwise Operators
In Python, bitwise operators are used to performing bitwise operations on
integers. To perform bitwise, we first need to convert integer value to binary
(0 and 1) value.
The bitwise operator operates on values bit by bit, so it’s called bitwise. It
always returns the result in decimal format. Python has 6 bitwise operators
listed below.
Program:
a=7
b=4
c=5
print(a & b)
print(a & c)
print(b & c)
Bitwise “|”
It performs logical OR operation on the integer value after
converting integer value to binary value and gives the result a
decimal value.
Program:
a=7
b=4
c=5
print(a | b)
print(a | c)
print(b | c)
Integer Binary Value Operation Decimal Value
a=7 0111 a | b = 0111 7
b=4 0100 a | c = 0111 7
c=5 0101 b | c = 0101 5
Bitwise “^”
It performs Logical XOR ^ operation on the binary value of a integer
and gives the result as a decimal value.
Program:
a=7
b=4
c=5
print(a ^ b)
print(a ^ c)
print(b ^ c)
Program:
a=7
b=4
c=3
print(~a, ~b, ~c)
# Output -8 -5 -4
Integer Binary Value Operation Decimal Value
a=7 0111 ~a = 1000 -8
b=4 0100 ~b = 0101 -5
c=3 0011 ~c = 0100 -4
Example:
s = 12 = 1100
~s = ~1100
= -(1 + 1100)
= -(1101)
= -13
print(4 << 2)
# Output 16
print(5 << 3)
# Output 40
s = 12 = 0000 1100
s << 1 = 0001 1000 = 24
s << 2 = 0011 0000 = 48
Bitwise right-shift >>
The right-shift >> operator performs shifting a bit of value to the right
by a given number of places. Here some bits are lost.
print(4 >> 2)
# Output 1
print(5 >> 2)
# Output 1
s = 10 = 0000 1010
s >> 1 = 0000 0101 = 5
1. Write the pseudocode and draw a flow chart to calculate the
sum and product of two numbers and display it.
Algorithm:
Step 1: Start
Step 2: Input A, B
Step 3: Sum = A + B
Step 4: Product = A * B
Step 5: Print Sum, Product
Step 6: Stop
Pseudocode:
BEGIN
READ A, B
ADD sum = A + B
MUL mul = A * B
PRINT sum
PRINT mul
END
Flowchart:
Program:
a = int (input())
b = int (input())
Sum = a+b
Mul = a*b
print ("The sum and product of {} and {} is : ".format (a,b), Sum, " ", Mul)
Program 2: Write a Python program to calculate simple interest based on user input
for principal amount, rate, and time. Provide a clear explanation of the formula and
calculations.
p= int (input ("Enter principle amount = "))
r = int (input ("Enter rate of interest = "))
t = int (input ("Enter time in years = "))
simple_interest = int ((p*r*t)/100)
print ("Simple Interest is : ", simple_interest)
You should follow the following steps to determine whether a year is a leap year
or not.
def CheckLeap(Year):
# Checking if the given year is leap year
if((Year % 400 == 0) or
(Year % 100 != 0) and
(Year % 4 == 0)):
print("Given Year is a leap Year");
# Else it is not a leap year
else:
print ("Given Year is not a leap Year")
# Taking an input year from user
Year = int(input("Enter the number: "))
# Printing result
CheckLeap(Year)
Program: # Simple Python program to print the Simple pyramid pattern
1. n = int(input("Enter the number of rows"))
2. # Here, we are declaring the integer variable to store the input rows
3. # Here, we are declaring an outer loop to handle number of rows
4. for i in range(0, n):
5. # Here, we are declaring an inner loop to handle number of columns
6. # Here, the values are changing according to outer loop
7. for j in range(0, i + 1):
8. # Here, we are declaring a for loop for printing stars
9. print("* ", end="")
10. # Here, we are giving the ending line after each row
11. print()
Program: Write a program to check whether an alphabet entered by the user is a vowel or a constant.
Write a program to find all the prime numbers in a given range from the user.
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
else: