Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Chapter-5 XIC CS Python Introduction (1)

cs

Uploaded by

n73928957
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter-5 XIC CS Python Introduction (1)

cs

Uploaded by

n73928957
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Class XIC

CHAPTER-5
Name derived from famous BBC [Getting Started
comedy show namely Monty with Python]
Python‟s flying circus

Prepared by:
VIJAY CHAWLA, PGT CS,
PM SHRI KV PITAMPURA,
DELHI – 110034
 Python is widely used general purpose, high level programming
language.
 Python is a programming language that lets you work quickly
and integrate systems more effectively.
 Python was created by Guido Van Rossum
 The language was released in February I991
 Python got its name from a BBC comedy series from seventies-
“Monty Python‟s Flying Circus”
 Python can be used to follow both Procedural approach and
Object Oriented approach of programming
 It is OSS , free to use and can be freely downloaded from
www.python.org/downloads
 Easy to use Object oriented language
 Expressive language
 Interpreted Language
 Its completeness
 Cross-platform Language
 Fee and Open source
 Variety of Usage / Applications
• Python is compact and very easy to use object oriented
language with very simple syntax rules. It is a high level
language and very programmer-friendly.

• More capable to express code„s purpose than many


other language.

In C++ In Python
int a=2, b=3, tmp; a,b=2,3
tmp=a; a,b=b,a
a=b;
b=tmp; VINOD KUMAR VER MA, PGT(CS), KV OEF KANPUR &
• It is interpreted not compiled, thus executes code line by line
and it makes python easy-to-debug and suitable for beginners
and advanced users

• When you install Python, you get a lot of libraries installed by


default. All functionality is available with Python additional
library. Features like web-pages, database connectivity, GUI
features are available in Python standard library.
• Python can run equally well on variety of platforms – Windows,
Linux/UNIX, Macintosh, supercomputers.
• Python is portable language.

• It is feely available i.e. without any cost can be downloaded


from www.python.org.
• It is also open source i.e. you can modify, improve/extend an
open-source software
 Not the fastest language
 Lesser Libraries than C, C++, Java, Perl
 Not Strong on Type-binding
 Not Easily convertible
• Python is being used in many diverse
fields/applications, some of which are:
• Software Development
• Web Applications
• Game Development
• Scientific Computing
• System Administrations
• Scripting/Programming
• GUI Programs
• Database Applications
Installing Python

Two Steps Only –

1. Download Python distribution


2. Python installation process
Installing Python

1. Download Python distribution


Open the link
https://www.python.org/

Note – Download only that python distribution/MSI Installer, which is best suited for
the Operating system on which you want to install it.
Installing Python

1. Download Python distribution


Click on Downloads or directly open the link https://www.python.org/downloads/

Note – Download only that python distribution/MSI Installer, which is best suited for
the Operating system on which you want to install it.

Note that Python 3.9.0 cannot be used on Windows 7 or earlier.


Installing Python

2. Python installation process


1. Double-click the icon labeling the file <version>.exe
Popup window will appear
Installing Python

2. Setup popup window will appear


Installing Python

5. Soon, a new Python <version> Setup pop-up window will


appear with a Setup was successfully message

Click the close button


How to work in Python

PROCESS OF WRITING PROGRAM


After installation of python ,we can work on it in following ways

(i) in Interactive mode


(ii) in Script mode
After Python installation we can start working with python. In
Python we can work in 2 ways:

Interactive Mode
(Immediate
Python working Mode)
Ways
Script Mode
 Interactive modes – one command at a time
 Python executes the given command and gives the output.
 In interactive mode we type command at IDLE prompt ( >>> )
 For e.g if you type 20 + 30 in from of IDLE prompt
>>> 20 + 30 (command give by user)
50 (output given by python)
 From the above example you can see than at >>> we have to
just give the command to execute and python we execute it if it
is error free otherwise gives an error.
( )
( )
( )
( )

( )
print (“Hello”)
 Script Mode – multiple commands can be saved in a file as a
program and then we can execute the entire program
 we type Python program in a file and then use the interpreter
to execute the content from the file.
 Working in interactive mode is convenient for beginners and for
testing small pieces of code, as we can test them immediately.
But for coding more than few lines, we should always save our
code so that we may modify and reuse the code
 In Python IDLE :
 Click File  New
 In new window type the commands you want to save in program
 For example:
 print(“Hello World!”)

 FileSave to save file. Give extension .py to execute it as


