Python Exercises 1-11

Practice 1


# sum of two number
'''a = 30 
b = 6 
print ("sum of two number:", a+b)

# Remainder after divided
a = 35 
b = 6 
print ("Remainder of when a is divided by b", a%b)
'''
# Average of two number
'''
a = input ("enter first number: ")
b = input ("enter second number: ")
a = int(a)
b = int (b)
avg = (a+b)/2
print ("the average of two number is " , avg)
'''
# square of any number
a = input ("enter your number")
a = int (a)
sqr = a*a
print ("square of your number" , sqr)

Practice 2


# problem 1
# name = input ("enter your name\n")
# print ("good afternoon, " + name) 

# Problem 2

letter = '''Dear <|Name|>,
Greeting from Abc coding house. I am happy to tell you about your selection 
you are selected !
Have a great day ahead!
Thanks and regards
onam
date: <|Date|>
'''
name = input ("enter your name\n")
date = input ("enter date\n")
letter = letter.replace("<|Name|>" , name )
letter = letter.replace("<|Date|>" , date )
print(letter) 




# problem 3 and 4
# st = "this is a string with doble  spaces"
# doubleSpaces = st.find("  ")
# print (doubleSpaces)
# st = st.replace("  ", " ")
# print(st)


letter = "Dear harry,\n\tthis python course is nice!\nThanks!"
print(letter)


Practice 3


# ploblem 1 
'''
f1 = input ("enter fruit number 1: ")
f2 = input ("enter fruit number 2: ")
f3 = input ("enter fruit number 3: ")
f4 = input ("enter fruit number 4: ")
f5 = input ("enter fruit number 5: ")
f6 = input ("enter fruit number 6: ")
f7 = input ("enter fruit number 7: ")

myFruitList = [f1,f2,f3,f4,f5,f6,f7]
print(myFruitList)
'''
# problem 2
'''
m1 = int(input ("enter Marks for student number 1: "))
m2 = int(input ("enter Marks for student number 2: "))
m3 = int(input ("enter Marks for student number 3: "))
m4 = int(input ("enter Marks for student number 4: "))
m5 = int(input ("enter Marks for student number 5: "))
m6 = int(input ("enter Marks for student number 6: "))

myList = [m1,m2,m3,m4,m5,m6]
myList.sort()
print(myList)
'''
#problem 3
a = [1,2,3,4,5]
print(a[0]+a[1]+a[2]+a[3]+a[4])
print(sum(a))

Practice 4


# problem 1
'''
myDict = {
    "pani": "water",
    "kalam": "pen",
    "balti": "bucket"
}
print("your option are : " , myDict.keys())
a = input ("enter your hindi words\n")
# print("the meaning of your word is:", myDict[a])
print("the meaning of your word is:", myDict.get(a)) # this line no error if word is not present in dictonary
'''
# problem 2
'''
num1 = int(input("enter number 1\n"))
num2  = int(input("enter number 2 \n"))
num3 = int(input("enter number 3\n"))
num4 = int(input("enter number 4\n"))
num5 = int(input("enter number 5\n"))
num6 = int(input("enter number 6\n"))
num7 = int(input("enter number 7\n"))
num8 = int(input("enter number 8\n"))

s = {num1, num2, num3, num4,num5,num6,num6,num7,num8}
print(s)
'''

# problem 3
'''
s = {18,"18"}
print(s)
'''
# problem 4
'''
s = {20, 20.0, "20"}
print(len(s))
print(s)
'''
# problem 5 
favLang = {}
a = input ("enter your favorite language shubham\n")
b = input ("enter your favorite language ankit\n")
c = input ("enter your favorite language sonali\n")
d = input ("enter your favorite language harshit\n")
favLang["shubham"] = a
favLang["ankit"] = b
favLang["sonali"] = c
favLang["harshit"] = d
print(favLang) 

Practice 5


# Problem 1
num1 = int(input("enter number 1"))
num2 = int(input("enter number 2"))
num3 = int(input("enter number 3"))
num4 = int(input("enter number 4"))
if (num1>num4):
    f1 = num1
else:
    f2 = num4
if (num2>num3):
    f1 = num2
else:
    f2 = num3
if (f1>f2):
    print(str(f1) + "is greatest")
else:
    print(str(f2) + "is greatest")


#problem 2
'''
sub1 = int(input("enter first subject marks\n"))
sub2 = int(input("enter second subject marks\n"))
sub3 = int(input("enter third subject marks\n"))

if (sub1<33 or sub2<33 or sub3<33):
    print("yor are fail")
elif(sub1+sub2+sub3)/3 < 40: 
    print("you are fail due to total percentage less than 40")
else:
    print("congratulation you are pass the exam")
   '''

