Python Unit2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

PYTHON PROGRAMMING

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.

In the above program when user entered second number as


zero it is throwing run time error… How to handle runtime
errors?
Ans: Two ways
1st way is: By using logic for this, we should go for control
statements
2nd way is: By using exception handling mechanism, with help of by
try, except, finally blocks…
Control Statements:
1. When we use control statements?
Ans: Control statements are used to control the program as per our requirement.
In python we have 3 types of control statements..
1. Conditional Statements
2. Loops
3. Transfer Statements

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.

Types of Conditional Statements:


In Python we have following conditional statements
1. Simple if
2. if else
3. if else if
4. multiple if
5. nested if..
1. Simple if:
<syntax>
if <condition>:
statement-1
statement-2
Example to handle divide by zero error program by using simple if:

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

Task1: Write a python program to accept a digit (0-5) display in letters….


Enter your Number: 5
You have entered number is: Five
1. Accept age from the user and display user status
age>=58 - senior citizen
age between 25-57 - working citizen
age between 16-24 - college student
age between 4-15 - school kid
age between 1-3 - playing kid
age other than range - invalid
2. Write a python program to accept alphabets and check it is vowel or not.
3. Write a python program to accept 3 subject marks i.e., calculate totmarks and avgmarks display
result:
Conditions: Fial – if he/she got < 35 in anyone subject
First class - if average >=60
Second class - if avgmarks between 50-59
Third class - if avgmarks between 35-49
What is the role of range() function?
range() function will do 3 responsibilities
1) It will initialize the starting range into given variable
2) It will compare ‘i’ value with ending range like i<6
If it is true it will go for iteration, otherwise it will skip
iteration.
3) After iteration is completed, it will increment the i value
one.
Write a python program to print 1 to 5 numbers like below.
o/p: 1 2 3 4 5
for i in range (1,6)
print (i,end= ‘ ‘)
Conditional statement within for loop:

Implementing if else or simple if or if elif or multiple if or nested if within for loop


is called as conditional statements within for loop.
Write a python program to print 1 to 10 numbers like below.
Out put:

Write a python program to print 1 to 10 numbers like below.


Out put:
Nested loop:
Implementing loop with in loop is called nested loop. That means implementing for loop within
for loop or while loop within while loop or while loop with in for loop or for loop within while
loop is called as nested loop.
Tutorial:

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

Write a python program to accept two numbers implement swapping.

Write a python program to accept a string and print in reverse order.


Write a python program to display Fibonacci series … upto given range.
Output: Enter ur no: 10
0112358
Python Lists: are one of the most versatile data types that allow us to
work with multiple elements at once. For example,
Python list is Mutable
In python, a list is created by placing elements inside square brackets [ ]
Access list elements:
There are various ways in which we can access the elements of list.
We can use the index operator [ ] to access an item in a list. In python, indices start at 0. So, a list
having 10 elements will have an index from 0 to 9.
Trying to access indexes other than these will raise an IndexError. The index must be an integer.
We can’t use float or other types, this will result TypeError.
Nested lists are accessed using nested indexing.
Note: When we slice lists, the start index is inclusive but the end index is exclusive. For example,
my_list [2:5] returns a list with element at index 2, 3 and 4, but not 5.
Add/change list elements
Lists are mutable, meaning their elements can be changed unlike string or tuple.
We can use the assignment operator = to change an item or a range of items.
Methods Descriptions
append() Adds an element to the end of the list
extend() Add all elements of a list to another list
insert() Inserts an item at the defined index
remove() Removes an item from the list
pop() Returns and removes an element at the given index
clear() Removes all items from the list.
index() Returns the index of the first matched item
count() Returns the count of the number of items passed as an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
copy() Returns a shallow copy of the list.

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.

Changing and adding dictionary elements:


Dictionaries are mutable. We can add new items or change the value of existing
items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is
not present, a new (key:value) pair is added to the dictionary.

Removing elements from dictionary:


We can remove a particular item in a dictionary by using the pop() method. This
method removes an item with the provided key and returns the value.
The popitem() method can bus used to remove and return an arbitrary (key,value)
item pair from the dictionary. All the items can be removed at once, using the clear()
method.
We can also use the del key word to remove individual items or the entire dictionary
itself.
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to
perform different tasks.

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.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries. (Not available in Python 3)

sorted() Return a new sorted list of keys in the dictionary.

Python Dictionary Methods


Methods that are available with a dictionary are tabulated below. Some of them have already been used
in the above examples.

Method Description

clear() Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.


fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to
None).

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.

keys() Returns a new object of the dictionary's keys.

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.

values() Returns a new object of the dictionary's values

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.

How to access characters in string?