python script
Save the
program
and press
F5
( )
Type the below code in script file:

#My First Program


print(“Hello World!”)

When you execute the script file output will be only


Hello World
Note: the first line starts from # which makes line as a
comment i.e. only for programmer information not for
interpreter. Comments are ignored by interpreter
To print or display output Python 3.x provides print() function.
Examples:-
print(“Welcome to Python”)
it will print Welcome to Python
print("Python rocks ! “ )
it will print Python rocks!
Note: Python allows both single quotation and double quotation
to enclose string. In any case both opening and closing must be
same.
print( “ Look carefully „ )
it will give error because both opening and closing
quotes are different.
Note:
1) Python is a case-sensitive language i.e. it will treat
small letter and capital letter as two different entities
like m & M will be treated differently in Python.
2) Single Line Comments in Python starts with # which is
ignored by Python Interpreter.
#This is my first program
#sample of basic statements
#print(“Watch out”)
print(“Hello World”)
print(“Python Rocks !!!!”)
(a) (b)
This is my first program sample of basic Watch out
statements Hello World
Watch out Python Rocks !!!!
Hello World
Python Rocks !!!!
(c)
(d)
Hello World
This is my first program
Python Rocks !!!! Hello World
Python Rocks !!!!
INPUT through input() function and
OUTPUT through print() statement
 To take input from the user, input() function is used. input() function
takes values in string data type.
Syntax of input Function
input()
 To print/display the contents on the console(monitor screen),
print() function is used.
Syntax of print Function
print(expression/variable)

NOTE:
Interactive mode
supports displaying of data ,
both with print() function
and also directly writing
the data (contents) on the
Python shell prompt >>>
NOTE: But, to display in Script mode , print() function is required to
display the data (contents), otherwise nothing is printed
More on INPUT through input() function and
OUTPUT through print() statement…….
# input () takes
string value by
default.

# But price
should be of
numeric value

#We can use


int() or float ()
function with
the input
function
Some more on input() and print()

sep and end parameters of print() function.


sep is the separator parameter which separates the strings given in print function.
The default separator (in the absence of sep) is a space ‘ ’.
end parameter denotes the end character to be given at the last of the print() functions
data/content.
Prog: WAP in Python to enter two numbers and display
the sum of these two.
#Program to add two numbers
num1=int(input(„Enter first number‟))
num2=int(input(„Enter Second Number‟))
sum=num1+num2
print(„The sum of to nos. is‟, sum)

Note: the first line starts from # which makes line as a


comment i.e. only for programmer information not for
interpreter. Comments are ignored by interpreter
TOKENS
Smallest individual unit in a program is called a token.
They are:

 K eywords
 I dentifiers
 Li terals
 P unctuators
 O perators
My funda of remembering Tokens: KILPO it’s just a shortcut given by me for remembrance ;)
TOKEN KEYWORDS
Keywords are the words that convey a special meaning to the
language compiler/interpreter. They are reserved for special
purpose and must not be used as normal identifier names.
and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda yield
except
TOKEN IDENTIFIERS
Identifiers are the fundamental building blocks of a program which
are used to identify a variable, function name, class name, module
name or any object.
RULES OF WRITING AN IDENTIFIER
 An identifier starts with a letter A to Z, a to z or an underscore ( _ ) followed by
zero or more letters, underscores and digits (0 to 9).
 Identifier name canNOT start with a digit.
 Python does NOT allow special characters other than underscore ( _ ).
 Identifier must NOT be a keyword of Python.
 Python is a case sensitive programming language that is uppercase letters
(capital letters) and lowercase letters (small letters) are treated differently.
Eg. Marks and marks are two different identifiers in Python.
• Some valid identifiers : Mymarks , file12 , tv9r , Avg_2 , _no

• Some invalid identifier : 4Qtr , global , XI-CS , E mail , %age

Starts with digit keyword


Special characters - (hyphen) space %
TOKEN LITERALS / values
Literals are data items that have a fixed value.
Python allows several kind of literals:
Numeric Literals
• Int (signed integers)  Positive or Negative
whole numbers with no decimal point Eg.
10, -96, 1234, 0
• Floating point/Real values  float represent
real numbers and are written with a decimal
point dividing the integer and fractional part.
Eg 2.0,54.7,-12.0,-0.075, .4
• Complex (complex numbers)  a+bj , where
a and b are floats and J(or j) represents √-1 ,
which is an imaginary number. a is the real
part and b is the imaginary part of the
number.
TOKEN LITERALS contd..

