This is Python Tutorial
This is our first program in python: It is just started here
In [1]: print("Hellow World")
Hellow World
a = b + c
Variables
In [1]: x = 3
In [2]: %whos
Variable Type Data/Info
----------------------------
x int 3
In [3]: print(type(x))
<class 'int'>
In [4]: x = 5.7
In [5]: %whos
Variable Type Data/Info
-----------------------------
x float 5.7
In [6]: print(type(x))
<class 'float'>
In [7]: abcd = 556.32
In [8]: %whos
Variable Type Data/Info
-----------------------------
abcd float 556.32
x float 5.7
In [9]: a,b,c,d,f = 3,5,6.0,7.2,-3
In [10]: %whos
Variable Type Data/Info
-----------------------------
a int 3
abcd float 556.32
b int 5
c float 6.0
d float 7.2
f int -3
x float 5.7
In [11]: del abcd
In [12]: %whos
Variable Type Data/Info
-----------------------------
a int 3
b int 5
c float 6.0
d float 7.2
f int -3
x float 5.7
In [13]: print(abcd)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-13-ce1394b9d4d9> in <module>
----> 1 print(abcd)
NameError: name 'abcd' is not defined
In [14]: c = 2+4j
In [15]: print(type(c))
<class 'complex'>
In [16]: s = "hellow how are you"
In [17]: print(type(s))
<class 'str'>
Operators
In [18]: %whos
Variable Type Data/Info
-------------------------------
a int 3
b int 5
c complex (2+4j)
d float 7.2
f int -3
s str hellow how are you
x float 5.7
In [19]: sumOfaAndb = a+b
In [20]: print(sumOfaAndb)
In [21]: type(sumOfaAndb)
Out[21]: int
In [22]: type(a+d)
Out[22]: float
In [23]: v = ((a+d)**3)/4
In [24]: print(v)
265.30199999999996
In [25]: s1 = "hellow"
s2 = "world"
s = s1+s2
print(s)
hellowworld
In [26]: 10//3
Out[26]: 3
In [27]: 10/3
Out[27]: 3.3333333333333335
In [28]: _
Out[28]: 3.3333333333333335
In [29]: 3x = 5
File "<ipython-input-29-b52acbda3310>", line 1
3x = 5
^
SyntaxError: invalid syntax
In [30]: @y=4
File "<ipython-input-30-e67763287a1a>", line 1
@y=4
^
SyntaxError: invalid syntax
In [31]: *t=4
File "<ipython-input-31-3588004ff47c>", line 4
SyntaxError: starred assignment target must be in a list or tuple
In [32]: _e = 6
In [33]: startingTimeOfTheCourse = 2.0
In [34]: %whos
Variable Type Data/Info
----------------------------------------------
a int 3
b int 5
c complex (2+4j)
d float 7.2
f int -3
s str hellowworld
s1 str hellow
s2 str world
startingTimeOfTheCourse float 2.0
sumOfaAndb int 8
v float 265.30199999999996
x float 5.7
Bool
In [35]: a = True
b = True
c = False
In [36]: %whos
Variable Type Data/Info
--------------------------------------------
a bool True
b bool True
c bool False
d float 7.2
f int -3
s str hellowworld
s1 str hellow
s2 str world
startingTimeOfTheCourse float 2.0
sumOfaAndb int 8
v float 265.30199999999996
x float 5.7
In [37]: print(a and b)
print(a and c)
print(c and a)
True
False
False
In [38]: d = a or c
print(d)
True
In [39]: not(a)
Out[39]: False
In [40]: not(b)
Out[40]: False
In [41]: not(c)
Out[41]: True
In [42]: t = not(d)
In [43]: type(t)
Out[43]: bool
In [44]: print(t)
False
In [45]: not((a and b) or (c or d))
Out[45]: False
Comparisons
In [46]: print(2<3)
True
In [47]: c = 2<3
print(type(c))
print(c)
<class 'bool'>
True
In [48]: d = 3==4
In [49]: print(d)
False
In [50]: 3==3.0
Out[50]: True
In [51]: x = 4
y = 9
z = 8.3
r = -3
In [52]: (x<y) and (z<y) or (r==x)
Out[52]: True
In [53]: (r==x) and (x<y) or (z>y)
Out[53]: False
In [57]: (True or False) and False
Out[57]: False
In [59]: print((not(2!=3) and True) or (False and True))
False
In [60]: print(round(4.556))
In [61]: print(round(4.345))
In [64]: print(round(4.556389,3))
4.556
In [66]: B = divmod(27,5)
In [67]: type(B)
Out[67]: tuple
In [68]: print(B)
(5, 2)
In [69]: B[0]
Out[69]: 5
In [70]: B[1]
Out[70]: 2
In [71]: divmod(22,10)
Out[71]: (2, 2)
In [73]: G = divmod(34,9)
In [74]: type(G)
Out[74]: tuple
In [75]: print(G)
(3, 7)
In [76]: G[0]
Out[76]: 3
In [77]: G[1]
Out[77]: 7
In [78]: 34//9
Out[78]: 3
In [79]: 34%9
Out[79]: 7
In [80]: isinstance(3,int)
Out[80]: True
In [83]: isinstance(3.4,(float,int))
Out[83]: True
In [86]: isinstance(2+3j,(int,float,str,complex))
Out[86]: True
In [87]: pow(2,4)
Out[87]: 16
In [88]: 2**4
Out[88]: 16
In [89]: pow(2,4,7)
Out[89]: 2
In [90]: x = input("Enter a number :")
Enter a number :56
In [91]: type(x)
Out[91]: str
In [92]: x = int(x)
In [93]: type(x)
Out[93]: int
In [94]: print(x-34)
22
In [95]: a = float(input("Enter a real number :"))
Enter a real number :12.5
In [96]: type(a)
Out[96]: float
In [97]: b = float(input("Enter a real number : "))
Enter a real number : abc
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-97-5ddd2644c78a> in <module>
----> 1 b = float(input("Enter a real number : "))
ValueError: could not convert string to float: 'abc'
In [100]: help(pow)
Help on built-in function pow in module builtins:
pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
In [101]: help(input)
Help on method raw_input in module ipykernel.kernelbase:
raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance
Forward raw_input to frontends
Raises
------
StdinNotImplentedError if active frontend doesn't support stdin.
In [104]: a = int(input())
b = int(input())
if a>b:
print(a)
print("I am still inside if condition")
print("I am outside the if condition")
10
45
I am outside the if condition
In [106]: a = int(input())
b = int(input())
if a>b:
print(a)
if b>a:
print(b)
22
4
22
In [109]: a = int(input())
b = int(input())
if a>b:
print(a)
print("if part")
else:
print(b)
print("else part")
10
10
10
else part
In [112]: a = 10
b = 10
if a==b:
print("Equal")
elif a>b:
print("A")
else:
print("B")
print("Not in if")
Equal
Not in if
In [114]: a = int(input("Enter Marks :"))
if a >= 85:
print("A Grade")
elif (a < 85) and (a >= 80):
print("A- Grade")
elif a < 80 and a >= 75:
print("B Grade")
elif a < 75 and a >= 70:
print("B- Grade")
else:
print("Below Average")
Enter Marks :64
Below Average
In [116]: a = 13
if a>10:
print(">10")
elif not(a>10):
print("Else part")
>10
In [118]: a = int(input())
if a>10:
print(">10")
print("Inside the top if")
if a>20:
print(">20")
print("Inside the nested if")
if a>30:
print(">30")
print("inside the nested if of nested if")
else:
print("<=30")
print("inside the else part of nested if of nested if")
else:
print("<=20")
print("Inside the else part of nested if")
print("Outside all ifs")
25
>10
Inside the top if
>20
Inside the nested if
<=30
inside the else part of nested if of nested if
Outside all ifs
In [132]: # single line comment
"""
User will enter a floating point number let say 238.915. Your task
is to find out the integer portion before the point (in this case 238)
and then check if that integer portion is an even number or not?
"""
x = float(input("Enter a real number :"))
y = round(x)
if x>0:
if y>x:
intPortion = y-1 # 29.6
else:
intPortion = y
else:
if y<x:
intPortion = y+1
else:
intPortion = y
if intPortion%2 == 0:
print("Even")
else:
print("Odd")
Enter a real number :-87.3
Odd
In [125]: round(-9.3)
Out[125]: -9
In [126]: round(-9.6)
Out[126]: -10
In [133]: n = int(input())
i = 1
while i < n:
print(i**2)
print("This is iteration number :", i)
i+=1 # i = i+1
print("Loop done")
5
1
This is iteration number : 1
4
This is iteration number : 2
9
This is iteration number : 3
16
This is iteration number : 4
Loop done
In [135]: n = 10
i = 1
while True:
if i%9 == 0:
print("Inside if")
break
else:
print("inside Else")
i = i+1 # i+=1
print("done")
inside Else
inside Else
inside Else
inside Else
inside Else
inside Else
inside Else
inside Else
Inside if
done
In [136]: n = 10
i = 1
while True:
if i%9 != 0:
print("inside if")
i +=1
continue
print("something")
print("somethingelse")
break
print("done")
inside if
inside if
inside if
inside if
inside if
inside if
inside if
inside if
something
somethingelse
done
In [140]: L = []
for i in range(1,20,3):
print(i)
L.append(i**2)
print(L)
1
4
7
10
13
16
19
[1, 16, 49, 100, 169, 256, 361]
In [142]: S = {"apple",4.9,"cherry"}
i = 1
for x in S:
print(x)
i+=1
if i==3:
break
else:
pass
else:
print("Loop terminates with success")
print("Out side the loop")
apple
4.9
Out side the loop
In [143]: D = {"A":10,"B":-19,"C":"abc"}
for x in D:
print(x,D[x])
A 10
B -19
C abc
In [149]: """ Given a list of numbers i.e. [1,2,4,-5,7,9,3,2], make another list
that contains all the items in sorted order from min to max. i.e. your
result will be another list like [-5,1,2,2,3,7,9]
"""
L = [1,2,4,-5,7,9,3,2]
for j in range(len(L)):
m = L[j]
idx = j
c = j
for i in range(j,len(L)):
if L[i]<m:
m = L[i]
idx = c
c+=1
tmp = L[j]
L[j] = m
L[idx] = tmp
print(L)
[-5, 1, 2, 2, 3, 4, 7, 9]
In [147]: L
Out[147]: [-5, 2, 4, 1, 7, 9, 3, 2]
In [1]: def printSuccess():
print("I am done")
print("send me another task")
In [2]: printSuccess()
I am done
send me another task
In [3]: 3+8
Out[3]: 11
In [4]: printSuccess()
I am done
send me another task
In [5]: def printSuccess2():
""" This function is doing nothing except printing a message.
That message is "hellow"
"""
print("hellow")
In [10]: help(printSuccess2)
Help on function printSuccess2 in module __main__:
printSuccess2()
This function is doing nothing except printing a message.
That message is "hellow"
In [11]: printSuccess2()
hellow
In [12]: def printMsg(msg):
""" The function prints the message supplied by the user
or prints that msg is not in the form of string"""
if isinstance(msg,str):
print(msg)
else:
print("Your input argument is not a string")
print("Here is the type of what you have supplied :",type(msg))
In [13]: help(printMsg)
Help on function printMsg in module __main__:
printMsg(msg)
The function prints the message supplied by the user
or prints that msg is not in the form of string
In [15]: printMsg?
In [16]: printMsg("This is the message")
This is the message
In [17]: printMsg(23)
Your input argument is not a string
Here is the type of what you have supplied : <class 'int'>
In [18]: y = "hellow there"
printMsg(y)
hellow there
In [19]: def mypow(a,b):
""" this function computes power just like builtin pow function"""
c = a**b
print(c)
In [20]: mypow?
In [21]: mypow(3,4)
81
In [22]: def checkArgs(a,b,c):
if isinstance(a,(int,float)) and isinstance(b,(int,float)) and isinstance(c,(int,flo
at)):
print((a+b+c)**2)
else:
print("Error: the input arguements are not of the expected types")
In [23]: checkArgs(3,4,5)
144
In [24]: checkArgs(3,4,"g")
Error: the input arguements are not of the expected types
In [25]: checkArgs(3,4)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-f6f193ef9e63> in <module>
----> 1 checkArgs(3,4)
TypeError: checkArgs() missing 1 required positional argument: 'c'
In [26]: checkArgs(2,3,4,5)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-182e860594b3> in <module>
----> 1 checkArgs(2,3,4,5)
TypeError: checkArgs() takes 3 positional arguments but 4 were given
In [27]: def f(a,b,c):
print("A is :",a)
print("B is :",b)
print("C is :",c)
In [29]: #f(2,3,"game")
f(3,"game",2)
A is : 3
B is : game
C is : 2
In [31]: #f(a = 2,b=3,c="game")
f(c="game",a=2,b=3)
A is : 2
B is : 3
C is : game
In [35]: def myadd(a,b):
sumValue = a+b
return sumValue
In [37]: d = myadd(2,3)
print(d)
In [38]: variableOutSideTheFunction = 3
In [44]: def g():
variableOutSideTheFunction = 5
#print(variableOutSideTheFunction)
In [47]: print(type(g()))
<class 'NoneType'>
In [43]: print(variableOutSideTheFunction)
In [51]: def h():
print("A")
a = 3
b = 5
c = a+b
print("something")
return c
print("B")
print("C")
In [53]: print(type(h()))
A
something
<class 'int'>
In [54]: def r():
a = 5
b = 7
d = "something"
return a,b,d
In [55]: x,y,z = r()
print(x,y,z)
5 7 something
In [56]: def myAddUniversal(*args):
s = 0
for i in range(len(args)):
s += args[i] # s = s+args[i]
return s
In [58]: print(myAddUniversal(2,4,5,4.6,78))
93.6
In [59]: def printAllVariableNamesAndValues(**args):
for x in args:
print("Variable Name is :",x," And Value is :",args[x])
In [60]: printAllVariableNamesAndValues(a = 3,b="B",c="CCC",y=6.7)
Variable Name is : a And Value is : 3
Variable Name is : b And Value is : B
Variable Name is : c And Value is : CCC
Variable Name is : y And Value is : 6.7
In [61]: def gg(s=4):
print(s)
In [62]: gg()
In [63]: gg(56)
56
In [64]: L = [1,2,3]
L2 = L
L2[0] = -9
print(L)
[-9, 2, 3]
In [65]: def ff(L=[1,2]):
for i in L:
print(i)
In [66]: L2 = [12,3,4]
ff()
1
2
In [67]: ff(L2)
12
3
4
In [68]: ff()
1
2
In [69]: import sys
sys.path.append('C:/ABC/')
In [77]: import my_universal_functions as myfs
#from my_universal_functions import addAllNumerics
In [76]: d = addAllNumerics(2,3,4,5,6,7)
print(d)
27
In [73]: c = myfs.addAllNumerics(2,3,4,6)
In [74]: print(c)
15
In [78]: myfs.myName
Out[78]: 'Python Course'
In [79]: """ Given a list of numbers i.e. [1,2,4,-5,7,9,3,2], make another list
that contains all the items in sorted order from min to max. i.e. your
result will be another list like [-5,1,2,2,3,7,9]
"""
Out[79]: ' Given a list of numbers i.e. [1,2,4,-5,7,9,3,2], make another list\nthat contains all
the items in sorted order from min to max. i.e. your \nresult will be another list like
[-5,1,2,2,3,7,9]\n'
In [88]: def findMin(L,startIndx):
m = L[startIndx]
idx = startIndx
for i in range(startIndx,len(L)):
x = L[i]
if x<m:
m = x
idx = i
else:
pass
return m,idx
In [83]: a,b = findMin([2,3,4,0,9])
In [84]: print(a,b)
0 3
In [85]: def swapValues(L,idx1,idx2):
tmp = L[idx1]
L[idx1] = L[idx2]
L[idx2] = tmp
return L
In [86]: L = [2,3,6,7]
L2 = swapValues(L,1,3)
print(L2)
[2, 7, 6, 3]
In [102]: from my_universal_functions import checkIfNotNumeric
def sortList(L):
if not(checkIfNotNumeric2(L)):
print("Error: List does not contain numeric values")
return
else:
c = 0
for x in L:
m,idx = findMin(L,c)
L = swapValues(L,c,idx)
c+=1
return L
In [103]: L2 = sortList([2,1,5,3,-8,17])
print(L2)
[-8, 1, 2, 3, 5, 17]
In [91]: checkIfNotNumeric??
In [99]: print(checkIfNotNumeric2([2,1,5,3,8,17]))
True
In [107]: def checkIfNotNumeric2(L):
for x in L:
if not(isinstance(x,(int,float))):
return False
return True
In [108]: s = "Python is a good language"
t = 'Its good for data science'
In [109]: type(s)
Out[109]: str
In [110]: print(s)
Python is a good language
In [111]: print("hellow",12,"hellow2",'who are you',5.9)
hellow 12 hellow2 who are you 5.9
In [113]: v = s+" "+t
print(v)
Python is a good language Its good for data science
In [117]: price = 12
s = "The price of this book"
v = s + ' is: ' + str(price)
print(v)
print(s,"is:",price)
The price of this book is: 12
The price of this book is: 12
In [119]: a = """this is line 1
this is line 2
this is last line and this line is 3"""
print(a)
this is line 1
this is line 2
this is last line and this line is 3
In [120]: print(""" The following options are available:
-a : does nothing
-b : also does nothing
""")
The following options are available:
-a : does nothing
-b : also does nothing
In [121]: s = "How are you and who are you"
print(s[5])
In [122]: type(s[5])
Out[122]: str
In [125]: s[0:10]
Out[125]: 'How are yo'
In [126]: s[-1]
Out[126]: 'u'
In [127]: s[-3]
Out[127]: 'y'
In [129]: s[-12:-3]
Out[129]: ' who are '
In [130]: s[1] = "e"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-130-6ca1c1f7962b> in <module>
----> 1 s[1] = "e"
TypeError: 'str' object does not support item assignment
In [131]: s[0:12:2]
Out[131]: 'Hwaeyu'
In [132]: s
Out[132]: 'How are you and who are you'
In [133]: #s[start:end:step]
s[:12]
Out[133]: 'How are you '
In [134]: s[3:]
Out[134]: ' are you and who are you'
In [135]: s[1:12]
Out[135]: 'ow are you '
In [136]: s[::-1]
Out[136]: 'uoy era ohw dna uoy era woH'
In [137]: a = " abc def hgq asdfaf "
b = a.strip()
print(b)
abc def hgq asdfaf
In [138]: a = "ABC deFg ;; sadfa QF"
b = a.lower()
print(b)
abc defg ;; sadfa qf
In [139]: c = a.upper()
print(c)
ABC DEFG ;; SADFA QF
In [140]: d = a.replace(";","*")
print(d)
ABC deFg ** sadfa QF
In [141]: d = a.replace(";","**&&^^%%")
print(d)
ABC deFg **&&^^%%**&&^^%% sadfa QF
In [142]: d = a.replace(";;","two semi colons")
print(d)
ABC deFg two semi colons sadfa QF
In [143]: a = "abc;def;hgydfa;yy23"
L = a.split(";")
print(L)
['abc', 'def', 'hgydfa', 'yy23']
In [144]: L[1]
Out[144]: 'def'
In [147]: print(a.capitalize())
Abc;def;hgydfa;yy23
In [149]: "abdAfadfGGQ".capitalize()
Out[149]: 'Abdafadfggq'
In [150]: help(a.count)
Help on built-in function count:
count(...) method of builtins.str instance
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
In [153]: "abc" in "asdfafdjabcl;jfdopasdfoajfd;la"
Out[153]: True
In [154]: "abc" == "abc"
Out[154]: True
In [156]: "abcdefghi"<"def"
Out[156]: True
In [157]: "$%"<"*&"
Out[157]: True
In [158]: print("we are learning "string" here")
File "<ipython-input-158-439afcb22d48>", line 1
print("we are learning "string" here")
^
SyntaxError: invalid syntax
In [159]: print("we are learning \"string\" here")
we are learning "string" here
In [160]: print('we are learing "string" here')
we are learing "string" here
In [162]: print("we are \t now on another line")
we are now on another line
In [163]: print("c:\name\drive")
c:
ame\drive
In [164]: print(r"c:\name\drive")
c:\name\drive
In [ ]: