0% found this document useful (0 votes)
197 views34 pages

Introduction To Phyton

The document contains 27 code snippets demonstrating various Python programming concepts. The snippets include: 1) Displaying personal details with formatting, 2) Calculating the sum of two numbers, 3) Taking user input to add two numbers. Most snippets demonstrate a Python concept, take user input, perform calculations, and display output.

Uploaded by

karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views34 pages

Introduction To Phyton

The document contains 27 code snippets demonstrating various Python programming concepts. The snippets include: 1) Displaying personal details with formatting, 2) Calculating the sum of two numbers, 3) Taking user input to add two numbers. Most snippets demonstrate a Python concept, take user input, perform calculations, and display output.

Uploaded by

karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

KARAN PAREKH 18EC054

Introduction to Phyton:

1.WAP to display basic details of a User like Name, Roll no, Division and
Address.

CODE:-
def personal_details():
Name = "Karan"
Rollno = "18EC054"
Division = "EC-1"
Address = "Jamnagar, Gujarat, India"
print("Name: {}\nRollno: {}\nDivision: {}\nAddress: {}".format(Name,
Rollno, Division, Address))
personal_details()

OUTPUT:

2. Summation of two given number.

CODE:-
val1 = 178.35
val2 = 36.92

sum = float(val1) + float(val2)

print("The sum of given numbers is: ", sum)

OUTPUT:-

3.Add two number which are provided by user input

CODE:-
num1 = 45
num2 = 12
sum = num1 + num2
print("The sum is :", sum)

CSPIT(EC)
KARAN PAREKH 18EC054

OUTPUT:-

4.Find square root of a number provided by user input

CODE:-
num = 40

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

OUTPUT:-

5. Simple interest formula is given by:


Simple Interest = (P x T x R)/100 Where, P is the principle amount T is the time
and R is the rate (principal amount and Tenure should be user input).

CODE:-
principal = 0
rate = 0.6
time = 0
print('Enter Principal Amount: ')
principal = int(input())
print('Enter Tenure in Years: ')
time = int(input())
simple_interest = (principal * rate * time)/100
print('Simple Interest: ', simple_interest)

OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

6. Find time from a given frequency (t=1/f)

CODE:-
print('Enter Frequency: ')
frequency = int(input())
time = 1/frequency
print('Required Time: ', time)

OUTPUT:-

7. Write a program to find area of a sphere and circle

CODE:-
import math
print('Enter Radius: ')
rad = int(input())
circle_area = math.pi * rad * rad;
sphere_area = (4/3) * math.pi * rad*rad*rad
print('Area of circle: ', circle_area)
print('Area of sphere: ', sphere_area)

OUTPUT:-

8. Check number is positive or negative


CODE:-
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
else:
print("Negative number")

CSPIT(EC)
KARAN PAREKH 18EC054

OUTPUT:-

9. Print 8 blank lines


CODE:-
print('Start')
print('')
print('')
print('')
print('')
print('')
print('')
print('')
print('')
print('End')

OUTPUT:-

10.Store a message in a variable, and then print that message.


CODE:-
message = input("Enter the message:") #taking the message
print("The message:",message)
OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

11.Store a message in a variable, and print that message. Then change the value
of your variable to a new message, and print the new message.
CODE:-
message = "how are you" #storing the message
print("The message:",message) #printing the message
message = "I'm fine" #storing the new message
print("The message:",message)
OUTPUT:-

12. Convert number of days into months and years.


CODE:-
days = int(input("Enter no of days:")) #taking no of days
M = days/30 #calculating no of months
Y = days/365 #calculating no of years
print("Months:",round(M)) #printing months and years
print("Years:",round(Y))
OUTPUT:-

13. Develop a program that computes the body mass index (BMI) of an
individual. Program should begin by reading a height and weight from the user.
If you read the height in centimeters then need to convert it in meters and the
weight in kilograms.

CSPIT(EC)
KARAN PAREKH 18EC054

CODE:-

W = float(input("Enter our weight in KG:")) #taking hight and weight of user


