Python Unit2
Python Unit2
Python Unit2
UNIT-II:
Flow control & Collections: If, If...else, if...elif...else,
Nested if, for loop, while loop, Break, Continue and Pass.
Numbers, Decimal, Fractions, Mathematics, List, Tuple,
String, Set and Dictionary. Data types manipulations
(create, Index, Negative indexing, Slicing, change or add
elements, delete or remove elements, Methods,
Comprehension, Membership Test, Iteration, Operations
and Built in Functions)
Learning Outcome: At the end of this Unit the student will be able to
• Implement Flow control statements required real world problems.
• Manipulate python programs by using the python data structures like lists,
dictionaries, tuples, strings and sets.
1. Conditional Statement:
What we can do by using conditional statement?
Ans: Using conditional statements, we can execute single statement or
multiple statements based on the condition.
2. if else:
<syntax>
if <condition>: #condition True – execute statement-1, skip else
statement-1 #condition False – skip stm-1, exe else stm-2
else:
statement-2
3. if elif
<syntax>
if <condition-1>:
Statement-1 is executed
elif <condition-2>:
Statement-2 is executed
elif <condition-3>:
Statement-3 is executed
else:
Statement-2 is executed
1. Write a python program to display list of even numbers and number of even numbers and sum
of even numbers within given range.
2. Write a python program to check given number is prime number or not.
What is prime number: A number which is divisible by 1 and itself is called as prime number.
3. Write a python program to print list of prime numbers upto given range.
4. Write a python program to print list of prime numbers upto given range in reverse order.
5. Write a python program to print odd numbers upto given range. In reverse order
Write a python program to display prime numbers in the range of 2-100
While loop:
Using while loop we can execute a set of statements as long as a condition.
While loop will execute as per given no of iterations after last iteration else part will execute.
If while loop is terminated by break then else part will not execute.
➢ Using break statement, we can stop the loop even if the while condition is true.
➢ Using continue statement, we can stop the current iteration and continue with the
next.
➢ Using else statement, we can run a block of code once when the condition is no longer
as true.
➢ Pass: Using pass we can pass from one block to another block.
Which we will use in functions.
while <condition>:
#logic
else:
#logic
Sum of even no and odd no program
The pop() method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (First in, Last out, FILO data structures). And if we have to empty the
whole list, we can use the clear() method.
Tuple:
A tuple in python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas we can change
the elements of a list.
Creating a tuple: A tuple is created by placing all the items (elements) inside
parentheses ( ), separated by commas. The parentheses are optional; however, it is
a good practice to use them.
A tuple can have any number of items and they may be of different types (integers,
float, list, string, etc.,).
Having one element within parentheses is not enough. We will need a trailing
comma to indicate that it is, in fact, a tuple.
We can also use + operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using *
operator.
Both + and * operations result in a new tuple.
Advantages of Tuple over list:
Since tuples are quite similar to lists, both of them are used in similar situations.
However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages.
➢ We generally use tuples for different data types and lists for similar data
types.
➢ Since tuples are immutable, iterating through a tuple is faster than with list.
So there is a slight performance boost.
➢ Tuples that contain immutable elements can be used as a key for a dictionary.
With lists, this is not possible.
➢ If you have data that doesn’t change, implementing it as tuple will guarantee
that it remains write-protected.
Python Dictionary:
Python Dictionary is ordered collection of items. Each item of a dictionary has a
key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary:
Creating a dictionary is as simple as placing items inside curly braces { } separated
by commas.
An item has a key and a corresponding value that is expressed as a pair (key:value).
While the values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.
Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
Method Description
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is
not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the
dictionary is empty.
setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the
key with a value of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing
keys.
Sets:
A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces { }, separated by comma,
or by using the built-in-set ( ) function.
It can have any number of items and they may of different types (integer, float, tuple, string etc.).
But a set cannot have mutable elements like lists, sets, or dictionaries as its elements.
Python Set operations:
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member. (Do nothing if the element is
not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element. Raises KeyError if the set is empty
remove() Removes an element from the set. If the element is not a member, raises a KeyError
symmetric_difference() : Returns the symmetric difference of two sets as a new set
symmetric_difference_update() : Updates a set with the symmetric difference of itself and another
union() Returns the union of sets in a new set,
Updates the set with the union of itself and others
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used
with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as
a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
sum() Returns the sum of all elements in the set.
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(),
issuperset(), symmetric_difference() and union(). Being immutable, it does not have methods that
add or remove elements.
Strings in Python:
A string is a sequence of characters. A character is simply a symbol. For example, the English
language has 26 characters.
Computers don’t not deal with characters; they deal with numbers(binary). Even though you may
see character on your screen, internally it is stored and manipulated as a combination of 0s and
1s.
This conversion of character to a number is called encoding, and the reverse process is decoding.
ASCII and Unicode are some of the popular encodings used.
In python, a string is a sequence of Unicode characters. Unicode was introduced to include every
character in all languages and bring uniformity in encoding. You can learn about Unicode from
python Unicode.
How to create a string in python:
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple
quotes can be used in Python but generally used to represent multiline strings and docstrings.
Python Decimal
In Python, numbers that contain decimal points are always treated as double-precision floating-
point numbers. Decimal points have a smaller range than floats, but more precision.
Decimal modules have a precision that can be adjusted to any size necessary for a given problem,
unlike hardware-based binary floating points. By default, precision is set to 28 places. There are
some values that cannot be accurately represented by the float data type. If the 0.1 value is stored
in a float variable (binary floating-point value), we get only an approximation. In the same
way, 1/3 cannot be exactly represented in a decimal floating point.
Importing the Decimal class from the decimal module is the first statement. Next, we create two
variables called "i" and "j", each containing some values. A value is stored in the variable "k" when
i and j are divided by each other. Once the numbers have been converted to decimal types, the
process is repeated.
A round( ) function returns a floating point number with the specified number of decimals as
a rounded version of the original number. In the default case, the function returns the nearest
integer, since the number of decimals is 0.
Rounding Description
ROUND_CEILING This will round towards Infinity
ROUND_DOWN This rounds the value towards zero
ROUND_FLOOR This will round towards Infinity
ROUND_HALF_DOWN This will round to the nearest value going towards zero
ROUND_HALF_EVEN The value is rounded to the nearest even integer
ROUND_HALF_UP This will round to nearest value going away from zero
ROUND_UP This will round values away from zero
Whenever the last number is either zero or five, the number is
ROUND_05UP
rounded away from zero
Important Function in Python Decimal Module
a. exp() Function
It's pretty straightforward to follow the code sample. Numbers are rounded off with a precision
of two digits. Changing the rounding method is done via the "rounding" object (part of the
main context).
The exp() function is used to calculate the exponent value of a decimal point number, e.g. x^2
b. sqrt() Function
Sqrt() is a function that calculates and returns the square root value of the decimal number that
has been passed to it.
Syntax: decimal.Decimal(decimal-number).sqrt()
The "compare" method in the decimal module allows you to compare two
decimal-type objects. Its usage is illustrated in the following examples.
In order to compare two decimal-type objects, you must supply the other number as
an argument. Depending on the numbers being compared, a value of 0, 1, or -1 will be
returned. If the value is 0, both numbers are equal, if it is 1, the first number is greater
than the second, and if it is -1, the first number is less.
The logarithmic functions
There are some logarithmic functions in the Decimal module. Here we are
discussing about two of them. The first one is the ln() method. This method is
used to find the natural logarithm of the decimal number.
Another method is log10() method. This method is used to find the logarithmic
value where base is 10.
Example Code
#Perform ln() and log10() methods
import decimal
my_dec = decimal.Decimal(25.36)
print(my_dec)
#Find logarithmic value with base e
print('ln(x) is: ' + str(my_dec.ln()))
#Find logarithmic value with base 10
print('log(x) is: ' + str(my_dec.log10()))
Output
25.3599999999999994315658113919198513031005859375
ln(x) is: 3.233173129569025152000878282
log(x) is: 1.404149249209695070459909761
The fma() method is known as the fused multiplication and add. If we use fma(x,
y) It will compute the (number * x) + y. In this case the (number*x) part is not
rounded off.
Example Code
#Perform as_tuple() and fma() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show decimal as tuple
print('\nmy_dec1 as tuple: ' + str(my_dec1.as_tuple()))
print('\nmy_dec2 as tuple: ' + str(my_dec2.as_tuple()))
#Perform Fused Multiply and Add
print('\n(x*5)+8 is: ' + str(my_dec1.fma(5, 8)))
Output
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
Example Code
#Perform copy_abs(), copy_negate() and copy_sign()
import decimal
my_dec = decimal.Decimal(-25.36)
print(my_dec)
#copy the absolute value
temp_dec = my_dec.copy_abs()
print('Absolute is: ' + str(temp_dec))
#copy the negative value
my_dec = decimal.Decimal(7.26)
temp_dec = my_dec.copy_negate()
print('Negate of 7.26 is: ' + str(temp_dec))
#copy the sign value from second argument to first one
my_dec = decimal.Decimal(-25.36)
temp_dec = my_dec.copy_sign(decimal.Decimal(12.5))
print('Copy sign from second argument: ' + str(temp_dec))
Output
-25.3599999999999994315658113919198513031005859375
Absolute is: 25.3599999999999994315658113919198513031005859375
Negate of 7.26 is: -7.2599999999999997868371792719699442386627197265625
Copy sign from second argument:
25.3599999999999994315658113919198513031005859375
Example Code
#Perform max() and min() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show Minimum and Maximum
print('Minumum: ' + str(my_dec1.min(my_dec2)))
print('Maximum: ' + str(my_dec2.max(my_dec1)))
Output
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
Minumum: -9.230000000000000426325641456
Maximum: 5.299999999999999822364316060
Sources:
https://www.tutorialspoint.com/
https://www.geeksforgeeks.org/python-programming-language/
https://www.w3schools.com/python/