PP&DS 1
PP&DS 1
CONTENTS
• Introduction to python
• Applications of python
• IDEs
• Introduction to python interpreter
• Indentation and comments
• Keywords
• Variables – identifiers
• Built– in types
• Assigning values to variables
• Input and output statements
• Operators
• Control structures
• Math & random modules
• List
• Tuple
• Strings
• Set
• Dictionary
• Functions
• Files
• Libraries in python
INTRODUCTION TO PYTHON
1.WHY PYTHON ?
Because it's
• Easy
• Short
• High-level language(many features build-in or in libraries)
• Able to do many things (servers, ai, data analysis, raspberry pi,
gui, desktop apps, image/language processing, etc.)
• Great structured, making you able to write extremely complex
programs easy understandable and simple
• Object oriented and functional at the same time
• Extendable and able to work with many other technologies
• Much more…
2.DIFFERENCE BETWEEN C ,C++,JAVA AND PYTHON
3.FEATURES OF PYTHON
There are many features in Python, some of which are discussed below –
I. Easy to code:
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is
very easy to code in python language and anybody can learn python basics in a
few hours or days. It is also a developer-friendly language.
V. High-Level Language:
Python is a high-level language. When we write programs in python, we do not
need to remember the system architecture, nor do we need to manage the
memory.
APPLICATIONS OF PYTHON
3) Console-based Application
4) Software Development
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6) Business Applications
o Gstreamer
o Pyglet
o QT Phonon
8) 3D CAD Applications
9) Enterprise Applications
Python contains many libraries that are used to work with the
image. The image can be manipulated according to our
requirements. Some libraries of image processing are given
below.
o OpenCV
o Pillow
o SimpleITK
INTERPRETER
Interpreter is a program that converts the high level language into the
bit format i.e. machine language. The function of the interpreter and
compiler is the same but the interpreter translates one line at a time and
executes it. No object code is produced so every time when the program has
to be run it is to be interpreted first.
INDENTATION AND COMMENTS
INDENTATION
Most of the programming languages like C, C++, and Java use braces { } to
define a block of code. Python, however, uses indentation. A code block (body
of a function, loop, etc.) starts with indentation and ends with the first
unindented line. Generally, four whitespaces are used for indentation and are
preferred over tabs. Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
COMMENTS
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 """.
"""This is also a
perfect example of
multi-line comments"""
KEYWORDS
keywords are reserved words. The keywords Which cannot be used as the
function name, variable name, and any identifier name, etc. Each keyword
has a specific meaning. In Python, except True, False and None All
keywords are case sensitive
As elif if or yield
.
No. Keywords Descripti
on
VARIABLES – IDENTIFIERS
The identifier is a name used to identify a variable, function, class,
module, etc. The identifier is a combination of character digits and
underscore. The identifier should start with a character or Underscore then
use digit. The characters are A-Z or a-z,a UnderScore ( _ ) and digit (0-9). we
should not use special characters ( #, @, $, %, ! ) in identifiers.
Examples of valid identifiers:
1. var1
2. _var1
3. _1_var
4. var_1
Examples of invalid identifiers
1. !var1
2. 1var
3. 1_var
4. var#1
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
In Python, numeric data type represents the data which has numeric
value. Numeric value can be integer, floating number or even complex
numbers. These values are defined as int, float and complex class in
Python.
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
SEQUENCE TYPE
In Python, sequence is the ordered collection of similar or different
data types. Sequences allows to store multiple values in an organized and
efficient fashion. There are several sequence types in Python –
• String
• List
• Tuple
STRING
A string is a collection of one or more characters put in a single quote,
double-quote or triple quote. In python there is no character data type, a
character is a string of length one. It is represented by str class.
CREATING STRING
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
# Creating a String
print(String1)
# Creating a String
print(String1)
print(type(String1))
# Creating a String
print(String1)
print(type(String1))
String1 = '''All
Is
Well'''
print(String1)
Output:
S I D D A R T H A
0 1 2 3 4 5 6 7
8
-9 -8 -7 -6 -5 -4 -3 -2
-1
Output:
LIST
Lists are just like the arrays, declared in other languages which is an
ordered collection of data. It is very flexible as the items in a list do not need
to be of the same type.
CREATING LIST
Lists in Python can be created by just placing the sequence inside the square
brackets[ ].
# Creating a List
List = [ ]
print("Initial blank List: ")
print(List)
Computer
Engineering
Multi-Dimensional List:
Output:
TUPLE
Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e. tuples
cannot be modified after it is created. It is represented by tuple class.
CREATING TUPLE
In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data
sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.
Output:
# Python program to
# demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("Frist element of tuple")
print(tuple1[0])
# Accessing element from last
# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])
Output:
SEQUENCE TYPE
In Python, sequence is the ordered collection of similar or different
data types. Sequences allows to store multiple values in an organized and
efficient fashion. There are several sequence types in Python –
• String
• List
• Tuple
STRING
A string is a collection of one or more characters put in a single quote,
double-quote or triple quote. In python there is no character data type, a
character is a string of length one. It is represented by str class.
CREATING STRING
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
# Creation of String
# Creating a String
print(String1)
# Creating a String
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
print(String1)
print(type(String1))
String1 = '''All
Is
Well'''
print(String1)
Output:
S I D D A R T H A
0 1 2 3 4 5 6 7
8
-9 -8 -7 -6 -5 -4 -3 -2
-1
Output:
of the operator.
same string.
string.
[:] It is known as range slice operator. It is used to access the characters from t
specified range.
not in It is also a membership operator and does the exact reverse of in. It returns
r/R It is used to specify the raw string. Raw strings are used in the cases where
Consider the following example to understand the real use of Python operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
>>> c="133"
>>> print(c.isdigit())
True
Returns True if all >>> c = u"\u00B2"
Isdigit() characters in the string >>> print(c.isdigit())
are digits True
>>> a="1.23"
>>> print(a.isdigit())
False
>>> c="133"
>>> print(c.isidentifier())
False
>>> c="_user_123"
Returns True if the
isidentifier() >>> print(c.isidentifier())
string is an identifier
True
>>> c="Python"
>>> print(c.isidentifier())
True
>>> c="Python"
>>> print(c.islower())
False
Returns True if all
>>> c="_user_123"
Islower() characters in the string
>>> print(c.islower())
are lower case
True
>>> print(c.islower())
False
>>> c="133"
>>> print(c.isnumeric())
True
Returns True if all >>> c="_user_123"
Isnumeric() characters in the string >>> print(c.isnumeric())
are numeric False
>>> c="Python"
>>> print(c.isnumeric())
False
>>> c="133"
>>> print(c.isprintable())
True
Returns True if all >>> c="_user_123"
isprintable() characters in the string >>> print(c.isprintable())
are printable True
>>> c="\t"
>>> print(c.isprintable())
False
>>> c="133"
>>> print(c.isspace())
False
>>> c="Hello Python"
>>> print(c.isspace())
Returns True if all False
isspace() characters in the string 73
are whitespaces >>> c="Hello"
>>> print(c.isspace())
False
>>> c="\t"
>>> print(c.isspace())
True
>>> c="Python"
>>> print(c.isupper())
False
Returns True if all >>> c="PYHTON"
isupper() characters in the string >>> print(c.isupper())
are upper case True
>>> c="\t"
>>> print(c.isupper())
False
>>> a ="-"
>>> print(a.join("123"))
1-2-3
Joins the elements of >>> a="Hello Python"
join(iterable) an iterable to the end >>> a="**"
of the string >>> print(a.join("Hello
Python"))
H**e**l**l**o**
**P**y**t**h**o**n
>>> a="Hello"
Returns a left justified >>> b = a.ljust(12, "_")
ljust(width[,fillchar])
version of the string >>> print(b)
Hello_______
>>> a = "Python"
Converts a string into
lower() >>> print(a.lower())
lower case
Python
LIST
Lists are just like the arrays, declared in other languages which is an
ordered collection of data. It is very flexible as the items in a list do not need
to be of the same type.
CREATING LIST
Lists in Python can be created by just placing the sequence inside the square
brackets[ ].
# Creating a List
List = [ ]
print("Initial blank List: ")
print(List)
Output:
Intial blank List: [ ]
Computer
Engineering
Multi-Dimensional List:
Output:
TUPLE
Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e. tuples
cannot be modified after it is created. It is represented by tuple class.
CREATING TUPLE
In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data
sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'CSE')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
# Python program to
# demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("Frist element of tuple")
print(tuple1[0])
# Accessing element from last
# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])
Output:
Representation Differences
The representation of the Lists and tuple is marginally different. List are
commonly enclosed with the square bracket [ ], and elements are comma-
separated element. Tuples are enclosed with parenthesis (), and elements are
separated by the comma. The parenthesis is optional to use, and these types of
tuples are called tuple packing.
Output:
<class 'list'>
<class 'tuple'>
It is the most important difference between list and tuple whereas lists
are mutable, and tuples are immutable. The lists are mutable which means the
Python object can be modified after creation, whereas tuples can't be modified
after creation.
a = ["Computer","Science","And","Engineering"]
print(a)
Output: ["Computer","Science","And","Engineering"]
a[0] = "Python"
print(a)
Output: ['Python', 'Science', 'And', 'Engineering']
Output:
(10,20,"Siddartha",30,40)
a[0] = 50
Output:
We get an error while changing the 1st element of the tuple because of
immutability. It does not support item assignment.
BOOLEAN
Data type with one of the two built-in values, True or False. True and
False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an
error.
You can evaluate any expression in Python, and get one of two
answers, True or False.
When you compare two values, the expression is evaluated and Python returns
the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output:
True
False
False
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "<string>", line 3, in <module>
NameError: name 'true' is not defined
SET
Set is an unordered collection of data type that is iterable, mutable
and has no duplicate elements. The order of elements in a set is undefined
though it may consist of various elements.
CREATING SETS
Sets can be created by using the built-in set( ) function with an iterable
object or a sequence by placing the sequence inside curly braces, separated by
‘comma’. Type of elements in a set need not be the same, various mixed-up
data type values can also be passed to the set.
Output:
Output:
Initial set
{'Siddartha', 'For', 'CSE'}
Elements of set:
Siddartha For CSE True
>
DICTIONARY
Dictionary is an unordered collection of data values, used to store data
elements, Dictionary holds key:value pair. Each key-value pair in a Dictionary is
separated by a colon :, whereas each key is separated by a ‘comma’.
CREATING DICTIONARY
Dictionary can be created by placing a sequence of elements within
curly { } braces, separated by ‘comma’. Values in a dictionary can be of any
datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable. Dictionary can also be created by the built-in function dict( ). An
empty dictionary can be created by just placing it to curly braces{ }. Dictionary
keys are case sensitive, same name but different cases of Key will be treated
distinctly.
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Siddartha', 2: 'For', 3: 'CSE'}
print("\n Dictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Siddartha', 1: [1, 2, 3, 4]}
print("\n Dictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Siddartha', 2: 'For', 3:'CSE'})
print("\n Dictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'ANT'), (2, 'For')])
print("\n Dictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Siddartha', 2: 'For', 3: 'CSE'}
Dictionary with the use of Mixed Keys:
{'Name': 'Siddartha', 1: [1, 2, 3, 4]}
Dictionary with the use of dict():
{1: 'Siddartha', 2: 'For', 3: 'CSE'}
In order to access the items of a dictionary refer to its key name. Key can
be used inside square brackets. There is also a method called get( ) that will
also help in accessing the element from a dictionary.
Output:
Output:
Anand
3
10.0
>
Output: 0 0 0
We use the print( ) function to output data to the standard output device
(screen).
Example :
Output
a=5
print('The value of a is', a)
Output
The value of a is 5
Example
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&
OUTPUT FORMATTING
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
# OUTPUT: The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in
which they are printed by using numbers (tuple index).
Output
PYTHON INPUT
Example:
# Taking input from the user as integer
num = int(input("Enter a number: "))
add = num + 1
# Output
print(add)
Output:
Enter a number: 9
10
OPERATORS
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Relational operators /Comparison Operators
• Logical operators
• Bitwise operators
• Assignment Operators
• Special Operators/Identity Operators
• Membership Operators
1. ARITHMETIC OPERATORS:
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.
x **
** Power : Returns first raised to power second y
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
OUTPUT:
13
5
36
2.25
2
1
6561
2. RELATIONAL OPERATORS:
Relational operators compares the values. It either
returns True or False according to the condition.
< Less than: True if left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
3. LOGICAL OPERATORS:
# Print a or b is True
print(a or b)
Output:
False
True
False
4. BITWISE OPERATORS:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
| Bitwise OR x|y
~ Bitwise NOT ~x
OUTPUT:
0
14
-11
14
2
40
5. ASSIGNMENT OPERATORS:
Output:
8
2) Add and Assign: This operator is used to add the right side operand with the
left side operand and then assigning the result to the left operand.
Syntax:
x += y
Example:
a=3
b=5
#a=a+b
a += b
print(a)
Output: 8
3) Subtract and Assign: This operator is used to subtract the right operand
from the left operand and then assigning the result to the left operand.
Syntax:
x -= y
Example :
a=3
b=5
#a=a-b
a -= b
print(a)
Output:
-2
4) Multiply and Assign: This operator is used to multiply the right operand
with the left operand and then assigning the result to the left operand.
Syntax:
x *= y
Example:
a=3
b=5
#a=a*b
a *= b
print(a)
Output:
15
5) Divide and Assign: This operator is used to divide the left operand with the
right operand and then assigning the result to the left operand.
Syntax:
x /= y
Example:
a=3
b=5
#a=a/b
a /= b
print(a)
Output:
0.6
6) Modulus and Assign: This operator is used to take the modulus using the
left and the right operands and then assigning the result to the left operand.
Syntax:
x %= y
Example:
a=3
b=5
#a=a%b
a %= b
print(a)
Output:
3
7) Divide (floor) and Assign: This operator is used to divide the left operand
with the right operand and then assigning the result(floor) to the left operand.
Syntax:
x //= y
Example:
a=3
b=5
# a = a // b
a //= b
print(a)
Output:
0
8) Exponent and Assign: This operator is used to calculate the exponent(raise
power) value using operands and then assigning the result to the left operand.
Syntax:
x **= y
Example:
a=3
b=5
# a = a ** b
a **= b
print(a)
Output:
243
9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on
both operands and then assigning the result to the left operand.
Syntax:
x &= y
Example:
a=3
b=5
#a=a&b
a &= b
print(a)
Output:
1
10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the
operands and then assigning result to the left operand.
Syntax:
x |= y
Example:
a=3
b=5
#a=a|b
a |= b
print(a)
Output:
7
11) Bitwise XOR and Assign: This operator is used to perform Bitwise XOR on
the operands and then assigning result to the left operand.
Syntax:
x ^= y
Example:
a=3
b=5
#a=a^b
a ^= b
print(a)
Output:
6
12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise
right shift on the operands and then assigning result to the left operand.
Syntax:
x >>= y
Example:
a=3
b=5
# a = a >> b
a >>= b
print(a)
Output:
0
13) Bitwise Left Shift and Assign: This operator is used to perform Bitwise left
shift on the operands and then assigning result to the left operand.
Syntax:
x <<= y
Example:
a=3
b=5
# a = a << b
a <<= b
print(a)
Output:
96
6. SPECIAL OPERATORS:
‘is’ operator – Evaluates to true if the variables on either side of the operator
point to the same object and false otherwise.
Output:
true
‘is not’ operator – Evaluates to false if the variables on either side of the
operator point to the same object and true otherwise.
Output:
true
7. MEMBERSHIP OPERATORS
in and not in are the membership operators; used to test whether a
value or variable is in a sequence.
Output:
not overlapping
‘not in’ operator- Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise.
x = ["apple", "banana"]
print("pineapple" not in x)
Output: True
• for loop
• while loop
for loop:
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.
Syntax of for Loop
for x in variable:
print(x)
Example:
Output:
apple
banana
cherry
Example:
Output:The sum is 48
The range() function
Example:
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
Output:
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
for loop with else
A for loop can have an optional else block as well. The else part is
executed if the items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is
ignored.
Hence, a for loop's else part runs if no break occurs
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts.
When the for loop exhausts, it executes the block of code in the else and
prints No items left.
This for...else statement can be used with the break keyword to run
the else block only when the break keyword was not executed.
Example:
# program to display student's marks from record
student_name = 'Baldev'
marks = {'Anand': 90, 'Ram': 55, 'Bhavmanyu': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')
Output:
No entry with that name found.
Example:
Output:
List Iteration
Siddartha
for
CSE
Tuple Iteration
Computers
for
Engineers
String Iteration
B
h
a
v
m
a
n
y
u
Dictionary Iteration
xyz 123
abc 345
Example:
Output:
Bhavmanyu
Anand
Ram
Baldev
Pass statement
In Python, we use the pass statement to implement stubs.
When we need a particular loop, class, or function in our program,
but don’t know what goes in it, we place the pass statement in it.
It is a null statement. The interpreter does not ignore it, but it
performs a no-operation (NOP).
Example
for i in 'selfhelp':
pass
print(i)
Output:
P
Example:
Output:
Current Letter : M
Current Letter : h
Current Letter : b
Current Letter : h
Current Letter : r
Python programming language allows to use one loop inside another loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Example:
persons = [ "Ram", "Bhavmanyu", "Arjun", "Dev" ]
restaurants = [ "Japanese", "American", "Mexican", "French" ]
Output:
Ram eats Japanese
Ram eats American
Ram eats Mexican
Ram eats French
Bhavmanyu eats Japanese
Bhavmanyu eats American
Bhavmanyu eats Mexican
Bhavmanyu eats French
Arjun eats Japanese
Arjun eats American
Arjun eats Mexican
Arjun eats French
Dev eats Japanese
Dev eats American
Dev eats Mexican
Dev eats French
while loop:
Syntax :
while expression:
statement(s)
Example:
Output:
Hello World
Hello World
Hello World
Example:
i=1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
5
The break Statement
With the break statement we can stop the loop even if the while condition
is true:
Example:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
With the continue statement we can stop the current iteration, and continue
with the next:
Example:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
3
4
5
6
The else Statement
With the else statement we can run a block of code once when the
condition no longer is true:
Example:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output:
1
2
3
4
5
i is no longer less than 6
Math Modules
The math module is a standard module in Python and is always
available. To use mathematical functions under this module, you have to import
the module using import math.
All methods of these functions are used for integer or real type objects, not for
complex numbers.
To use math module, we should import that module into our code.
import math
Some Constants
These constants are used to put them into our calculations.
Pi constant:
Example:
# Import math Library
import math
# Print the value of pi
print (math.pi)
Output:
3.141592653589793
E constant:
Example:
# Import math Library
import math
# Print the value of Euler e
print (math.e)
Output:
2.718281828459045
Tau constant:
Example:
# Import math Library
import math
# Print the positive infinity
print (math.inf)
# Print the negative infinity
print (-math.inf)
Output:
inf
-inf
Nan constant:
nan
Numbers and Numeric Representation
These functions are used to represent numbers in different forms.
1 ceil(x) Return the Ceiling value.It is the smallest integer,greater or equal to the num
x.
5 floor(x) Return the Floor value. It is the largest integer, less or equal to the numbe
ceil() :
This function returns the smallest integral value greater than the number.
If number is already integer, same number is returned.
floor() :
This function returns the greatest integral value smaller than the number.
If number is already integer, same number is returned.
Example:
# Python code to demonstrate the working of
# ceil() and floor()
# importing "math" for mathematical operations
import math
a = 2.3
# returning the ceil of 2.3
print ("The ceil of 2.3 is : ", end="")
print (math.ceil(a))
factorial() :
This function returns the factorial of the number. An error message is
displayed if number is not integral.
Example:
# Python code to demonstrate the working of
# fabs() and factorial()
# importing "math" for mathematical operations
import math
a = -10
b= 5
# returning the absolute value.
print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))
copysign(a, b) :
This function returns the number with the value of ‘a’ but with the sign of ‘b’. The retu
value is float type.
gcd() :
This function is used to compute the greatest common divisor of 2 numbers mentione
arguments.
Example:
# Python code to demonstrate the working of
# copysign() and gcd()
# importing "math" for mathematical operations
import math
a = -10
b = 5.5
c = 15
d=5
# returning the copysigned value.
print ("The copysigned value of -10 and 5.5 is : ", end="")
print (math.copysign(5.5, -10))
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ", end="")
print (math.gcd(5,15))
Output:
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5
fsum(iterable) :
Find sum of the elements in an iterable object
Example:
# Import math Library
import math
# Print the sum of all items
print(math.fsum([1, 2, 3, 4, 5]))
print(math.fsum([100, 400, 340, 500]))
print(math.fsum([1.7, 0.3, 1.5, 4.5]))
Output:
15.0
1340.0
8.0
remainder(x, y)
Find remainder after dividing x by y.
Example:
# Import math Library
import math
# Return the remainder of x/y
print (math.remainder(9, 2))
print (math.remainder(9, 3))
print (math.remainder(18, 4))
Output:
1.0
0.0
2.0
Power and Logarithmic Functions
These functions are used to calculate different power related and logarithmic
related tasks.
4 log(x[, base]) Returns the Log of x, where base is given. The default base is e
exp(a) :
This function returns the value of e raised to the power a (e**a) .
log(a, b) :
This function returns the logarithmic value of a with base b. If base is not
mentioned, the computed value is of natural log.
EXAMPLE:
log10(a) :
This function computes value of log a with base 10.
Example:
# Python code to demonstrate the working of
# log2() and log10()
4 asin(x) This is the inverse operation of the sine, there are acos, atan also.
5 degrees(x) Convert angle x from radian to degrees
sin() :
This function returns the sine of value passed as argument. The value
passed in this function should be in radians.
cos() :
This function returns the cosine of value passed as argument. The value
passed in this function should be in radians.
Example:
# Python code to demonstrate the working of
# sin() and cos()
# importing "math" for mathematical operations
import math
a = math.pi/6
# returning the value of sine of pi/6
print ("The value of sine of pi/6 is : ", end="")
print (math.sin(a))
Example:
# Python code to demonstrate the working of
# tan()
# importing "math" for mathematical operations
import math
a = math.pi/6
b=3
c=4
# returning the value of tangent of pi/6
print ("The value of tangent of pi/6 is : ", end="")
print (math.tan(a))
Output:
The value of tangent of pi/6 is : 0.5773502691896257
degrees() :
This function is used to convert argument value from radians to degrees.
radians() :
This function is used to convert argument value from degrees to radians.
Example:
# Python code to demonstrate the working of
# degrees() and radians()
# importing "math" for mathematical operations
import math
a = math.pi/6
b = 30
# returning the converted value from radians to degrees
print ("The converted value from radians to degrees is : ", end="")
print (math.degrees(a))
Example:
# Python3 program to demonstrate the use of
# choice() method
# import random
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))
# prints a random item from the string
string = "Anand"
print(random.choice(string))
Output:
5
t
Example:
import random
random.seed()
print(random.random())
Output:
0.7051535963024892
shuffle():
It is used to shuffle a sequence (list). Shuffling means changing the
position of the elements of the sequence.
Example:
# import the random module
import random
# declare a list
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)
Output:
Original list :
['A', 'B', 'C', 'D', 'E']