H = float(input("Enter our hight in M:"))
bmi = W/(H*H) #calculating bmi
if bmi <18.5: #'if' and 'elif' for bmi
conditioning
print("you are Underweight with BMI of:",round(bmi,2) ,"kg/m2") #printing
the status according to the bmi
elif bmi >18.5 and bmi<25 :
print("your weight is normal with BMI :",round(bmi,2) ,"kg/m2")
else :
print("you are Overerweight with BMI :",round(bmi,2) ,"kg/m2")

OUTPUT:-

14. Store the names of a few of your friends in a list called names. Print each
person’s name by accessing each element in the list, one at a time.
CODE:-
names = ['yash', 'meet', 'rushi']
print(names[0])
print(names[1])
print(names[2])
OUTPUT:-

15.Start with the list you used in above example, but instead of just printing
each person’s name, print a message to them. The text of each message should
be the same, but each message should be personalized with the person’s name

CSPIT(EC)
KARAN PAREKH 18EC054

CODE:-
names = ["rushi","meet","yash","ankit"] #list of friends
for i in names: #for loop for individual name accessing
print("Friend name is:",i,"\n")
OUTPUT:-

16. Think of your favorite mode of transportation, such as a motorcycle or a car,


and make a list that stores several examples. Use your list to print a series of
statements about these items, such as “I would like to own a Honda
motorcycle.”
CODE:-
transportation = ["airoplane","motorcycle","cycle", #list of transportation
"car","yot"]
for i in transportation: #for loop for whole list
if transportation[0]==i:
print("I always travel in A class in airoplane") #printing statements for
each mode
print("I would like to own a airoplane")
print("I don't like all airoplanes services\n")
elif transportation[1]==i:
print("I would like to own a Honda motorcycle")
print("My motorcycle is very coastly")
print("my motorcycle is only single seater\n")
elif transportation[2]==i:

CSPIT(EC)
KARAN PAREKH 18EC054

print("My cycle is very coastly")


print("I would like to own a cycle")
print("my cycle is only single seater\n")
elif transportation[3]==i:
print("I would like to own a Honda car")
print("My car is very coastly")
print("my car is only two seater\n")
else:
print("I have a yot which is very coastly")
print("my yot consist of two floars")
print("I would like to own a yot\n")
OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

17.Write a program in python that reads a number of feet from the user,
followed by a number of inches. After that program should compute and display
the equivalent number of centimeters.
CODE:-
foot = float(input("Enter the no of foot:")) #taking foots and inches
inches = float(input("Enter the no of inches:"))
inches += 12*foot #computing foots and inches in CM
CM = inches*2.54
print("No of centimeters:",CM,"cm") #printing CM value
OUTPUT:-

18.Write a program to create dictionary (key is roll number and value is student
name). Print it by key
CODE:-
dic = {1:'Ankit' ,2:'rushi' ,3:'Meet' ,4:'Jay'} #creating dictionary
for i in dic: #for printing every element of dictionary
using keys
print(dic.get(i))
OUTPUT:-

19.Print your name in forward and reverse order(using slicing list)


CODE:-
def reverse_slicing(s):
return s[::-1]
input_str = 'KARAN'

CSPIT(EC)
KARAN PAREKH 18EC054

if __name__ == "__main__":
print(input_str)
print('Reverse String using slicing =', reverse_slicing(input_str))

OUTPUT:-

20. Convert list in to string List=['a', 'b', 'c', 'd'] String=abcd.


CODE:-
def convert(s):

new = ""
for x in s:
new += x
return new
s = ['a', 'b', 'c', 'd']
print(convert(s))

OUTPUT:-

21.Append one string to another str1= Fal str2=guni str3 should be Falguni

CODE:-
test_string ="Fal"
add_string = "guni"

print("The str1 is : " + str(test_string))


print("The sre2 is : " + str(add_string))
test_string += add_string

print("The str3 is : " + test_string)

OUTPUT:-

22. Write a program to find magnitude and phase of complex characteristic


impedance (Z0=50+j50)

CSPIT(EC)
KARAN PAREKH 18EC054

CODE:-
import cmath, math, numpy
c1 = 50 + 50j
print('Magnitude: ', abs(c1))
print('Phase: ', cmath.phase(c1))
print('Phase in Degrees: ', numpy.degrees(cmath.phase(c1)))