Boolean Literals
True and False are the only two Boolean
values

Special Literal None


None literal represents absence of a value.
That is why nothing is printed
for the value of b.
String Literal
String literal is a sequence of characters
surrounded by quotes (single or double or
triple)
String literals can be written in either single
quote ‘ ’ or double quote “ ”
TOKEN PUNCTUATORS
Punctuators are certain symbols which are used in
the programming languages to organize
programming sentence and structures, and indicate
the rhythm and emphasis of expressions, statements,
and program structure.

Most common punctuators of Python programming


language are:

‘ “ # \ ( ) [] {} @ , : . ` =
TOKEN OPERATORS
Operators are tokens that trigger some computation/ action when
applied to variables and other objects in an expression.
UNARY OPERATORS
- ~ Bitwise complement , not logical negation
Unary + , Unary ,

BINARY OPERATORS
ARITHMETIC OPERATORS: +,-,*,/,%,//,**
AUGMENTED ASSIGNMENT OPERATORS: = , +=,-=,*=,/=,%=,//=,**=
RELATIONAL OPERATORS: >,<,>=,<=,==,!=
LOGICAL OPERATORS: and , or, not
MEMBERSHIP OPERATORS: in, not in
IDENTITY OPERATORS: is, is not
BITWISE OPERATORS: &(Bitwise AND), ^(Bitwise XOR), |(Bitwise OR)
SHIFT OPERATORS: << (Shift Left) , >> (Shift Right)
DATA TYPES
The kind of data for handling the data used in a
program code is the data type.

CORE DATA TYPES

NUMBERS NONE SEQUENCES MAPPINGS

Floating Dictionary Sets


Integer Complex
Point

Boolean
Strings Tuple List
MUTABLE AND IMMUTABLE TYPES
• Mutable types:
The mutable types are those whose values can be
changed in place.
Only three types are mutable in Python.
These are: Lists, dictionaries and sets.

• Immutable types:
The immutable types are those that can never
change their value in place.
In python , the following are the immutable types:
Integers, floating point numbers, booleans, strings, tuples
DATA TYPE: Number in Python
It is used to store numeric values.

Python has three numeric types:

1. Integers
2. Floating point numbers
3. Complex numbers.
DATA TYPE: NUMBER  Integer
Integer or int are
positive or negative numbers
with no decimal point.
Integers in Python are of
unlimited size.
Type Conversion to Integer , int( ) function

int() function converts


any data type to
integer.
DATA TYPE: NUMBER  Float
Float are positive or
negative real numbers with
decimal point. Some Floating
point number examples:
4.5, 2.0, -38.9,-18.0

Type Conversion to Float ,


float( ) function
float() function converts any
data type to floating point
numbers.
DATA TYPE: Complex Number
• Complex numbers are combination of a real and imaginary part.
• Complex numbers are in the form of X+Yj
, where X is a real part and Y is imaginary part. We know, in
mathematics, j stands for √-1
• Using complex() function , we can also create complex numbers.
DATA TYPE: Boolean
• Boolean takes any two values, either True or False
• Every integer number, float number or complex number whether
negative or positive takes a Boolean value True.
• Value 0 , 0.0 , 0+0j are considered False in Boolean.
DATA TYPE: STRING
STRINGS in Python
in Python
A string is a sequence of characters. In python, we can create string
using single('') or double quotes(""). Both are same in python.
FORWARD INDEX DIRECTION
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
C omp u t e r S c i e n c e
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
BACKWARD INDEX DIRECTION

NOTE:-
The index (also called subscript) is the numbered position of a letter
in the string. In python, indices begin from
0,1,2,…. upto (length-1) in the forward direction and
-1,-2,-3,….. (-length) in the backward direction.
where length is the length of the string.
DATA TYPE: working with STRING examples
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
C omp u t e r S c i e n c e ! ! !
-19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
DATA TYPE: String contd..
Python allows to have two string types:
1) Single line strings (Basic strings)
Text enclosed in single quote ‘India’ or in double quotes “Bharat”
are normally single line strings i.e. they must terminate in one line.