We can access individual characters using indexing and a range of characters using slicing. Index
starts from 0. Trying to access a character out of index range will raise an IndexError. The index
must be an integer. We can’t use floats or other types; this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range
of items in a string by using the slicing operator : (colon).
Python String Operations
Concatenation of Two or More Strings
✓ Joining of two or more strings into a single one is called concatenation.
✓ The + operator does this in Python. Simply writing two string literals together also concatenates
them.
✓ The * operator can be used to repeat the string for a given number of times.
Iterating Through a string
We can iterate through a string using a for loop. Here is an example to count the number of 'l's in a string.

String Membership Test


We can test if a substring exists within a string or not, using the keyword in.
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
Built-in functions to Work with Python
Various built-in functions that work with sequence work with strings as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an
enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful
for iteration.
Similarly, len() returns the length (number of characters) of the string.
Python String Formatting
Escape Sequence
If we want to print a text like He said, "What's there?", we can neither use single quotes nor double quotes.
This will result in a SyntaxError as the text itself contains both single and double quotes.
>>> print("He said, "What's there?"")
SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
SyntaxError: invalid syntax
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to
represent a string, all the single quotes inside the string must be escaped. Similar is the case with double
quotes. Here is how it can be done to represent the above text.
# using triple quotes
print('''He said, "What's there?"''')
Output: He said, "What's there?"
# escaping single quotes
print('He said, "What\'s there?"')
Output: He said, "What's there?"
# escaping double quotes
print("He said, \"What's there?\"")
Output: He said, "What's there?"
Here is a list of all the escape sequences supported by Python.
Escape Sequence Description
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
Here are some examples
>>> print("C:\\Python32\\Lib")
O/P: C:\Python32\Lib
>>> print("This is printed\nin two lines")
This is printed
in two lines
>>> print("This is \x48\x45\x58 representation")
O/P: This is HEX representation
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in
front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.
>>> print("This is \x61 \ngood example")
This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example

The format() Method for Formatting Strings


The format() method that is available with the string object is very versatile and powerful in formatting
strings. Format strings contain curly braces { } as placeholders or replacement fields which get replaced.
We can use positional arguments or keyword arguments to specify the order.
# Python string format() method
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
--- Default Order ---
John, Bill and Sean
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)
--- Positional Order ---
Bill, John and Sean
# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
--- Keyword Order ---
Sean, Bill and John
The format() method can have optional format specifications. They are separated from the field name
using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.
We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the
exponent format. There are tons of formatting you can use. Visit here for all the string formatting available
with the format() method.
>>> # formatting integers
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'
>>> # formatting floats
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'
>>> # round off
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'
>>> # string alignment
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter | bread | ham|'
Old style formatting
We can even 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 is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Common Python String Methods
There are numerous methods available with the string object. The format() method that we mentioned
above is one of them. Some of the commonly used methods are lower(), upper(), join(), split(), find(),
replace() etc. Here is a complete list of all the built-in methods to work with strings in Python.
>>> "MecHaNIcaL".lower()
'mechanical'
>>> "MecHaNIcaL".upper()
'MECHANICAL'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'
Mathematics & Fractions in Python:

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.

Rounding off Numbers Using Python Decimal Module:

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.

In the Decimal module, rounding types are available, as shown below:

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 – Exponent calculation

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 as_tuple() and the fma() method


The as_tuple method is used to represent the decimal as a tuple
with three elements. The elements are sign, digits and the exponent value. In the
sign field when the number is 0, it means the decimal is positive, when it is 1, it
represents the negative number.

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

my_dec1 as tuple: DecimalTuple(sign=0, digits=(5, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 2, 2, 3,


6, 4,
3, 1, 6, 0, 5, 9, 9, 7, 4, 9, 5, 3, 5, 3, 2, 2, 1, 8, 9, 3, 3, 1, 0, 5, 4, 6, 8, 7, 5), exponent=-50)

my_dec2 as tuple: DecimalTuple(sign=1, digits=(9, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 2, 6, 3,


2, 5,
6, 4, 1, 4, 5, 6, 0, 6, 0, 1, 1, 1, 5, 2, 2, 6, 7, 4, 5, 6, 0, 5, 4, 6, 8, 7, 5), exponent=-48)

(x*5)+8 is: 34.49999999999999911182158030

Some copying functions


There are some different methods for copying decimal numbers into another
decimal object. The first method is copy_abs(). It is used to get the absolute
value from the decimal number. The second method is copy_negate(), It is used
to copy the decimal number after negating the actual number. The third function
is copy_sign(). this method prints the first argument, by taking the sign from the
second argument.

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

The max and min methods


The max and min are two simple methods. These are used to find the maximum
or minimum between two numbers respectively.

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/

You might also like