Python Codes
Python Codes
# 1 Hello World
Learning: How to print and run python program
Assingment 2.1: WAP to add three numbers and print the result.
Assingment 2.2: WAP to concatinate three strings and print the result.
# Run the program with (1) Two strings and (2) Two numbers
### 3.2 Input two numbers from user and add them
a = int(input("Enter First No: "))
b = int(input("Enter Second No: "))
c = a + b
print (a, " + ", b, " --> ", c)
4 Loop
Learning: Learn various loops.
1
2
3
4
5
6
7
8
9
10
### 4.2 Range Function
print ("range(10) --> ", list(range(10)))
print ("range(10,20) --> ", list(range(10,20)))
print ("range(0,20,2) --> ", list(range(2,20,2)))
print ("range(-10,-20,2) --> ", list(range(-10,-20,2)))
print ("range(-10,-20,-2)--> ", list(range(-10,-20,-2)))
0
1
2
3
4
5
6
7
8
9
0
2
4
6
8
10
12
14
16
18
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Sum is --> 55
Assingment 4.3: WAP to add all the numbers from 1 to n and n is given by user.
Enter a No: 54
54 is even
### 5.3 Check weather a number is prime of not
n = int(input("Enter a No: "))
f=0
for i in range(2, n//2 + 1):
if n % i == 0:
f=1
break
if f==0:
print ("Prime")
else:
print ("Not Prime")
Enter a No: 56
Not Prime
if a == b:
print ("a == b")
elif a >= b:
print ("a > b")
else:
print ("a < b")
Assingment 5.1: WAP to find max amoung three numbers and input from user. [Try max()
function]
Assingment 5.2: WAP to add all numbers divisible by 7 and 9 from 1 to n and n is given by the
user.
Assingment 5.3: WAP to add all prime numbers from 1 to n and n is given by the user.
6 Functions
Learning: How to declare and call function
Add(10,20) --> 30
Add(20,50) --> 70
Add(80,200) --> 280
IsPrime(20) --> 0
IsPrime(23) --> 1
IsPrime(200) --> 0
IsPrime(37) --> 1
AddN(10) --> 55
AddN(20) --> 210
AddN(50) --> 1275
AddN(200) --> 20100
Assingment 6.1: WAP using function that add all odd numbers from 1 to n, n is given by the user.
Assingment 6.2: WAP using function that add all prime numbers from 1 to n, n given by the user.
7 Math library
Learning: Use math library
import math as m
print ("exp(-200) --> ", m.exp(-200)) # Exponential function
print ("log(100,2) --> ", m.log(100,2)) # Log
print ("log(100,10) --> ", m.log(100,10))# Log
print ("log10(100) --> ", m.log10(100)) # Log 10
print ("m.cos(30) --> ", m.cos(30)) # cos
print ("m.sin(30) --> ", m.sin(30)) # sin
print ("m.tan(30) --> ", m.tan(30)) # tan
print ("m.sqrt(324) --> ", m.sqrt(324))
print ("m.ceil(89.9) --> ", m.ceil(89.9))
print ("m.floor(89.9)--> ", m.floor(89.9))
var=var[::-1]
print ("var after reverse --> ", var)
s1 --> False
s2 --> True
s3 --> True
s4 --> False
9 Random Numbers/String
Learning: Generate Random Numbers/String
0.7512486175763348
0.5015832763034391
0.7335
88
47
-5
4
### 9.3 Generate random real number
import random as r
print (r.uniform(1, 100))
print (r.uniform(1, 100))
print (r.uniform (-10, 10))
print (r.uniform (-10, 10))
print (round(r.uniform (-10, 10),2))
97.39127815370512
99.35262788984427
1.5886268848088747
-4.72371568384482
3.54
A=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 8, 10, 3]
[3, 8]
[60, 70]
[12, -55, 54, -86, 30]
passwd=r.sample(s.ascii_letters, 6)
print ("Selected Char --> ",passwd)
passwd1="".join(passwd)
print ("passwd1 --> ",passwd1)
passwd2="+".join(passwd)
print ("passwd2 --> ",passwd2)
passwd3="*".join(passwd)
print ("passwd3 --> ",passwd3)
String -->
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Selected Char --> ['h', 's', 'Z', 'l', 'P', 'k']
passwd1 --> hsZlPk
passwd2 --> h+s+Z+l+P+k
passwd3 --> h*s*Z*l*P*k
otp=r.sample(s.digits, 5)
print ("Selected num1 --> ",otp)
otp="".join(otp)
print ("otp1 --> ",otp)
otp=r.sample(s.digits, 5)
print ("Selected num2 --> ",otp)
otp="".join(otp)
print ("otp2 --> ",otp)
otp=r.sample(s.digits, 5)
print ("Selected num2 --> ",otp)
otp="".join(otp)
print ("otp3 --> ",otp)
mixPasswd=r.sample(s.ascii_letters + s.digits, 6)
print ("\nSelected Str2 --> ",mixPasswd)
mixPasswd="".join(mixPasswd)
print ("mixPasswd2 --> ",mixPasswd)
splChar="#@!~%^&*()_+=-[]{}|"
mixPasswd=r.sample(splChar + s.ascii_letters + s.digits, 8)
print ("\nSelected Str3 --> ",mixPasswd)
mixPasswd="".join(mixPasswd)
print ("mixPasswd3 --> ",mixPasswd)
Selected Str3 --> ['p', 'W', '{', 'b', '_', '+', '6', '#']
mixPasswd3 --> pW{b_+6#
10 Exception Handaling
Learning: How to handle exceptions
for i in range(8):
try:
print (i," --> ",L[i])
except:
print ("error")
0 --> 1
1 --> 2
2 --> 3
3 --> 4
4 --> 5
error
error
error
----------------------------------------------------------------------
-----
FileNotFoundError Traceback (most recent call
last)
<ipython-input-42-df3155df6860> in <module>()
1 fileName=input("Enter File Name: ")
----> 2 fp=open(fileName) # Open the file in reading mode
3 fp.close()
4 print ("Done")
print ("Done")
L.append("Rahul")
print ("List After Adding --> ", L)
del L[1]
print ("List After Deleting --> ", L)
L.sort(reverse=True)
print ("After Sort (Desending) --> ", L)
L1 --> [3, 6, 9]
L2 --> [12, 5, 3, 2]
L3 --> [3, 6, 9, 12, 5, 3, 2]
newL = [ i * 5 for i in L ]
print ("After Multiply with constant --> ", newL)
if (6 in L) == True:
print ("Present")
else:
print ("Not Present")
if 10 in L == False:
print ("Not Present")
else:
print ("Present")
----------------------------------------------------------------------
-----
KeyError Traceback (most recent call
last)
<ipython-input-54-598d6ecb7ab2> in <module>()
6 print ("CGPA of 4 --> ", CGPA[4])
7 print ("CGPA of 7 --> ", CGPA[7])
----> 8 print ("CGPA of 3 --> ", CGPA[3])
KeyError: 3
bold text---
CGPA[4] = 9.2
print ("After Updating (4) --> ", CGPA)
CGPA[3] = 8.6
print ("After Adding (3) --> ", CGPA)
del CGPA[1]
print ("After Deleting (1) --> ", CGPA)
CGPA.clear()
print ("After Clear --> ", CGPA)
del CGPA
print ("After Delete --> ", CGPA)
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
<ipython-input-57-81104b3723b2> in <module>()
15
16 del CGPA
---> 17 print ("After Delete --> ", CGPA)
for d in HomeTown:
print ("Home Town of ", d, " is --> ", HomeTown[d])
# Method 2
T = tuple(["Pratham", 'Sharma', 3.14, 3]) # Convert list to tuple
#T = tuple(("Pratham", 'Sharma', 3.14, 3)) # Also Works
i = 0
while i < len(T):
print (T[i])
i += 1
for s in T:
print (s)
# Example 2:
T = (3, 6, 9, 12, 5, 3, 2)
print ("T -->", T)
# Example 2
T = ("Ram", "Shyam", "Human", "Ant") # String Tuple
print ("T -->", T)
print ("Max -->", max(T))
print ("Min -->", min(T))
T3 = T1 + T2
print ("T3 -->", T3)
T4 = T1 + T2 + T1 + T2
print ("T4 -->", T4)
T1 --> (3, 6, 9)
T2 --> (12, 5, 3, 2)
T3 --> (3, 6, 9, 12, 5, 3, 2)
T4 --> (3, 6, 9, 12, 5, 3, 2, 3, 6, 9, 12, 5, 3, 2)
T3 = T1[1:2] + T2[1:3]
print ("T3 -->", T3)
T4 = T1[:-2] + T2[:-3]
print ("T4 -->", T4)
T1 --> (3, 6, 9)
T2 --> (12, 5, 3, 2)
T3 --> (6, 5, 3)
T4 --> (3, 12)
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-74-fb1d27ae8658> in <module>()
2 print ("T -->", T)
3
----> 4 T[2] = 900 # Error; 'tuple' object does not
support item assignment
5 print ("T -->", T)
6
T1 = list(T)
T1.append(9.8)
T = tuple(T1)
T1 = list(T)
T1.insert(2, "Rahul")
T = tuple(T1)
del T[1]
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-77-0baff4d8a5c8> in <module>()
2 print ("T -->", T)
3
----> 4 del T[1]
5
6 print ("After Delete -->", T)
T1 = list(T)
del T1[1]
T = tuple(T1)
• python Program.py 10 20
import sys
print (sys.argv)
a = int(sys.argv[1]) # First Number
b = int(sys.argv[2]) # Second Number
c = a + b
print (a, " + ", b, " --> ", c)
['/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py', '-f',
'/root/.local/share/jupyter/runtime/kernel-2c370b3f-04bb-4872-8f9b-
8559cbd8132b.json']
----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
<ipython-input-82-a3d67294dc12> in <module>()
1 import sys
2 print (sys.argv)
----> 3 a = int(sys.argv[1]) # First Number
4 b = int(sys.argv[2]) # Second Number
5 c = a + b
import sys
print (sys.argv)
s = sys.argv[1] + " " + sys.argv[2]
print (sys.argv[1], " + ", sys.argv[2], " --> ", s)
['/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py', '-f',
'/root/.local/share/jupyter/runtime/kernel-2c370b3f-04bb-4872-8f9b-
8559cbd8132b.json']
-f + /root/.local/share/jupyter/runtime/kernel-2c370b3f-04bb-4872-
8f9b-8559cbd8132b.json --> -f
/root/.local/share/jupyter/runtime/kernel-2c370b3f-04bb-4872-8f9b-
8559cbd8132b.json
• python Program.py
• python Program.py 10
• python Program.py 10 20 30 40
import sys
print (sys.argv)
sum=0
for s in sys.argv[1:]:
sum += int(s)
['/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py', '-f',
'/root/.local/share/jupyter/runtime/kernel-2c370b3f-04bb-4872-8f9b-
8559cbd8132b.json']
----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
<ipython-input-84-87063e0e9afe> in <module>()
3 sum=0
4 for s in sys.argv[1:]:
----> 5 sum += int(s)
6
7 print ("Sum is --> ", sum)
Writing done !!
Open result.txt to view the content
1
2
3
4
5
6
7
8
9
10
### 16.3 Read from one file, Convert it to upper case and
write to other file
Readfp=open('result.txt') # Open the file in reading mode
Writefp=open('abc.txt','w')# Open the file in writing mode
for line in Readfp:
Writefp.write(line.upper())
Writefp.close()
Readfp.close()
Writing done !!
Open result.txt to view the content