#problem 3
'''

text = input("enter the text")
if("make a lot of money" in text):
    spam = True
elif("buy now" in text):
    spam = True
elif("subscribe this" in text):
    spam = True
else:
    spam = False

if (spam):
    print("this text is spam")
else:
    print("this text is not spam")

'''
#problem 4
'''
username = input("enter your username")
character = len(username)

if(character<10):
    print("username contain less than 10 characters")
else:
    print("username contain 10 or more characters")
'''
# problem 5
'''
names = ["harry", "shubham","rohit", "rohan", "aditi", "shipra"]
name = input ("enter your name to check\n")

if name in names:
    print("your name is present in the list")
else:
    print("your name is not present in the list")
'''

# problem 6
'''
marks = int(input("enter your marks\n"))

if marks >=90:
    grade = "Ex"
elif marks>=80: 
    grade = "A"
elif marks>=70: 
    grade = "B"
elif marks>=60: 
    grade = "C"
elif marks>=50:
    grade = "D"

else:
    grade = "F"

print ("your grade is " + grade)
'''

# program 7

post = ["harry", "onam", "kunal"]
names = ("harry", "Harry", "HaRRy", "HARRY")
if post in names :
    print("name found")
else:
    print("name not found")


Practice 6



# problem 1
'''
num = int(input("Enter the numer"))
for i in range (1, 11):
    print(str(num) + "x" + str(i) + "=" + str(i*num))
    # print(f"{num}x{i}={num*i}") # alternate meathod to do the same thing 
'''

# program 2
# l1 = ["harry","sohan", "sachin", "rahul"]
# for name in l1:
#     if name.startswith("s"):
#         print("hello " + name)

# problem 3 (solve problem 1 using while loop)
# num = int(input("Enter the numer"))
# i = 1
# while i<=10:
#     print(str(num) + "x" + str(i) + "=" + str(i*num))
#     i = i + 1


# problem 4 (Identify prime number)
'''
num = int(input('enter the number: '))
prime = True

for i in range (2, num):
    if (num%i == 0):
        prime = False 
        break
if prime:
    print("This number is a prime number")
else:
    print("This number is not a prime number")
'''


# Progam 5 
# num = int(input("enter number: "))
# sum = 0
# if num <=0:
#     print("Please enter a postive number!")
# else:
#     while num>0:
#         sum = sum + num 
#         num = num - 1
#     print(f"sum of first natural number is {sum}" )



# problem 6 (find out factorial)
# num = int(input("enter number: "))
# factorial = 1
# for i in range (1, num+1):
#     factorial = factorial * i
# print(f"The factorial of {num} is {factorial}")


# Problem 8
# n = 4

# for i in range (4):
#     print("*" * (i+1))

# problem 7
# n = 3
# for i in range (3):
#     print(" " * (n-i-1), end="")
#     print("*" * (2*i+1), end="")
#     print(" " * (n-i-1))

# problem 9
# Try it yourself


# Problem 10
num = int(input("Enter the numer "))
for i in reversed(range (1, 11)):
    print(str(num) + "x" + str(i) + "=" + str(i*num))
    # print(f"{num}x{i}={num*i}")


Practice 7


# problem 1
'''
def maximum(num1, num2, num3):
    if (num1>num2):
        if(num1>num3):
            return num1
        else:
            return num3
    if (num2>num3):
        return num2
    else:
        return num3

m = maximum(5,6,2)
print(m)
'''

# Problem 2
'''
def far(cel):
    return (cel*(9/5))+ 32

c = 37
f = far(c)
print("Fahrenheit Temperature is " + str(f))
'''

# Problem 3 
'''
print("Hello" , end=" ") 
print("How" , end=" ") 
print("Are" , end=" ") 
print("you" , end=" ") 
'''

# Problem 4 sum of first n natural number [formula sum(n)= n + sum(n-1)]
'''
def recursive_sum(n):
    if (n<=0):
        return 0
    return n + recursive_sum(n-1)

s = recursive_sum(2)
print(s)
'''

# Problem 5
'''
n = 3
for i in range(n):
    print("*" * (n-i)) # Print * (n-i) times
'''

# Problem 6  (inch to cm convertor)
'''
def cm(inch):
    return (inch * 2.54)

inch = 2
cm = cm(inch)
print(cm)
'''

# Problem 7
'''
def remove_and_split(string, word):
    newStr = string.replace(word, "")
    return newStr.strip()

this = "   He is good   "
n = remove_and_split(this, "He")
print (n)
'''


# Problem 8  (multiplication table of any number )
#def table (num):
#    for i in range(1,11):
#        print(f"{num}X{i}={num*i}")
    

#num = 5
#table = table(num)
#print (table)



      

Practice 8


