Basic Python
Quick start
python -V # to check the version of python
python -c ’print ("Hello World")’ # simplest hello world program
ipython # IPython 1.2.0 #-- An enhanced Interactive Python
In [4]:
a=2
b=5
c = a+b
d = a-b
q, r = a/b, a%b # Yes, this is allowed!
# Now, let's print!
print "Hello World!" # We just had to do this, did we not? print "Sum, Differe
nce = ", c, d
print "Quotient and Remainder = ", q, r
Hello World!
Quotient and Remainder = 0 2
What we have learned from the above simple program?
Dynamic Typing We don't declare variables and types in advance. (dynamic typing)
Variables created when first assigned values.
Variables don't exist if not assigned. (strong typing)
Commenting Everything after # is a comment and is ignored. Comment freely
In [5]:
##Tuple unpacking assignments
a,b,c,d,e = 5,5,1,0,7
In [6]:
a,b,c,d,e
Out[6]:
(5, 5, 1, 0, 7)
In [7]:
Out[7]:
5
Integers
In [8]:
8 ** 3 # Exponentiation
Out[8]:
512
In [9]:
23**100 # Auto-upgrade to "LONG INT" Notice the L!
Out[9]:
148861915063630393937915565865597542319871196538013686865769882092
224332785393313521523901432773468042334765921794473108595202225298
76001L
In [10]:
2 / 5, 2%5 # Quotient-Remainder Revisited.
Out[10]:
(0, 2)
Floats
In [11]:
5. * 2, 5*2. # Values upgraded to "higher data type".
Out[11]:
(10.0, 10.0)
In [12]:
5**0.5 # Yes, it works! Square-root.
Out[12]:
2.23606797749979
In [13]:
2. / 4. # No longer a quotient.
Out[13]:
0.5
In [14]:
5 % 4.0, 5 % 4.1 # Remainder, yes!!!
Out[14]:
(1.0, 0.9000000000000004)
In [15]:
a="Hello" ; b=" World"
a,b
a+b
a*3
Out[15]:
'HelloHelloHello'
Math Module
In [16]:
import math as mp
In [17]:
x = 45*mp.pi/180.0
mp.sin(x)
Out[17]:
0.7071067811865475
In [18]:
mp.sin( mp.radians(45) ) # nested functions
Out[18]:
0.7071067811865475
In [19]:
print dir(mp) # Prints all functions associated with Math module.
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh'
, 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', '
cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs
', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot'
, 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'm
odf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'
, 'trunc']
In [20]:
help(mp.sqrt)
Help on built-in function sqrt in module math:
sqrt(...)
sqrt(x)
Return the square root of x.
Strings
In [21]:
a = 10000.
a
Out[21]:
10000.0
In [22]:
a = "Tom's Laptop" # notice the '
In [23]:
Out[23]:
"Tom's Laptop"
In [24]:
b = 'Tom said, "This is my laptop."' # notice the "
In [25]:
Out[25]:
'Tom said, "This is my laptop."'
In [26]:
a_alt = 'Tom\'s Laptop' # now you need the escape sequence \
In [27]:
a_alt
Out[27]:
"Tom's Laptop"
In [28]:
b_alt = "Tom said, \"This is my laptop.\"" # again escape sequence.
In [29]:
b_alt
Out[29]:
'Tom said, "This is my laptop."'
In [30]:
long_string = """Hello World!
Tom said, "This is my laptop!" """
In [31]:
long_string
Out[31]:
'Hello World! \nTom said, "This is my laptop!" '
In [32]:
a= "Hello World"
b= "This is my laptop"
print a
print b
Hello World
This is my laptop
String Arithmetic
In [33]:
s1 = "Hello" ; s2 = "World!"
In [34]:
string_sum = s1 + s2
print string_sum
HelloWorld!
In [35]:
string_product = s1*3
print string_product
HelloHelloHello
In [36]:
print s1*3+s2
HelloHelloHelloWorld!
String is a sequence!
In [37]:
a = "Python rocks!"
In [38]:
a[0:6:2], a[1], a[6] # Positions begin from 0 onwards.
Out[38]:
('Pto', 'y', ' ')
In [39]:
a[-1], a[-2], a[-3] # Negative indices - count backwards!
Out[39]:
('!', 's', 'k')
In [40]:
len(a) # Measures length of both sequence/unordered collection s!
Out[40]:
13
Sequences can be sliced!
In [41]:
a[2:6] # elements with indices 2,3,4,5 but not 6
Out[41]:
'thon'
In [42]:
a[8:-2] # indices 8,9 ... upto 2nd last but not including it.
Out[42]:
'ock'
In [43]:
a[:5] # Missing first index, 0 assumed.
Out[43]:
'Pytho'
In [44]:
a[5:] # Missing last index, len(a) assumed.
Out[44]:
'n rocks!'
In [45]:
a[1:6:2],a[1],a[3],a[5] # Indices 1, 3, 5
Out[45]:
('yhn', 'y', 'h', 'n')
In [46]:
a[::2] # beginning to end
Out[46]:
'Pto ok!'
In [47]:
a[::-1] # Reverse slicing!
Out[47]:
'!skcor nohtyP'
String Methods
In [48]:
a = " I am a string, I am an object, I am immutable! "
In [49]:
a.title()
Out[49]:
' I Am A String, I Am An Object, I Am Immutable! '
In [50]:
a.split(",")
Out[50]:
[' I am a string', ' I am an object', ' I am immutable! ']
In [51]:
a.strip() # Remove trailing and leading whitespaces.
Out[51]:
'I am a string, I am an object, I am immutable!'
In [52]:
a = "0000000this is string example....wow!!!0000000";
print a.strip( '0' )
this is string example....wow!!!
In [53]:
# Modified first program.
a = raw_input("Please enter number 1: ")
b = raw_input("Please enter number 2: ")
c, d = a+b, a-b
q, r = a/b, a*b
print c,d,q,r
Please enter number 1: 1
Please enter number 2: 2
------------------------------------------------------------------
---------
TypeError Traceback (most recent c
all last)
<ipython-input-53-846d8c97a6ee> in <module>()
2 a = raw_input("Please enter number 1: ")
3 b = raw_input("Please enter number 2: ")
----> 4 c, d = a+b, a-b
5 q, r = a/b, a*b
6 print c,d,q,r
TypeError: unsupported operand type(s) for -: 'str' and 'str'
In [54]:
a = float( raw_input("Enter Number 1: ") )
b = float( raw_input("Enter Number 2: ") )
c,d = a+b, a-b
q,r = a*b, a/b
print "Addition = %f, Difference = %f " % (c,d)
print "Division = %f, Quotient = %f" % (q,r)
Enter Number 1: 1
Enter Number 2: 2
Addition = 3.000000, Difference = -1.000000
Division = 2.000000, Quotient = 0.500000
In [55]:
a = float( raw_input("Enter Number 1: ") )
b = float( raw_input("Enter Number 2: ") )
c,d = a+b, a-b
q,r = a*b, a/b
print "Addition = %5.2f, Difference = %5.2f " % (c,d)
print "Division = %5.2f, Quotient = %5.2f" % (q,r)
Enter Number 1: 1
Enter Number 2: 3
Addition = 4.00, Difference = -2.00
Division = 3.00, Quotient = 0.33
In [56]:
gal_name = "NGC 7709"
int_bmagnitude = 13.6
statement1 = "The galaxy %s has an integrated B-band magnitude of %.2f" % (gal
_name, int_bmagnitude)
statement2 = "The galaxy {:s} has an integrated B-band magnitude of {:.2f}".fo
rmat(gal_name, int_bmagnitude)
statement3 = "The galaxy {name:s} has an integrated B-band magnitude of {mag:.
2f}".format(name=gal_name, mag=int_bmagnitude)
In [57]:
print statement1
The galaxy NGC 7709 has an integrated B-band magnitude of 13.60
In [58]:
print statement2
The galaxy NGC 7709 has an integrated B-band magnitude of 13.60
In [59]:
print statement3
The galaxy NGC 7709 has an integrated B-band magnitude of 13.60
In [60]:
print statement1, "\n", statement2, "\n", statement3, "\n"
The galaxy NGC 7709 has an integrated B-band magnitude of 13.60
The galaxy NGC 7709 has an integrated B-band magnitude of 13.60
The galaxy NGC 7709 has an integrated B-band magnitude of 13.60
Click on the link : https://pyformat.info (https://pyformat.info) for find more
information about Python formatting.
Conditionals
In [61]:
num = int( raw_input("Enter number: ") )
if num %2 == 0:
print "%d is even!" % num
else:
print "%d is odd!" % num
Enter number: 5
5 is odd!
Conditions are anything that return True or False.
'==' (equal to)
'!='
'>'
'>='
'<'
'<='
You can combine conditionals using "logical operators"
'and'
'or'
'not'
The Boolean Data Type
In [62]:
a = True; b = False
if a:
print "This comes on screen."
if b:
print "This won't come on screen."
This comes on screen.
Exercise time
1. Write a program to accept 5 numbers and print their median and standard deviation.
1. Write a program which accepts a name from a user and prints the same name with all letters
capitalized. Use iPython to find the correct string method for the same.
2. Create a program which defines a list [1,2,3,4,5,7,8,9,10]. And then it should accept from the
number from the user and check if it exists inside the list. If in the list it should display "Yes,
found it!" or it should display "Sorry, could not find that."
3. Define a function which accepts a number and checks if the number is prime or not. It should
return True if prime else return a False.