2) Multiline strings
Text spread across multiple lines as one single string.
Two ways of treating multiline strings:-
(i) By adding a backslash at the (ii) By typing the text in triple quotation or
end of normal single apostrophe mark (No backslash
quote/double quote strings. needed at the end of line)
DATA TYPE: LIST in Python
A list in Python represents a list of comma-separated values of any data type
between square brackets e.g. following are some lists:
LIST is mutable- one can change/add/delete a list’s element)
FORWARD INDEX DIRECTION
0 1 2 3 4 5
10 20 30 40 50 60
-6 -5 -4 -3 -2 -1
BACKWARD INDEX DIRECTION
DATA TYPE: TUPLE in Python
Tuples are represented as list of comma-separated values of any data
type within parentheses. Some examples of tuples:
Tuple is immutable - one cannot change the values of a tuple.
FORWARD INDEX DIRECTION
0 1 2 3 4 5
10 20 30 40 50 60
-6 -5 -4 -3 -2 -1
BACKWARD INDEX DIRECTION
DATA TYPE: DICTIONARY in Python
Dictionary data type is an unordered set of comma-separated key: value
pairs, within { } , with the requirement that within a dictionary, no two keys can be
the same (i.e. there are unique keys within a dictionary). Some examples of Dictionary:
Value
D = { 10 : ' CS' , ' IP': 50 }
Key
CONCEPT OF VARIABLES
• Variable is a name (Named Labels)
given to a memory location that refers
to a value and whose values can be
used and processed during program
run.
NOTE:
• Python variables are created by
Here, marks, Name and
assigning value of desired data type to Item_price are the named labels
them. The assignment operator = is used (variables) with datatype inferred
to assign the values from RHS to LHS as Integer, String and Float for the
variable. Eg. Assign integer value to values 100, ‘Agni’, 999.90
create integer variable, string value to a respectively.
variable to create string variable.
• Python is a type infer language that
marks Name
means you don't need to specify the 100 ‘Agni’
datatype of variable. Python
automatically get variable datatype Item_price
depending upon the value assigned to
the variable. 999.90
ASSIGNING VALUES TO VARIABLES
• A Variable is not created until ASSIGNING SAME VALUE TO MULTIPLE
VARIABLES
some value is assigned to it.

ASSIGNING DIFFERENT VALUES TO


MULTIPLE VARIABLES

SWAPPING VARIABLES’
ASSIGNING VALUES TO VARIABLES ASSIGNING None VALUES
THROUGH AN EXPRESSION. VALUE (nothing) TO
A VARIABLE
L-VALUE and R-VALUE OF A VARIABLE
Lvalue: Expressions which Rvalue: Expressions which
can be given on the LHS(Left can come on the RHS(Right
Hand Side) of an assignment. hand side) of an assignment.
NOTE: In Python, assigning a value
to a variable means, variable’s
label is referring to that value
VARIABLE INTERNALS
VARIABLE
DATA
VALUE ID
TYPE
id of an object (Identity)
The id of an object is generally the memory location of the object. Although id is
implementation dependent but in most implementations it returns the memory
location of the object. id() is a built-in function that returns the id of an object.
Consider, the following code

marks marks
100
100 int 1852878304
UNARY OPERATORS
Unary + , Unary - , ~ Bitwise complement , not logical negation

BINARY OPERATORS
ARITHMETIC OPERATORS: +,-,*,/,%,//,**
AUGMENTED ASSIGNMENT OPERATORS: = , +=,-=,*=,/=,%=,//=,**=
RELATIONAL OPERATORS: >,<,>=,<=,==,!=
LOGICAL OPERATORS: and , or, not
MEMBERSHIP OPERATORS: in, not in
IDENTITY OPERATORS: is, is not
BITWISE OPERATORS: &(Bitwise AND), ^(Bitwise XOR), |(Bitwise OR)
SHIFT OPERATORS: << (Shift Left) , >> (Shift Right)
ARITHMETIC OPERATORS
1) BINARY OPERATOR: requires two A + B , where A and B
values(or operands) to calculate a final answer are Operands and + is the
SYMB BINARY DESCRIPTION Operator
OL OPERATOR
+ ADDITION returns sum of two values
Operator

- SUBTRACTION subtracts second operand from first operand


Operator

* MULTIPLICATION multiplies two values


Operator

/ DIVISION divides first operand by the second operand and


Operator always return a float value

% MODULO produces the remainder of dividing the first


Operator operand by the second operand

// FLOOR DIVISION divides the first operand with the second operand
Operator in which the whole part of the result is given in the
output , the fractional part is truncated

** EXPONENTIATION returns the no. raised to a power(exponent)


Operator
Augmented assignment operator
OPERATORS DESCRIPTION EXAMPLE EQUIVALENT
ASSIGNMENT

Assigns values from right side a=b a=b