# problem 1
'''
f = open('poem.txt')
t = f.read()
if 'Twinkle' in t:
    print("Twinkle is present")
else:
    print("Twinkle is not present")
f.close()
'''


def game():
    return 800

score = game()
with open('highScore.txt') as f:
    highScore = (f.read())

if highScore=='':
    with open('highScore.txt', 'w') as f:
        f.write(str(score))

elif int(highScore) < score:
    with open('highScore.txt', 'w') as f:
        f.write(str(score))

# Multiplication Table 
'''
for i in range(2,21):
    with open(f"Tables/Multiplication table of {i}.txt", 'w') as f:
        for j in range(1,11):
            f.write(f"{i}x{j}={i*j}")
            if j!=10:
                f.write('\n')
           
'''


# Problem 4
'''
with open ('sample.txt') as f:
    content = f.read()

content = content.replace("donkey", "$%@$#")

with open('sample.txt', 'w') as f:
    f = f.write(content)
'''


# Problem 5
'''
words = ["donkey","kaddu", "mote"]

with open('sample.txt') as f:
    content = f.read()

for word in words:
    content = content.replace(word, "$%@$#")
    with open('sample.txt', 'w') as f:
        f= f.write(content)
'''

# Problem 6
'''
with open('sample1.txt') as f:
    content = f.read()

if "python" in content.lower():
    print("yes python is present")

else:
    print("sorry python is not present")
'''

# problem 7
'''
content = True
i = 1
with open('sample1.txt') as f:
    while content:
        content = f.readline()
        if "python" in content.lower():
            print(content)
            print(f"yes python is present on line number {i}")
        i+=1
'''

# Problem 8
'''
with open('sample1.txt') as f:
    content = f.read()

with open('copy.txt', 'w') as f:
    f.write(content)
'''

# problem 9
'''
file1 = 'copy.txt'
file2 = 'sample1.txt'

with open(file1) as f:
    f1 = f.read()

with open(file2) as f:
    f2 = f.read()

if f1==f2:
    print('files are identical')
'''

# problem 10
'''
filename = 'copy.txt'
with open(filename, 'w') as f:
    f.write("")
'''

# problem 11
'''
import os

oldname = 'copy.txt'
newname = 'rename_by_python.txt'
with open(oldname) as f:
    content = f.read()

with open(newname,'w') as f:
    f.write(content)

os.remove(oldname)
'''
      
      
      
      

Practice 9


# Problem 1
'''
class programmer:
    company = "Microsoft"

    def __init__(self,name,product):
        self.name = name
        self.product = product

    def getInfo(self):
        print(f"The name of programmer is {self.name} and their product is {self.product}")

harry = programmer("Harry", "Skype")
alka = programmer("Alka","github" )
harry.getInfo()
alka.getInfo()
'''


# Problem 2
'''
class Calculator:
    def __init__(self,num):
        self.num = num

    def square(self):
        print(f"The square of {self.num} is {self.num **2}")

    def squareroot(self):
        print(f"The squareroot of {self.num} is {self.num **0.5}")

    def cube(self):
        print(f"The cube of {self.num} is {self.num **3}")

a = Calculator(9)
a.square()
a.squareroot()
a.cube()
'''


# Problem 3
'''
class sample:
    a = "harry"

obj = sample()
obj.a = "vikky"
# sample.a = "vikky"
print(sample.a)
print(obj.a)
'''


# Problem 4
'''
class Calculator:
    def __init__(self,num):
        self.num = num

    def square(self):
        print(f"The square of {self.num} is {self.num **2}")

    def squareroot(self):
        print(f"The squareroot of {self.num} is {self.num **0.5}")

    def cube(self):
        print(f"The cube of {self.num} is {self.num **3}")

    @staticmethod
    def greet():
        print("****Hello there welcome to the best calculator service****")

a = Calculator(9)
a.greet()
a.square()
a.squareroot()
a.cube()
'''

# problem 5
'''
class Train:
    def __init__(self,name,fare,seat):
        self.name = name
        self.fare = fare 
        self.seat = seat

    def getStatus(self):
        print('************')
        print(f"The name of the train is {self.name}")
        print(f"The fare of the train is Rs. {self.fare}")
        print(f"The seats available in the train is {self.seat}")
        print("***********")

    def bookTicket(self):
        if (self.seat > 0):
            print(f"Your ticket has been booked! Your seat number is {self.seat}")
            self.seat = self.seat - 1
        else:
            print("Sorry this train is full! Kindly try in tatkal")

intercity = Train("Intercity Express", 90,300)
intercity.getStatus()
intercity.bookTicket()
intercity.getStatus()
intercity.bookTicket()    
intercity.getStatus()
'''
      
      

Practice 10


