0% found this document useful (0 votes)
90 views24 pages

Understanding Python Tokens and Literals

The document provides an overview of Python tokens, including keywords, identifiers, literals, and operators, along with their definitions and examples. It explains how to use Python for mathematical calculations, including built-in functions and formatting outputs. Additionally, it discusses the use of Python as a scientific calculator and the importance of modules for various mathematical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views24 pages

Understanding Python Tokens and Literals

The document provides an overview of Python tokens, including keywords, identifiers, literals, and operators, along with their definitions and examples. It explains how to use Python for mathematical calculations, including built-in functions and formatting outputs. Additionally, it discusses the use of Python as a scientific calculator and the importance of modules for various mathematical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python tokens: These are smallest meaningful component in a program.

There are 4 types of tokens. i) Keywords, ii) Identifiers, iii) Literals and iv) Operators.

Keywords are some reserved words


which can’t be used freely as
name of variables, functions,
classes etc.

the orange words indicating that they can’t be used as variables and
the blacks are proofing that Python is case sensitive.
Identifiers: are name of variables, functions or objects. There are some rules
i) Variable’s name can’t carry any special characters except _(underscore)
ii)Identifiers are case sensitive.
iii)First letter can’t be a digit.

Literals in python: -
Generally, literals are a notation for representing a fixed value in source code. They can
also be defined as raw value or data given in variables or constants.
# Numeric literals Python has different types of
x = 24 literals.
y = 24.3
i. String literals
z = 2+3j
[Link] literals
print(x,y,z)
24 24.3 (2+3j) [Link] literals
Here 24, 24.3, 2+3j are considered as literals. [Link] Collections
v. Special literals
String literals
A string literal can be created by writing a text(a group of Characters ) surrounded
by the single(”), double(“”), or triple quotes. By using triple quotes we can write
multi-line strings or display in the desired way.
Character literal
Numeric literals
It is also a type of string literals where a
single character surrounded by single or double- They are immutable and there are three types of
quotes. numeric literal :
i. Integer
# character literal in single quote
v = 'n'
[Link]
# character literal in double quotes [Link].
w = "a"
print(v); n print(w);w Integer :
Both positive and negative numbers including 0.
There should not be any fractional part.
# Binary Literals; a = 0b10100 ;
# Decimal Literal; b = 50.0
# Octal Literal; c = 0o320 ;
# Hexadecimal Literal; d = 0x12b;
print(a, b, c, d) output 20 50 208 299
print(hex(255)) ;0xff. Float: These are real numbers having both integer and
print(bin(255)); 0b11111111. fractional parts.
print(oct(255)); 0o377. Complex Literal : The numerals will be in the form of a + bj,
print (0xff); 255;
where ‘a‘ is the real part and ‘b‘ is the complex part.
print(0o125) ; 85
print(0b1010101); 85
Boolean literals Literal Collections
There are only two Boolean literals in Python. They
re true and false. There are four different types of
a = (1 == True); b = (1 == False); c = True + 3; d = literal collections
False + 7
1. List literals; 2. Tuple literals;
print("a is", a); print("b is", b); print("c:", c);
3. Dict literals; 4. Set literals
print("d:", d)
Outputs List literals
a is True
List contains items of different
b is False
c: 4
data types. The values stored in
d: 7 List are separated by comma (,) and
In python, True represents the value enclosed within square brackets([]).
as 1 and False represents the value as 0. In the above We can store different types of data
example ‘a‘ is True and ‘b‘ is False because 1 equal to in a List. Lists are mutable.
True.
# List literals
x = (1 == True); y = (2 == False) ; z = (3 == True);
r = (1 == True); a = True + 10; b = False + 10
number = [1, 2, 3, 4, 5]
print("x is", x); print("y is", y); print("z is", name = ['Amit', 'kabir', 'bhaskar', 2]
z); print("z is", r); print("a:", a) ; print("b:", print(number) ; print(name) ;
b) Output
Output x is True; y is False ; z is False; z is [1, 2, 3, 4, 5] ; ['Amit', 'kabir', 'bhaskar', 2]
True; a: 11; b: 10
Tuple literals
A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and
each element is separated by the comma(,). It is immutable.
Tuple literals examples
even_number = (2, 4, 6, 8) ; odd_number = (1, 3, 5, 7) ; print(even_number) ; print(odd_number)
Output (2, 4, 6, 8); (1, 3, 5, 7)
Dictionary literals
Dictionary stores the data in the key-value pair. It is enclosed by curly-braces ‘{}‘ and each
pair is separated by the commas(,). We can store different types of data in a dictionary.
Dictionaries are mutable.
# Dict literals ; alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'} ; information = {'name':
'amit', 'age': 20, 'ID': 20}
print(alphabets) ; print(information) ;
Output ; {'a': 'apple', 'b': 'ball', 'c': 'cat'} ; {'name': 'amit', 'age': 20, 'ID': 20}
Set literals
Set is the collection of the unordered data set. It is enclosed by the {} and each element is
separated by the comma{ , }.
Example: we can create a set of vowels and fruits.
Now let us try to make a calculator using Python:

Calculating numbers and functions: -


 A function in Python is similar to a function on a calculator, in that you pass something
into the function, and the function passes something back.
For example, most calculators and programming languages have a square root function: You give it a number,
and it gives back the square root of that number.
 Python functions generally have the syntax: variablename = functioname(parameter,[parameter])
Because most functions return some value, you typically start by defining a variable to store
what the function returns.
 Follow that with an = sign and the function name, followed by a pair of parentheses.
Inside the parentheses you may pass one or more values (called parameters or arguments) to the
function.
For example, the abs() function accepts one number and returns the absolute value of that [Link] abs()
function simply converts negative numbers to positive numbers.
 Let us created a variable named x and assigned it the value -4. Then create a variable named
y and assigned it the absolute value of x using the abs() function. Printing x then shows its
value, -4, which hasn’t changed. Printing y shows 4, the absolute value of x as returned by
the abs () function.
Here is list of python3 built-in-function is given in a table.
Problem 1: A ball of mass 100g is thrown vertically upward with a speed 5 m/s.
1. Calculate the height at 0.2 second.
2. Find out the maximum height.
3. What is flight time?
4. Find speed at any time less than flight time.
5. What is the value of kinetic energy at a particular time?
𝟏 𝒖𝟐
To solve this problem, we can use the formula “𝒉 = 𝒖𝒕 − 𝟐 𝒈𝒕𝟐 for calculating height at any time, maximum height 𝑯 =
𝟐𝒈
𝟐𝒖 𝟏
, flight time T= , speed at any time t is v=(-u+g*t) and kinetic energy = 𝒎𝒗𝟐
𝒈 𝟐

u= 5m/s, g=9.8m/s2, and t = 0.2 s.