OUTPUT:-

23.Calculate W and L for (f=2.4GHz, ℇr=2.32, h=0.16cm)

CODE:-
f = 2.4*(10**9) #calculations
r = 2.32
h = 0.16
c = 3*(10**8)
w = c/(2*f*(((r+1)/2)**(-1/2)))
e = (r+1)/2 + ((r-1)/2)*((1+10*h/w)**(-1/2))
l = c/(2*f*(e**1/2))
D = h/(e**1/2)
L = l-2*D
print("Value of W and L is:",round(w,2),"and",round(L,2)) #printing values of
W and L

OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

24.Write a program to calculate SWR and T


¿)
ZL−Z 0
(T= ZL+ Z 0 ))
(ZL=50+j50, Z0=50)

CODE :-
ZL=50+50j #initializing the given values
ZO=50
T=(ZL-ZO)/(ZL+ZO) #calculation for T
SWR=(1+T)/(1-T) #calculation for SWR
print("Values of SWR and T is:",SWR,",",T) #printing the values of SWR and
T

OUTPUT :-

25.WAP to print Multiplication Table.

CODE:-
num = 25

for i in range(1, 11):


print(num, 'x', i, '=', num*i)

OUTPUT:-

26.Adding two binary number.

CODE:-
num1 = '00001'

CSPIT(EC)
KARAN PAREKH 18EC054

num2 = '10001'

sum = bin(int(num1,2) + int(num2,2))


print(sum)

OUTPUT:-

27.Swap Two Variables

CODE:-
x = 158
y = 108

temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

OUTPUT:-

28.Simple calculator (add, subtract, multiplication, division)

CODE:-
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")

CSPIT(EC)
KARAN PAREKH 18EC054

print("4.Divide")

choice = input("Enter choice(1/2/3/4): ")

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))

if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':


print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':


print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':


print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

OUTPUT:-

29. Scientific calculator

CODE:-
import math #to import math

CSPIT(EC)
KARAN PAREKH 18EC054

cal=""
while cal!="close": #for countineous use of cal
suff=""
pre=""
base=2.72
op=""
suff = input("suffix:") #fetching suffix
if suff=="sin" or suff=="cos" or suff=="tan":
pre=input("enter -1 for inverse ortherwise skip:")
if suff == "log":
base=int(input("Base:"))
num1 = float(input("Enter first number:")) #taking num1 and num2
if suff == "":
op = input("Enter the operation :") #taking operation for num
if op == '^' or op == '+' or op == '-' or op == '*' or op == '/':
num2 = float(input("Enter second number:"))
if (suff=="sin" or suff=="cos" or suff=="tan") and pre=="":
num1=num1*math.pi/180 #converting degree to radian
if op == '+': #'if' and 'elif' statement for different operation
out = num1 + num2 #calculating the operation selected
print("=",out) #printing result by calculation
elif op == '-':
out = num1 - num2
print("=",out)
elif op == '*':
out = num1 * num2
print("=",out)
elif op == '/':
out = num1 / num2
print("=",out)
elif op == '^':
out = num1 ** num2
print("=",out)
elif suff=="sin": #calculation for sin,cos,tan and invers
if pre=="-1":
out = math.asin(num1)
print("=",out*180/math.pi)
else:
out = math.sin(num1)
print("=",out)
elif suff=="cos":
if pre=="-1":
out = math.acos(num1)

CSPIT(EC)
KARAN PAREKH 18EC054

print("=",out*180/math.pi)
else:
out = math.cos(num1)
print("=",out)
elif suff=="tan":
if pre=="-1":
out = math.atan(num1)
print("=",out*180/math.pi)
else:
out = math.tan(num1)
print("=",out)
elif suff=="log" : #calculation for log
if base==2.72:
out = math.log(num1)
else:
out = math.log(num1,base)
print("=",out)
else:
print("syntax error") #for for syntax error
cal=input("Write close to close the calculator :") #to close the loop

OUTPUT:-

Flow Control-

1.Find greater number out of two number given by user

CODE:-
num1=int(input("enter the first number:"))
num2=int(input("enter the second number:"))
if num1>=num2:
large=num1
else:
large=num2