= operands to left side operand.
Add 2 numbers and assigns the a=a+b a+=b
+= result to left operand.
Divides 2 numbers and assigns a=a/b a/=b
/= the result to left operand.
Multiply 2 numbers and assigns a=a*b a*=b
*= the result to left operand.
Subtracts 2 numbers and assigns a=a-b a-=b
-= the result to left operand
Here,
a*=b
Modulus 2 numbers and assigns a=a%b a%=b is equivalent to a=a*b
%= the result to left operand.
b-=c
Floor division on 2 numbers and a=a//b a//=b
//= assigns the result to left operand
is equivalent to b=b-c

Calculate power on operators and a=a**b a**=b c/=5


**= assigns the result to left operand is equivalent to c=c/5
RELATIONAL OPERATORS
 Relational Operators are used to compare the values of Left Hand
Side (LHS) and Right Hand Side (RHS) of the relational operator.
 Relational Operators always return Boolean value True or False
OPERATOR DESCRIPTION EXAMPLE
Equal to, A==B
== return True if LHS is equal to RHS of the operator
Not Equal to, A!=B
!= Returns True if LHS is not Equal to RHS
Greater than, A>B
> Returns True if LHS is greater than RHS
Greater than or Equal to, A>=B
>= Returns True if LHS is greater than or equal to RHS
Less than, A<B
< Returns True if LHS is less than RHS
Less than or Equal to, A<=B
<= Returns True if LHS is less than or equal to RHS

Here, A and B can be an expression or a variable.


Some examples of Relational Operator

NOTE: T of True and F of False is always in capital letters


IDENTITY OPERATOR ( is , is not)
Is, is not are the operators which compares two objects in terms of
their memory locations which is their corresponding identity (id)
OPERATORS DESCRIPTION EXAMPLE
It returns True, if two variables point to the
is P is Q
same object, else it returns false
It returns True, if two variables point to different
is not P is not Q
objects, else it returns false

P Q
int 10
1805363264

R
int 20
Here, P and Q can be an expression or a variable object. 1805363424
MEMBERSHIP OPERATOR
Membership operator tests for Membership in a sequence.
Returns Boolean True or False
OPERATOR DESCRIPTION
in Results to True value if it finds a variable at the LHS of in operator in the
sequence mentioned in the RHS of the in operator, else it returns False

not in Results to True value if it does not find a variable at the LHS of in operator in
the sequence mentioned in the RHS of the in operator, else it returns False

Program
written in
script
mode

Output
visible on
Interpreter
shell
LOGICAL OPERATORS
or , and , not
Logical operators are used to
perform logical operations on the
given two variables or values.
or operator
The or operator combines two expressions, which make its operands.
i) Relational expression as operands X Y
X Y
Tea or Coffee X Y X or Y
False False False
False True True
NOTE: If either Tea or Coffee is True False True
available at home, you can have X Y
it, hence True. If nothing available True True True
out of the two then, False

ii) Numbers / Strings / Lists as operands


In an expression X or Y , if first operand (i.e. expression X) has false, then return second
operand Y as result, otherwise return X.
X Y X or Y NOTE: Every integer
number, float number or
False False Y complex number whether
negative or positive takes
False True Y a Boolean value True.
Value 0 , 0.0 , 0+0j are
True False X considered False in
True True X Boolean.
and operator
The and operator combines two expressions, which make its operands.
i) Relational expression as operands X Y
X Y
Pen and Paper X Y X and Y
False False False
NOTE: To write something using pen False True False
and paper, you need both pen and
True False False
paper. Then only its True and you will X Y
be able to write. Otherwise, in absence True True True
of anyone out of the two will be False

ii) Numbers / strings / Lists as operands


In an expression X and Y , if first operand (i.e. expression X) has false, then return first
operand X as result, otherwise return Y.
X Y X and Y NOTE: Every integer
number, float number or
False False X complex number whether
negative or positive takes
False True X a Boolean value True.
True False Y Value 0 , 0.0 , 0+0j are
considered False in
True True Y Boolean.
not operator
 The logical not operator works on single Not(X)
expression or operand i.e. it is a unary operator. X
 Not operator negates or reverses the truth =Y
value of the expression.
True False
 A non-zero value is always true(1)
i.e. 5 , 24,-38 all are true value.
(1) (0)
 A zero (0, 0.0, 0+0j) is a false(0) value False True
 Empty string ‘’ is considered as False. (0) (1)
 A white space ‘ ’ is considered as True. X