H1=5*5/(2*9.8) ('Maximum height attend by the body is',


v1=-5.0+9.8*0.2;v2=-5.0+9.8*1.2 1.2755102040816326, 'm')
T=2*5.0/9.8
KE1=0.5*0.1*v1**2;KE2=0.5*0.1*v2*v2 ('Flight time = ', 1.0204081632653061, 's')
print('Maximum height attend by the body is',H1,'m')
print('Flight time = ',T,'s') speed at 0.2 s is -3 m/s and at 1.2 s is 6.76 m/s
print('speed at 0.2 s is %.2g m/s and at 1.2 s is %.3g m/s respectively
respectively'%(v1,v2))
print('Kinetic Energy at time 0.2 s is ',KE1,' J and at 1.2 s is ',KE2,' J') ('Kinetic Energy at time 0.2 s is ',
0.46208000000000005, ' J and at 1.2 s is ',
2.2848800000000002, ' J')
Some other mathematical operations. Division
>>> 5/2 #float division; 5//2 # integer division; 10%4 # modulo division give remainder
2.5, 2, 2

We can format the output within any no. of decimal place with round of by using the command
‘round’ and any decimal no. can be truncated by using ‘Decimal’ importing from math or
decimal module.
But for a particular type of out-put we can use format command inside print.
We can print the values at different positions by mentioning the position inside { }, or
arranging the variables inside the format command.

Formatting the out-put: - Previously I have explained how python calculating the given
numbers and operations. Output for a float number have a large tail of decimal places. Some
time it is better to express the answer with rounding off.
Similarly, some time we should print the answer with its proper units and required some
arrangement to get output in a sequence. To do this type of job, with output is called
formatting.
Formatting the math operation output
Command on input Import math Operation or output
>>> int(9.81) 9
>>> float(9.81) 9.81
>>> abs(-9.81) 9.81
>>>abs(8+6j) 10.0
int(abs(-9.81)) 9
>>> complex(8,6) (8+6j)
>>>round(1.27551020408) 1
>>>round(1.275510204,3) 1.276
*>>> round(1.225,2) *1.23
*>>> round(1.255,2) *1.25
X= 12.123456789, 12.123; 12.12
‘{:.3f}’.format(x); {:.2f}'.format(x);
X=12.12345678 1.212E+01; 1.212e+01; 12.1
'{:.3E}'.format(x); '{:.3e}'.format(x); '{:.3g}'.format(x).

*The last output of round result showing 1.25 in the >>> import decimal
place of 1.26 and the reason is computer have saved >>> [Link](1.255)
the no. 1.255 as Decimal('1.2549999999999998934185896359
1.25499999999999989341858963598497211933135986328125
8497211933135986328125')
something like that. So, the no. behind 1.25 is 4
Now let us fix the anomaly
and the rounding off give 1.25, not 1.26.
>>> round([Link](1.255),2)
To check the actual value in computer memory, we
Decimal ('1.25')
should use
#and the anomaly is gone.
Print using formatting for Fancier Output
u=5.0; g=9.8; t=0.2; m=0.1 #now setting the values as variable
Or u,g,t,m=5.0,9.8,0.2,0.1 # we can feed values to variable by use coma only.
v=-u+g*t; H=(u**2)/(2*g); T=(2*u)/g; KE=(m*v**2)/2 # all formulie are written in terms of variable.
print('The speed of the object at %.2f s is %.3f m/s and Kinetic Energy %1.3g J'%(t,v,KE))
print('Maximum height attened by the body in {:.2} s is {:.3E} m and time of flight is{:.3e}'.format(t,H,T))
print('the speed at time {:.2f} s is {v} m/s '.format(t,v=-u+g*t)) #we can use the direct formula inside format command

The speed of the object at 0.20 s is -3.040 m/s and Kinetic Energy 0.462 J

Maximum height attened by the body in 0.2 s is 1.276E+00 m and time of flight is1.020e+00

the speed at time 0.20 s is -3.04 m/s

More different way of formatting


print('At time {t:0.2f} s and for initial velocity {u:0.2f} m/s, the height reached by the
object is {h:.3f} m'.format(t,u,h=-u*t+0.5*g*t**2)) # it gives error as input have different
sequencs than sequence used inside format command.
print(‘For initial velocity {1:0.2f} m/s at time {0:0.2f} s, the height reached by the object is
{h:.3f} m'.format(t,u,h=-u*t+0.5*g*t**2)) # give the correct result as index number of t and u inside
the tuple is placed correctly, as h is written as formula it has no place index.
For initial velocity 5.00 m/s at time 0.20 s, the height reached by the object is -0.804 m
Python as a Scientific calculator: -
We can use Python as a scientific calculator by finding power, square root, trigonometric
functions, logarithmic function, integration, differentiation, permutation, combination and
many other operations, commonly needed for a scientific calculator. To do the job we should
use import math function from math module.
Note: -
Python Modules: - Modules are organized Python codes. For example, if we want to calculate
square, cube or any trigonometric operation in any language, we have to write a programme
using some basic codes and operator, following a numerical rule and this is a good habit for
codding, but weight!!
It is not obvious to write a perfect programme and sometimes it become very laborious and
annoying for a very simple calculation. These problems are fixed in python, providing a vast
library containing huge numbers of programs as operators. You should know goal and choose the
operator to use for the task from a correct module. Mathematical operators belong to ‘math’
and ‘cmath’ modules. To use a programme, you have to call the particular operation using a
command like ‘import math’ for all programs inside it or for one or two or more particular
programs by using ‘from math import e, pi, sin, log’ etc. To know about the programs inside a
module by the given process-
To know about your directory (a collection) >>> help('modules')
>>> import math >>> import builtins
>>> dir(builtins)
>>> dir(math) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError',
['__doc__', '__loader__', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError',
'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'__name__', '__package__',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'__spec__', 'acos', 'acosh', 'asin',
'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt',
'asinh', 'atan', 'atan2', 'atanh', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
'ceil', 'comb', 'copysign', 'cos', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError',
'cosh', 'degrees', 'dist', 'e', 'erf', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'erfc', 'exp', 'expm1', 'fabs', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError',
'factorial', 'floor', 'fmod', 'frexp', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'fsum', 'gamma', 'gcd', 'hypot', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',
'inf', 'isclose', 'isfinite', 'isinf', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs',
'isnan', 'isqrt', 'lcm', 'ldexp', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex',
'lgamma', 'log', 'log10', 'log1p', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset',
'log2', 'modf', 'nan', 'nextafter', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals',
'perm', 'pi', 'pow', 'prod', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr',
'radians', 'remainder', 'sin', 'sinh', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
'sqrt', 'tan', 'tanh', 'tau', 'trunc',
'ulp'] >>> help('[Link]') #Help on built-in function comb in math:
[Link] = comb(n, k, /)
If we want to know the
Number of ways to choose k items from n items without repetition and without
function of a particular
order.
module, we have to use
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k >
help following the
n. Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in
module name.
polynomial expansion of the expression (1 + x)**n.
I listed up some commands (with proper title) in math module and their operations
Operation Command from math module
Square root of x, Return the integer square root of the [Link](x), [Link](n)
nonnegative integer n
[Link] = pow(x, y, /) [Link](x, y)
Return x**y (x to the power of y).
Combination [Link](n, k)
Return the base-10 logarithm of x. This is usually more accurate math.log10(x)
than log(x, 10).
Log x[base] [Link](x[, base])
Return the base-2 logarithm of x, This is usually more accurate math.log2(x)
than log(x, 2).
Return e raised to the power x [Link](x)
Return e raised to the power x, minus 1. exp(x) - 1 math.expm1(x)

Sin(x), Cos(x), Tan(x), [Link](x), [Link](x), [Link](x)

Sin-1(x), Cos-1(x), Tan-1(x) [Link](x), [Link](x), [Link](x)

Sinh(x), Cosh(x), Tanh(x), [Link](x), [Link](x), [Link](x)

Sinh-1(x), Cosh-1(x), Tanh-1(x), [Link](x), [Link](x), [Link](x)


Operation Command from math module
absolute value of x [Link](x)
x factorial as an integer [Link](x)
greatest common divisor [Link](a, b)
Return the fractional and integer parts of x. Both results carry the [Link](x)
sign of x and are floats.

Evaluates to n! / (n - k)! when k <= n & evaluates to zero when k > n [Link](n, k=None)

Return the Euclidean distance between two points p and q [Link](p, q)

Convert angle x from radians to degrees [Link](x)


Return the error function at x. [Link](x)

The mathematical constant e = 2.718281…, to available precision. math.e, [Link]


Tau is a circle constant equal to 2π, the ratio of a circle’s
circumference to its radius.
How to import any module and use some function inside a module?
import math
# import all functions inside a module. You can use any function by calling their proper name e.g.
[Link](x), [Link], [Link](x) etc. But to extra load of function, response time of python may be
increase. To avoid this type of problem we should use the command
from math import *
# To import all functions in the math module. This includes sin, cos, tan, asin,acos, atan,
sinh, cosh, tanh, exp, log (base e), log10 (base 10), sqrt, as well as the famous numbers e
and pi.
Importing all functions from a module,using the asterisk (*) syntax, is convenient, but this may result in
a lot of extra names in the program that are not used.
It is in general recommended not to import more functions than those that are really used in the program.
Nevertheless, the convenience of the compact from math import * syntax occasionally wins over the general
recommendation among practitioners.
With a from math import sqrt statement, we can write the formulas for the roots in a more pleasing way as
>>> import math >>> from math import *
>>>from math import sqrt
t2 = (v0 + sqrt(v0*v0 -2.0*g*h))/g >>> z=sin(pi/2)
>>> x=sin(pi/2)
where we can call the sqrt function by writing ‘sqrt’ Traceback (most recent call last):
not ‘[Link] >>> print(x)
Similarly “from math import *” support ‘sqrt’ not File "<stdin>", line 1, in <module>
‘[Link] NameError: name 'sin' is not defined 1.0
Example
import math
print('Square root of 50',[Link](50.0)) Square root of 50 7.0710678118654755
print('The integer square root of the nonnegative integer The integer square root of the nonnegative integer 50 7
50',[Link](50)) x(2) to the power of y(3) 8.0
print('x(2) to the power of y(3)',[Link](2,3)) Combination 5C2 10
print('Combination 5C2',[Link](5,2)) the base-10 logarithm of x 0.3010299956639812
print('the base-10 logarithm of x',math.log10(2)) Log x[base] 0.30102999566398114
print('Log x[base]',[Link](2,10)) base-2 logarithm of x 1.4426950408889634
print(‘base-2 logarithm of x',math.log2(math.e)) e to the power x 2.1932800507380152
print('e to the power x',[Link]([Link]/4)) sin of pi/4 0.7071067811865476 cos of pi/4
print('sin of pi/4',[Link]([Link]/4),' cos of pi/4 0.7071067811865476 tan of pi/4 0.9999999999999999
',[Link]([Link]/4),' tan of pi/4 ', [Link]([Link]/4)) Sin inverse(x) 0.785247163395153 cos inverse(x)
print('Sin inverse(x) ',[Link](0.707),' cos inverse(x) 0.7855491633997437 tan inverse(x) 0.7853981633974483
',[Link](0.707),' tan inverse(x) ', [Link](1)) x factorial as an integer 120
print('x factorial as an integer ',[Link](5)) greatest common divisor 5
print('greatest common divisor ',[Link](5,20,25)) Evaluates to n! / (n - k)! when k <= n & evaluates to zero when
print('Evaluates to n! / (n - k)! when k <= n & evaluates to zero k > n 20
when k > n ',[Link](5,2)) Evaluates to n! / (n - k)! when k <= n & evaluates to zero when
print('Evaluates to n! / (n - k)! when k <= n & evaluates to zero k>n 0
when k > n ',[Link](5,6)) Return the error function at x 0.997020533343667
print('Return the error function at x ',[Link](2.1)) Convert angle x from radians to degrees
print('Convert angle x from radians to degrees 0.009138522593601256
',[Link]([Link]/6))
Example : let us calculate the time to reach a given height by an object have initial speed v0.
>>> import math
>>> v0 = 5.0; h = 1.2; g = 9.81;t1 =(v0 - [Link](v0*v0 -2.0*g*h))/g
>>> print(t1); print('%.3f s'%(t1))
0.3866821355433365
0.387 s
>>> t2 = (v0 + [Link](v0*v0 -2.0*g*h))/g
>>> print('time to reach the height %0.3f s and %0.3f s'%(t1,t2))
time to reach the height 0.387 s and 0.633 s
>>> from math import sqrt
>>> t2 = (v0 + sqrt(v0*v0 -2.0*g*h))/g; t2
0.6326858563017195
>>> print ('time to reach the height %0.3f s and %0.3f s'%(t2,t1))
time to reach the height 0.633 s and 0.387 s
It is possible to rename any module and functions under the module as
>>> from math import sin as si,cos as co, log as ln,pi as p
>>> a=si(p/3)**2 + co(p/3)**2
1.0
In Python, everything is an object, and variables refer to objects, so new variables may refer to modules and functions as well as
numbers and strings. The examples above on new names can also be coded by introducing new variables explicitly:

Our next examples involve calling some more mathematical functions from the math module. We
look at the definition of the cosh(x) function:
1 𝑥
cosh 𝑥 = (𝑒 + 𝑒 −𝑥 )
2
We can evaluate cosh(x) in three ways:
i) by calling [Link],
ii) by computing the right-hand side of the equation using [Link], or
iii) by computing the right-hand side of equation with the aid of the power expressions
math.e**x and math.e**(-x).
>>> import math as m
>>> c1 = [Link]([Link])
>>> x=[Link]
>>> c2 = 0.5*([Link](x)+[Link](-x))
>>> c3 = 0.5*(m.e**x + m.e**(-x))
>>> print(c1, c2, c3)
11.591953275521519 11.591953275521519 11.591953275521517
Complex number and Complex arithmetic: (Use of cmath module)
Suppose x2 = 2. Then most of us are able to find out that x = √2 is a solution to the
equation. The more mathematically interested reader will also remark that x = −√2 is
another solution. But faced with the equation x2 = - 2, very few are able to find a
proper solution without any previous knowledge of complex numbers.
Such numbers have many applications in science, and it is therefore important to be
able to use such numbers in our programs.
On the following pages we extend the previous material on computing with real numbers
to complex numbers. The text is optional, and readers without knowledge of complex
numbers can safely drop this part.

u = a + ib; v = c + id.
The following rules reflect complex arithmetic:
u = v for a = c and b = d - u = - a – ib u* = a – ib (complex conjugate)
u + v = (a+c) + i(b+d) u – v = (a-c) + i(b-d)
uv = (ac - bd) + i(bc +ad)
u/v = {(ac+bd)/(c2 + d2)} +i{(bc-ad)/(c2 + d2)}
|u|= (a2 + b2)1/2
eiq = cos(q) + isin(q).
Complex arithmetic in python: >>> from math import *
>>> u=1.5+3.2j # writing a complex number >>> x=cos(pi/3) + sin(pi/6)
>>> u+v #adding two complex number. >>> x #cheaking that trigonometric functions are
working properly.
(5+6j)
1.0
>>> u-v #subtraction between two complex no.
>>> y=e**pi #cheaking pi and e working properly.
(-2+0.40000000000000036j)
>>> y
>>> u=complex(1.5,3.2) #creating a complex number
23.140692632779263
>>> v=complex(3.5,2.8) #creating a complex number
>>> z2=complex(cos(pi),sin(pi))
>>> u*v # product of two complex number
>>> z2
(-3.709999999999999+15.4j)
(-1+1.2246467991473532e-16j)
>>> u/v # divission of complex numbers
>>> from cmath import *
(0.7073170731707318+0.3484320557491289j)
>>> z3=cos(pi) + jsin(pi);
>>> w=[Link]# creating a complex conjugate
>>> z3=cos(pi) + sin(pi)*j ,
>>> w
>>> u=cos(pi) + j*sin(pi)
<built-in method conjugate of complex object at
0x000001F9F3269A70> This type of input is not supported.
>>> w=[Link]() # creating a complex conjugate Traceback (most recent call last):
>>> w File "<stdin>", line 1, in <module>
(1.5-3.2j) NameError: name 'j' is not defined
>>> from cmath import sin, cos, pi,exp >>> from math import *
>>> u=cos(pi) + 1j*sin(pi) >>> z1=e**(pi) + 1

>>> u >>> z1 24.140692632779263

(-1+1.2246467991473532e-16j) >>> z2 = e**(1j*pi)

>>> import math >>> z2

>>> u2=[Link](1j*[Link]) (-1+1.2246467991473532e-16j)

Traceback (most recent call last): >>> z3 = cos(pi)+ 1j*sin(pi)

File "<stdin>", line 1, in <module> >>> z3 (-1+1.2246467991473532e-16j)

TypeError: can't convert complex to float But

>>> import cmath >>> from math import *

>>> u2=[Link](1j*[Link]) >>> sqrt(-1)

>>> u2 (-1+1.2246467991473532e-16j) Traceback (most recent call last):

But ‘from math import *’ command have a different File "<stdin>", line 1, in <module>
gesture. ValueError: math domain error
>>> v= exp(1j*pi) >>> from cmath import *
>>> v (-1+1.2246467991473532e-16j) >>> sqrt(1) (1+0j)
Functions inside math module as sin, cos, pi etc >>> sqrt(-1)
are not working for complex calculation

To call math and cmath jointly we should use >>> from [Link] import *
Exercise 1.1

“Write a program that computes the volume V and total surface A of a cube with sides of length L=10 cm and prints the result to
the screen. V, A and L should be defined as separate variables in the program. Run the program and confirm that the correct
result is printed.”
i) Print this statement on screen in single line and multiline.
ii) prints the result to the screen by calculating manually.
iii) Run the program and confirm that the correct result is printed.
iv) prints the result in SI unit up to 2 and 3 decimal place using proper formatting.(The result should be printed as “The volume
V = ___ cubic meter, Total area A = ___ m2 )
v) prints the result in scientific notation.
vi) Using user input method print the volume and area for different value of L.

Exercise 1.2: find the roots of the equation 2x2 +x+2=0.


Find errors in the coding of a formula and print the correct result.
>>>a = 2; b = 1; c = 2
>>> from math import sqrt
>>> q = b*b - 4*a*c
>>> q_sr = sqrt(q)
>>> x1 = (-b + q_sr)/2*a
>>> x2 = (-b - q_sr)/2*a
>>> print (x1, x2)
Hence find the roots of 2x2 +x-2=0.
Exercise 1.3
Find errors in a program and print the correct value in different format (%d,%f,%g,%e,%E)
What is the problem in the following program?
>>>from math import pi, tan
>>>tan = tan(pi/4)
>>>tan2 = tan(pi/3)
>>>print (tan, tan2)
Exercise 1.4
Let us see the power of compounding. Let you fix 1000 Rs. in a bank with 7.5% interest rate for 30 year. Compute the total
amount you will get back i) with the option of simple interest. And ii) with an option of yearly compound interest. Use the
𝑝 𝑛
formula 𝐴(1 + ) where A is principal, p is interest rate and n is number of year.
100

Exercise 1.5
1
Write a python program to compute cosh(x) using the formula cosh 𝑥 = (𝑒 𝑥 + 𝑒 −𝑥 ) and prove the your value is correct by
2
using [Link]( ) function.
Exercise 1.6
Compute sin(pi/6) and and cos(pi/6) and hence show the (𝑠𝑖𝑛 𝑥)2 + (𝑐𝑜𝑠 𝑥)2 = 1.
Exercise 1.7
Write a Python script to verify Stirling's approximation: ln 100! 100 ln 100 — 100.
Exercise 1.8
Consider z be a complex number: z = 2 + 3j. Utilize appropriate functions from a proper module to find out some values of the
multiple valued function w = ln z.

You might also like