CSPIT(EC)
KARAN PAREKH 18EC054

print("the greater number is:",large)

OUTPUT:-

2.Find (user given) number is odd or even

CODE:-
num = 47
if (num % 2) == 0:
print("num is even",(num))
else:
print("num is odd",(num))

OUTPUT:-

3.Find (user given) number is positive or negative

CODE:-
num= 66
if num > 0:
print("positive number")
else:
print("negative number")

OUTPUT:-

4.Print "A" if a is greater than b.

CODE:-
a=100
b=120
if b>a:
print(" A")
else:
print(" B")

CSPIT(EC)
KARAN PAREKH 18EC054

OUTPUT:-

5.Print "a is not equal to b" if a is not equal to b.

CODE:-

6.Print "Yes" if a is equal to b, otherwise print "No".

CODE:-
a=100
b=100
if a==b:
print(" YES")
else:
print(" NO")

OUTPUT:-

7.Print "1" if a is equal to b, print "2" if a is greater than b, otherwise print "3".

CODE:-
a = input("Enter value of 'a':") #fetching the value of a and b
b = input("Enter value of 'b':")
if a==b: #comparision
print("1") #printing given statement
elif a>b:
print("2")
else:
print("3")

OUTPUT:-

8.Print "Hello" if a is equal to b, and c is equal to d.

CSPIT(EC)
KARAN PAREKH 18EC054

CODE:-
a = input("Enter value of 'a':") #fetching the value of a and b
b = input("Enter value of 'b':")
c = input("Enter value of 'c':") #fetching the value of c and d
d = input("Enter value of 'd':")
if a==b and c==d: #comparision
print("Hello") #printing given statement

OUTPUT:-

9.Print "Hello" if a is equal to b, or c is equal to d.

CODE:-
a = input("Enter value of 'a':") #fetching the value of a and b
b = input("Enter value of 'b':")
c = input("Enter value of 'c':") #fetching the value of c and d
d = input("Enter value of 'd':")
if a==b or c==d: #comparision
print("Hello") #printing given statement

OUTPUT:-

10. Prepare grade sheet. For each of following subjects the marks should be
given by user and grades should be calculated according to the given table and
grade should be displayed for each subject. The list of subject is
1. RF & Microwave
2. Python
3. Antenna

CSPIT(EC)
KARAN PAREKH 18EC054

4. Microwave Integrated circuit

CODE:-

subjects = ["RF & Microwave" ,"Python", "Antenna", #subjects

"Microwave Integrated circuit"]

M = [0,0,0,0]

print("1.RF & Microwave 2.Python 3.Antenna 4.Microwave Integrated circuit")


#printing subjects

for j in range(0,4):

print("Enter marks for subject:",subjects[j])

M[j] = int(input()) #fetching marks

for i in range(0,4):

if M[i]>=80: #calculating grades

print(subjects[i]," grade :AA") #printing apropriate grades

elif M[i]<80 and M[i]>=75:

print(subjects[i]," grade :AB")

elif M[i]>=70 and M[i]<75:

print(subjects[i]," grade :BB")

elif M[i]>=65 and M[i]<70:

print(subjects[i]," grade :BC")

elif M[i]>=60 and M[i]<65:

print(subjects[i]," grade :CC")

elif M[i]>=55 and M[i]<60:

print(subjects[i]," grade :CD")

elif M[i]>=50 and M[i]<55:

CSPIT(EC)
KARAN PAREKH 18EC054

print(subjects[i]," grade :DD")

else:
print(subjects[i]," grade :FF")

OUTPUT:-

11.WAP to prompt the user for hours and rate per hour to compute gross pay.
Company will give the employee 1.5 times the Hourly rate for hours worked
above 40 hours.

CODE:-

hours = float(input("Enter the no of working hours :")) #fetching hours and rate

rate = float(input("Enter the hourly rate:RS "))

gross = rate*hours #calculation for gross

if hours>=40: #printing the gross if hours is 40

print("Your gross amount :",round(gross,2))

else:
print("Minimum 40 hours is required")

OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

12. Add 1 to 100 number using for loop

CODE:-

result = 0 #initialising result

for i in range(100): #for loop for addition