# Problem 1 
'''
class c2dvec:
    def __init__(self,i,j):
        self.icap = i
        self.jcap = j

    def __str__(self):
        return f"{self.icap}i + {self.jcap}j"

class c3dvec(c2dvec):
    def __init__(self, i, j,k):
        super().__init__(i, j)
        self.kcap = k

    def __str__(self):
        return  f"{self.icap}i + {self.jcap}j + {self.kcap}k"

    
v2d = c2dvec(1,3)
v3d = c3dvec(1,9,7)
print(v2d)
print(v3d)
'''


# Problem 2
'''
class Animal:
    animalType = "mamal"


class Pet:
    color = "white"


class Dog:
    @staticmethod
    def bark():
        print("bow bow!")


d = Dog()
d.bark()
'''

# Problem 3
'''
class Employee:
    salary = 1000
    increment = 1.5

    @property
    def salaryAfterIncrement(self):
        return self.salary * self.increment

    @salaryAfterIncrement.setter
    def salaryAfterIncrement(self,sai):
        self.increment = sai/self.salary

e = Employee()
print(e.salaryAfterIncrement)
print(e.increment)
e.salaryAfterIncrement = 2000
print(e.increment)
'''


# Problem 4
'''
class complex:
    def __init__(self,r,i):
        self.real = r
        self.imaginary = i

    def __add__(self,c):
        return complex(self.real + c.real, self.imaginary + c.imaginary)

    def __mul__(self,c):
        mulReal = self.real * c.real - self.imaginary * c.imaginary
        mulImg = self.real * c.imaginary + self.imaginary * c.real
        return complex(mulReal,mulImg)

    def __str__(self):
        if self.imaginary<0:
            return f"{self.real} - {-self.imaginary}i"
        else:
            return f"{self.real} + {self.imaginary}i"
        

c1 = complex(1,-4)        
c2 = complex(8,5)
print(c1 +c2)
print(c1*c2)
'''


# Problem 5
'''
class vector:
    def __init__(self,vec):
        self.vec = vec

    def __str__(self):
        str1 = ""
        index = 0
        for i in self.vec:
            str1 += f" {i}a{index} +"
            index += 1
        return str1[:-1]

    def __add__(self,vec2):
        newList = []
        for i in range(len(self.vec)):
            newList.append(self.vec[i] + vec2.vec[i])
        return vector(newList)

    def __mul__(self,vec2):
        sum = 0
        for i in range(len(self.vec)):
            sum += (self.vec[i] * vec2.vec[i])
        return sum


v1 = vector([1,4])
v2 = vector([1,6])
print(v1 + v2)
print(v1 * v2)
'''

# Problem 6
'''
class vector:
    def __init__(self,vec):
        self.vec = vec

    def __str__(self):
        return f"{self.vec[0]}i + {self.vec[1]}j + {self.vec[2]}k"


v1 = vector([1,4,6])
v2 = vector([1,6,8])
print(v1)
print(v2)
'''        


# Problem 7
'''
class vector:
    def __init__(self,vec):
        self.vec = vec

    def __str__(self):
        str1 = ""
        index = 0
        for i in self.vec:
            str1 += f" {i}a{index} +"
            index += 1
        return str1[:-1]

    def __add__(self,vec2):
        newList = []
        for i in range(len(self.vec)):
            newList.append(self.vec[i] + vec2.vec[i])
        return vector(newList)

    def __mul__(self,vec2):
        sum = 0
        for i in range(len(self.vec)):
            sum += (self.vec[i] * vec2.vec[i])
        return sum

    def __len__(self):
        return len(self.vec)

v1 = vector([1,4])
v2 = vector([1,6])
print(len(v1))
print(len(v1))
'''

Practice 11


# Problem 1
'''
def readFile(filename):
    try:
        with open(filename, "r") as f :
            print(f.read())
    except FileNotFoundError:
        print(f"file {filename} is not found")

readFile("sample.txt")
readFile("sample1.txt")
readFile("sample2.txt")
'''

# Problem 2
'''
l = [1,2,3,4,5,6,7,8,9,10]
for index, item in enumerate(l):
    if index == 2 or index == 4 or index == 6:
        # print(index,item)
        print(f"The {index+1}th element is {item}")
'''

# Problem 3
'''
num = int(input("Enter number: "))

table = [num*i for i in range(1,11)]

print(table)
'''

# Problem 4
'''
a = int(input("enter number a :"))
b = int(input("enter number b :"))

try:
    print(a/b)
except:
    print("infanite")
'''

# Problem 5
'''
num = int(input("Enter number: "))

table = [num*i for i in range(1,11)]

print(table)
with open("table.txt", "a") as f:
    f.write(str(table))
    f.write('\n')
'''

Comments

Popular posts from this blog

Python chapter 3

Login Page design using Html and CSS only