Y
OPERATOR PRECEDENCE
Operator Description
** Exponentiation (raised to the power) Highest
~+- Complement unary plus and minus(method Priority
names for last two are +@ and -@)
*/%// Multiply, divide, modulo and floor division
+- Addition and Subtraction
>> << Right and left bitwise shift
& Bitwise ‘AND‘
^| Bitwise exclusive ‘OR' and regular ‘OR'
<= <> >= Comparison operators
< > == != Equality operators
= %= /= //= += ‘= “= Assignment operators
is , is not Identity operators
in , not in Membership operators Lowest
not , or , and Logical operators Priority
DATA TYPE
CONVERSIONS
The process of converting the value of one data
type (integer, string, float, etc.) to another
data type is called type conversion.

Python has two kinds of type conversion.


i) Implicit Type Conversion
ii) Explicit Type Conversion
IMPLICIT TYPE CONVERSION
In implicit type conversion, Python automatically
converts one data type to another data type.
This process doesn’t need any user involvement.
Eg.
EXPLICIT TYPE CONVERSION
In Explicit Type Conversion, user converts the data
type of an object to required data type. We use
the predefined functions like int(),float(),str() etc.
Eg.

Changing Data type of s from <str> type to <int> type


DATA HANDLING  WORKING WITH
MATH MODULE
Some mathematical functions in math module are:
Write this statement before using the
following functions in the math module.

FUNCTION Prototype Description


(General form)
math.sqrt(num) The sqrt() function returns
sqrt the square root of num.If
√25 = 5
num <0, domain error
occurs
math.pow The pow() function returns 24=16
pow (base, exp) this raised to exp power
i.e., base exp. A domain 2-4= 1
error occurs if base=0 and 16
exp<=0; also if base <0 and =0.0625
exp is not integer.
math.fabs(num) The fabs() functions returns
fabs the absolute value of num |18|=18.0
i.e. the magnitude of the |-18|=18.0
number without sign(+ or -)
FUNCTION Prototype Description Q) Find :
(General form) math.ceil(2.7) and
math.floor(num) The floor() math.floor(2.7)
floor functions
returns the
largest integer ceiling
value not
2.7
greater than floor
num
math.ceil(num) The ceil()
ceil functions
returns the
smallest
integer not less
than num.

HINT:
Imagine a room between the two integer points on
the y axis where the given value will lie.
ceiling
Now, the integer value which comes in the ceiling of
- 2.7
the room is the answer for ceil function . Similarly floor
integer value which comes in the floor of the room is
the answer for floor function.
FUNCTIO Prototype Description
N (General
form)
math.exp(arg) The exp() function
exp returns the natural
logarithm e raised to
the arg power
Value of e is 2.718
math.sin(arg) The sin() functions
sin returns the sine of
arg.the value of arg must
be in radians.
math.cos(arg) The cos() functions
Cos returns the cosine of
arg. The value of arg
must be in radians
math.tan(arg) The tan() function
tan returns the tangent of
arg. The value of arg
must be in radians.
FUNCTION Prototype Description
(General form)
math.log The log() function
log (num,[base]) returns the natural
logarithm for num. A
domain error occurs if
num is negative and a
range error occurs if the
argument num is zero.
math.log10(num) The log10() function
log10 returns the base 10
logarithm for num. A
domain error occurs if
num is negative and
range error occurs if the
argument is zero.
math.degrees(x) The degrees()
degrees converts angle x from
radians to degree

math.radians(x) The radians()


radians converts angle x from
degrees to radians
APPLICATION OF MATH MODULE FUNCTIONS IN
MATHEMATICAL EXPRESSIONS
Q) Write the corresponding Python Expressions from the
mathematical expressions:
i) ut+1/2 ft2
Ans. u*t+1/2*f*t*t
Alternative way

u*t+(1/2)*f*math.pow(t,2)

ii) |e2y-x|
Ans.
math.fabs(math.exp(2*y)-x)
TIME TO SOLVE…………… 
Q1) Give the output for the Q2) Write the corresponding
Python Expressions from the
print statements mathematical expressions:
import math
i) |a|+b >= |b|+a
a=math.pow(2,5)
print(a) ii)

print(math.sqrt(81))
print(math.ceil(12.8)) (iii) Cos(x) - 5x
Tan(x)
print(math.floor(12.8)
print(math.ceil(-38.5)) iv) p+ q
(r+s) 4
print(math.floor(-38.5))

You might also like