result+=i
print("Result is:",result) #printing result

OUTPUT:-

13.Create list i=[1,’two,3,’four’,5,’six’,7,’eight’,9] and print it using for loop

CODE:-

i_list=[1,"TWO",3,"FOUR",5,"SIX",7,"EIGHT",9]

for i in i_list:
print(i)

OUTPUT:-

14.Print 1 to 100 using for loop

CODE:-

CSPIT(EC)
KARAN PAREKH 18EC054

for i in range(1,101): #for loop for printing


print("Result is:",i) #printing result

OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

CSPIT(EC)
KARAN PAREKH 18EC054

15.Print odd number 1 to 100 using for loop

CODE:-
for number in range(1, 100):
if(number % 2 != 0):
print("{0}".format(number))

OUTPUT:-

16.Print even number 1 to 100 using for loop

CODE:-
for number in range(1, 100):
if(number % 2 == 0):
print("{0}".format(number))

OUPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

17.Print 1 to 100 in steps of 5 using for loop

CODE:-
for i in range(1,21): #for loop for printing
print("Result is:",i*5) #printing result

OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

18. Print following using for loop


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

CODE:-
print("Second Number Pattern ")
lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=' ')
print("")

OUTPUT:-
Second Number Pattern

CSPIT(EC)
KARAN PAREKH 18EC054

19. Print following using for loop


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

CODE:-
for num in range(6):
for i in range(num):
print (num, end=" ")

print("\n")

OUTPUT:-

20. Print following using for loop


*
* *
* * *
* * * *
* * * * *

CODE:-
rows = input("Enter number of rows ")
rows = int (rows)

for i in range (0, rows):

CSPIT(EC)
KARAN PAREKH 18EC054

for j in range(0, i + 1):


print("*", end=' ')

print("\r")

OUTPUT:-

21. Print following


*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

CODE:-
rows = input("Enter max star to be display on single line")
rows = int (rows)
for i in range (0, rows):
for j in range(0, i + 1):
print("*", end=' ')
print("\r")

for i in range (rows, 0, -1):


for j in range(0, i -1):
print("*", end=' ')
print("\r")

OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

22. Print i as long as i is less than 6: (use while loop)

CODE:-
i = 10
while i>6: #while loop use
print(i) #printing value of i
i-=1

OUTPUT:-

23. Stop the loop if i is 3. (start with i=1) (use while loop)

CODE:-
i=1
while i!=3: #while loop use
print(i) #printing value of i
i+=1

OUTPUT:-

24. Check given number is Armstrong number

CODE:-
num = int(input("Enter a number: "))
sum = 0

CSPIT(EC)
KARAN PAREKH 18EC054

temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

OUTPUT:-

25.Print the word ‘hello’ indefinitely because the condition will always be true.

CODE:-
a=0
while a>=0: #while loop for indefinite loop
print("Hello") #printing hello
a+=1

OUTPUT:-

CSPIT(EC)
KARAN PAREKH 18EC054

26. Print the pattern ‘G’.

CODE:-
def Pattern(line):
pat=""
for i in range(0,line):
for j in range(0,line):
if ((j == 1 and i != 0 and i != line-1) or ((i == 0 or
i == line-1) and j > 1 and j < line-2) or (i == ((line-1)/2)
and j > line-5 and j < line-1) or (j == line-2 and
i != 0 and i != line-1 and i >=((line-1)/2))):

CSPIT(EC)
KARAN PAREKH 18EC054

pat=pat+"*"
else:
pat=pat+" "
pat=pat+"\n"
return pat

line = 7
print(Pattern(line))

OUTPUT:-

27. Inverted Star Pattern

CODE:-

n=7

for i in range (n, 0, -1):


print((n-i) * ' ' + i * '*')

OUTPUT:-

28. Sum of the numbers from 1 to 100 using while loop

CODE:-

x = 100 #for sum of 1 to 100

sum = 0 #to store the result

while x>=0: #while loop for calculation

CSPIT(EC)
KARAN PAREKH 18EC054

sum+=x

x-=1
print("Sum of 1 to 100 is:",sum) #to print the summation

OUTPUT:-

CSPIT(EC)

You might also like