Built-in Functions in Python
® python’ 4Program for computing the height of a ball in vertical motion.
=65
# initial velocity
9.81 # acceleration of gravity
0.6 # time
vOet - 0.54g*tk2 # vertical position
rint y
>>> v0 = 5
>>> g = 9.81
>>> t= 0.6
>>> y = vOat - 0.5agatan2
>>> print y
1.2342
=y-t 2
0.6 y=Vot-1/2gt
0.6=t 0 This is wrong 2len(...)
len(object) -> integer
Return the number of items of a sequence or mapping.
>>> x='physics'
>>> print len(x)
7
>>> print len(‘physics')
7
>>>
physics
0123456
® python
>>> print x
physics
>>> print x[0]
p
>>> print x[1]
h
>>> print x[7]
Traceback (most recent call last):
File "", line 1, in ?
IndexError: string index out of range
>>> print x[6]
s
>>> print x[0:4]
phys
>>>
3* Indexing:
—‘abe'[0] returns the string ‘a’
—‘abc'[2] returns the string ‘c’
—‘abc'’[3] isanerror (as we cannot go beyond the
boundaries of the string)
—‘abc'[-1] returns the string ‘c’ (essentially
counting backwards from the start of the string)
* Slicing:
—Ifs isastring, the expression s[start:end]
denotes the substring that starts at start, and ends
at end-1
* ‘abo'[1:3] hasthevalue ‘bc’
® python>>> 3 * ‘a’
‘aaa’
>>> ‘a’ + ‘a’
‘aa’
>>> ‘a’ + str(3)
"43
>>> len(‘abc’)
3
® python’
5>>> type("32")
The name of the function is type,
® python
>>> name="physics"
‘quaid-i-azam'
>>> pi-3.14
>>> theta=90
>>> print name
>>> unis
physics
>>> print pi
3.14
>>> print
90
>>> print
physics
>>> type (name)
6Python provides a collection of built-in functions that convert values
from one type to another.
The int function takes any value and converts it to an integer, if
possible, or complains otherwise:
>>> int("32")
32
>>> int("Hello")
ValueError: invalid literal for int(): Hello
int can also convert oating-point values to integers, but remember
that it truncates the fractional part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
7The float function converts integers and strings to foating-point
numbers:
>>> minute=59
>>> float(32) >>> minute/60
32.0 0
>>> "3, 1" >>> minute/60.0
float( 3.14159") 0.9833333333333333
3.14159 >>> minute=59.0
>>> minute/60
The str function converts to type string: 0.9833333333333333
>>> str(32)
39"
>>> str(3.14149)
'3.14149'
>>> float(minute) / 60
0.983333333333
® python
8>>> x=123456
>>> print x[0]
Traceback (most recent call last):
File "", line 1, in
print x[0]
TypeError: ‘int' object has no attribute '_getitem_'
>>> z=str (x)
>>> print z[0]
1
>>> print z[3]
4
>>> print 2[0:3]
123
>>>
® python’
9let u = a+bi and v=c+di
u*=a-—bi (complex conjugate)
ut+tv=(atc)+(bt+d)i
u-—v=(a-—c)+(b-d)i
uv = (ac — bd) + (be + ad)i
act+bd be—ad.
w= are are
e'? = cosq +ising
“10>>> u
>>> Vv
>>> w=utv
>>> Ww
(4.5433)
2.5 + 33
2
(-10.5-3.753)
>>> s/w
(-0. 25641025641025639+0 . 28205128205128205j)
>>> s.real
>> s. -gguaueate0
2-0
create a complex number
this is an int
complex + int
ae aE te
# create a complex number from two floats
# alternative creation
# complex*complex
# complex/complex
A complex object s has functionality for
extracting the real and imaginary parts as well
as computing the complex conjugate:
eu1
Je = uot — =gt?.
Ye = Vol 39
Square Root
1
got wtb te = SN
t= (0 ob Bave) fo t= (m+ Bae) (a.
Exp
Log
(e" —e77). Cos Mathematical Function
Sin How in Python?
‘Sinh(x) Exp(-x) Tan
Sinh
® python’
sinh) =
Nie
“12To evaluate a function either we have to write our own code(function)
(we will do it later on) or use built-in Modules in Python
A Module in Python can be used by Importing its name, e.g.,
import Module-Name
Two Ways of Importing a Module. The standard way to import a
module, say math, is to write
import math
and then access individual functions in the module with the module
7 vO=5
name as. prefix asin 2=9.81
ye=0.2
import math
tl =(v0- math.sqrt(v0**2 - 2*g*ye))/g
12 =(v0 + math.sqrt(v0**2- 2*g*ye))/g
print t1,t2
x = math.sqrt(y)
“13There is an alternative import syntax that allows us to skip the
module name prefix. This alternative syntax has the form
“from module import function”.
A specific example is
from math import sqrt
Now we can work with sqrt directly, without the math. prefix.
x= sqrt(y)
. . tl =(v0 - sqrt(v0**2 - 2*g*yc))/g
from math import sqrt, exp, log, sin 2 =(v0 + sqrt(v0**2 - 2*g*yc))/2
Sometimes one just writes
from math import *
to import all functions in the math module viaImported modules and functions can be given
new names in the import statement, e.g.,
import math as m
#=m is now the name of the math module
v = m.sin(m.pi)
from math import log as In
v = 1n(5)
from math import sin as s, cos as c, log as In
v= s(x)se(x) + In(x)
math import sinh, exp, e, pi
pi
sinh (x)
0.5% (exp(x) - exp(-x))
0.5*(ex#x — e#s(-x))
print ri, r2, r3
The output from the program shows that all three computations give
identical results:
‘267 .744894041 267.744894041 267.744894041 15import math
x=math.sqrt(2)
print x
from math import sqrt
y=sqri(2.)
print y
from math import sqrt as sq
z=sq(2.)
print z
pydoc math
Getting Help from Python Documents
ffelp on module math:
fusr/1ib64/python?. 4/1ib-dynload/mathmodule.so
[DESCRIETION
‘This module is always available. It provides access to the
mathematical functions defined by the C standard.
1.41421356237
1.41421356237
141421356237
® python
[runcrions
(---)
‘acos(x)
Return the arc cosine (measured in radians) of x
asin(...)
asin(x)Taking the sine of a complex number docs not work:
>>> from math import sin
>>> r = sin(w)
Traceback (most recent call last):
File "", line 1, in?
TypeError: can’t convert complex to float; use abs(z)
sqrt (-1)=?
>>> from cmath import sin, sinh
>>> ri = sin(8j)
>>> x1
1490 . 4788257895502}
>>> 12 = 1j*sinh(8)
>>> 12
1490 . 4788257895502}
Another relation, e“! = cos g + ising, is exemplified next:
>>> q=8 — # some arbitrary number
>>> exp(1j+q)
(-0. 1455000338086 1354+0.98935824662338179j)
>>> cos(q) + 1j*sin(q)
(-0. 14550003380861354+0. 98935824662338179j)
e17Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "copyright’, "credits" or "license()" for more information.
No Subprocess =
>>> import emath
>>> y=44+6j ——_____
>>> emath.sin(y)
(-152.65889676010067-131.8485 1855934087j)
>>> math.sin(y)
Traceback (most Serer
File "", line 1, in
math.sin(y)
NameError: name 'math' is not defined
>>> from cmath import sin, sinh, cosh
>>> xl=sin(4j)
>>> print xd ——____
27.2899171971j
>>> xLreal
0.0
>>> xlimag
27.28991719712775
>>> x1.conjugate()
+27.28991719712775j
>>> x1.conjugate( J——____
018We may ask the user a question C=?(Enter your roll number, Enter
your age) and wait for the user to enter a number.
Ask the user a question (What is your name?) and wait for the user
to enter a name.
Fortran Code
Program test
Implicit none
Character (5):: name . .
Integer: roll raw_input function
Real:: xx
Write (*,*) ‘Enter your name”
Read (*,*) name
Write (*,*) ‘Enter your roll number’
Read (*,*) roll
End 219C =raw_input(’C=? ’)
The raw_input function always returns the user input as a string bject.
That is, the variable C above refers to a string object.
If we want to compute with this C, we must convert the string to a
floating-point
number: C = float(C). C= cE — 32).
C = raw_input(’C=?7 ’)
c=f1 (c)
Fe (9. /5)aC + 32 F=(9./5)*C+32
print F
>>> raw_input
raw input([prompt]) —-> string]
20Fi. Python Sha
Fle Edt Shell Debug Options Windows Helo
Python 2.7.3 |EPD free 7.3-2 (32-bit)| (default, Apr 12 2012, 14:30:
t (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> raw_input ("Enter your name")
Enter your nameAli
"Ali"
>>> C=raw_input ("Enter your value")
Enter your value40
>>> C
40: —_____—
>>> type (C)
>>> C=float (Cc)
>>> type (C)
>>> C=float (raw input ("Enter your value"))
Enter your value40
>>> type (C)
<—________
>>> c>>>
>>> C=input ("Enter your value")
Enter your value40
>>> type (Cc)
>>> C=input ("Enter your value")
Enter your valueAli
Traceback (most recent call last):
File "", line 1, in
C=input ("Enter your value")
File "", line 1, in
NameError: name 'Alit is not defined
>>> C=input ("Enter you name")
Enter you nameAli
Traceback (most recent call last):
File "", line 1, in
C=input ("Enter you name")
File "", line 1, in
NameError: name 'Ali' is not defined
>>>Fle Edt Format Ron Options Windows Help
print (‘This program calculates the kinetic energy’)
m=float (raw input ("Enter mass m'))
v=float (raw input ("Enter velocity v'))
ke=(m*v**2) /2.
print ("The kinetic energy is ="), ke
Save this in a file ,e.g., ke.py
and run it
Fi Pyne shal” = =
lef Shel_Oebug_Optone Windows Help
Python 2.7.3 |EPD free 7.3-2 (32-bit)| (default, Apr 12 2012, 14:30:
t (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> =
277 NRC es(olg
2.0 scheme in the
. 3.0 eee
. Potions
>>>print
print ‘Iwill do an other calculations’
pur(Enter mass)
raw_input(Enter velocity)
print ‘GOOD Bye’
‘Ble Edit Debug Options windows Help
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[cc 4.6.3] on linux?
‘No Subprocess
Enter mass0.5
Enter velocity.
‘The Kinetic energy is 0.5625
L will do an other calculations
Enter mass4.6
Enter velocity3.7
‘The Kinetic energy is 31.487
24ax? +be+e=0,
the two roots are
_ —b+ VPP —Fae
=
2a
y=sin(x), x=0, 45,90,180.
+ yo.
2
F(x) =2tand — wear
‘The bell-shaped Gaussian function,
Fe) = Fee [-3 =);
The parameters m and s are real numbers,
where s must be greater than zero. Make a
program for evaluating this function when
m=0,s=2,and x= 1.
ball.
In this expression, x is a horizontal coordinate, g is the acceleration of gravity, v0 is the size of
the initial velocity which makes an angle with the x axis, and (0, y0) is the initial position of the