0% found this document useful (0 votes)
147 views

Python 123455

The document provides examples of code snippets to perform various tasks in Python like swapping variables, calculating areas of shapes, solving quadratic equations, type conversion between Celsius and Fahrenheit, generating random numbers, classifying triangles, defining and evaluating functions, creating a basic calculator, counting even and odd numbers in a range, displaying the Fibonacci sequence, printing patterns using loops, string operations like counting vowels and removing punctuation, checking for palindromes, list operations like summing values and linear search, tuple operations like finding min and max values, set operations, and examples using the random module like generating random numbers and lottery tickets.

Uploaded by

Aayush Singh
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)
147 views

Python 123455

The document provides examples of code snippets to perform various tasks in Python like swapping variables, calculating areas of shapes, solving quadratic equations, type conversion between Celsius and Fahrenheit, generating random numbers, classifying triangles, defining and evaluating functions, creating a basic calculator, counting even and odd numbers in a range, displaying the Fibonacci sequence, printing patterns using loops, string operations like counting vowels and removing punctuation, checking for palindromes, list operations like summing values and linear search, tuple operations like finding min and max values, set operations, and examples using the random module like generating random numbers and lottery tickets.

Uploaded by

Aayush Singh
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/ 11

Swap two variables.

1.Using temp variable


2.Using comma operator
3.Using bitwise XOR operator
Type 1-
x=input("Enter the value of x :")
y=input("Enter the value of y :")
tem=x
x=y
y=tem
print("The value of x after swapping is: ",x)
print("The value of y after swapping is: ",y)
Type 2-
x=input("Enter the value of x :")
y=input("Enter the value of y :")
x,y=y,x
print("The value of x after swapping is: ",x)
print("The value of y after swapping is: ",y)
Type 3-
x=int(input("Enter the value of x :"))
y=int(input("Enter the value of y :"))
x=x^y
y=x^y
x=x^y
print("The value of x after swapping is: ",x)
print("The value of y after swapping is: ",y)

Compute areas of the following (Find the equation and implement in python)
1.Circle
2.Square
3.Sphere
4.Triangle
5.Rectangle
print("Menu")
print("1.CIRCLE")
print("2.SQUARE")
print("3.SPHERE")
print("4.TRIANGLE")
print("5.RECTANGLE")
a=int(input("Enter the choice: "))
if(a==1):
b=int(input("Enter the Radius of the Circle: "))
print(3.14*b*b)
elif(a==2):
c=int(input("Enter the Side of the Square: "))
print(c*c)
elif(a==3):
d=int(input("Enter the Radius of the Sphere: "))
print(4*3.14*d*d)
elif(a==4):
e=int(input("Enter the base of the triangle: "))
f=int(input("Enter the height of the triangle: "))
print(0.5*e*f)
elif(a==5):
g=int(input("Enter the length of the rectangle: "))
h=int(input("Enter the breadth of the rectangle: "))
print(g*h)
else:
print("invalid number")

Solve quadratic equationax2+bx+c=0


a=int(input('Enter the value of a : '))
b=int(input('Enter the value of b : '))
c=int(input('Enter the value of c : '))
print(' Entered equation is ',a,'x^2+',b,'x+',c,'=0',sep=' ')
ro1=(-b+((b**2))-4*a*c)**(1/2)/(2*a)
ro2=(-b-((b**2))-4*a*c)**(1/2)/(2*a)
print('Roots of the equation : ',ro1,'and',ro2)

Convert Celsius to Fahrenheit


cel=int(input('Enter the temperature in celcius: '))
far=cel*(9/5)+32
print('Temperature in farenheit= ',far)

Generate a Random Number using random(), randint(), sample()[import random]


import random
n=random.random()
print('Random number n =',n)

Accept three sides of a triangle and print if the triangle is equilateral, isosceles or scalene.
a=int(input('Enter the side 1: '))
b=int(input('Enter the side 2: '))
c=int(input('Enter the side 3: '))
if(a==b and a==c):
print('The triangle is an equilateral triangle')
elif(a==b or b==c or c==a):
print('The triangle is an isosceles triangle')
else:
print('The triangle is a scalene triangle')

A function f is defined as follows :


f(x)=ax3–bx2+ cx –d, if x > k
=0, if x = k
=-ax3+ bx2–cx +d, if x < k
Write a program that reads a, b, c, d, k and x and prints the value of f(x).
a=int(input("Enter value of a : "))
b=int(input("Enter value of b : "))
c=int(input("Enter value of c : "))
d=int(input("Enter value of d : "))
k=int(input("Enter value of k : "))
x=int(input("Enter value of x : "))
if(x>k):
print(" x>k")
p=a*x**3-b*x**2+c*x-d
print("f(",x,") =",p)
elif(x==k):
print(" x=k")
print("0")
else:
print(" x<k")p=-a*x**3+b*x**2-c*x+d
print("f(",x,") =",p)

Create a calculator.
a=float(input("Enter 1st no. : "))
b=float(input("Enter 2nd no. : "))
choice=input("Enter +, -, *, /, // or % : ")
if(choice=="+"):
c=a+b
print(a,"+",b,"=",c)
elif(choice=="-"):
c=a-b
print(a,"-",b,"=",c)
elif(choice=="*"):
c=a*b
print(a,"*",b,"=",c)
elif(choice=="/"):
c=a/b
print(a,"/",b,"=",c)
elif(choice=="//"):
c=a//b
print(a,"//",b,"=",c)
elif(choice=="%"):
c=a%b
print(a,"%",b,"=",c)
else:
print("Wrong choice!")

Count the number of even and odd numbers from a series of numbers 5 to 100 using for and
range().
even_count,odd_count=0,0
x=range(5,100)
for num in x:
if num%2==0:
even_count +=1
else:
odd_count +=1
print("Even numbers in the list:",even_count)
print("Odd numbers in the list:",odd_count)

Display the Fibonacci sequence up to nth term where n is provided by the user (use while loop).
n = int(input("Enter number of terms: "))
n1,n2 = 0, 1
i=0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n)
print(n1)
else:
print("Fibonacci sequence:")
while(i<n):
print(n1)
sum = n1 + n2
n1 = n2
n2 = sum
i += 1

Print the following pattern using nested loop.


*
***
*****
***
*
for x in range(3):
print(" " * (3 -x), "*" * (2*x + 1))
for x in range(3 -2, -1, -1):
print(" " * (3 -x), "*" * (2*x + 1))

Write a program to count the number of each vowel in a string


str=input("enter a string")
c=0
vowel=set("aeiouAEIOU")
for alphabet in str:
if alphabet in vowel:
c=c+1
print("No. of vowels :",c)

Write a program to remove all punctuation from the string provided by the user punctuations =
'''!()-[]{};:'"\,<>./?@#$%^&*_~''‘
p='''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
str=input("Enter a string: ")
c=""
for char in str:
if char not in p:
c=c+char
print(c)

Write a program to check if the given string is Palindrome or not?


x = input("Enter the string ")
w = ""
for i in x:
w=i+w
if (x == w):
print("Yes")
else:
print("No")

Sum all the items in a list.


my_list = [10,11,12,13]
total = 0
l=my_list
for val in l:
total = total + val
print ("The sum of my_list is",total)

Implement Linear Search using List.


l=[1, 2,"Aayush",4,"Adarsh",6]
n="Aayush"
for i in range(len(l)):
if l[i]==n:
print("Found")
else:
continue

Demonstrate list operations.


list1=[]
n1=int(input("enter the number of elements in the list 1-"))
for i in range(0,n1):
list1.append(input("enter the items in list 1-"))
print("printing the list 1 items-")
for i in list1:
print(i,end=' ')
print()
list2=[]
n2=int(input("enter the number of elements in the list 2-"))
for i in range(0,n2):
list2.append(input("enter the items in list 2-"))
print("printing the list 2 items-")
for i in list2:
print(i,end=' ')
print()
print("repetition operator: ")
i=list1*2
print(i)
print()
print("concentate: ")
i=list1+list2
print(i)
i=len(list1)
print()
print("The length of List 1")
print(i)
print("elements of list 1 printed in vertical: ")
for i in list1:
print(i)
Create a tuple, and find the minimum and maximum number from it.  
tup = (10, 40, 20, 50, 30)
min_num = min(tup)
max_num = max(tup)
print("The given tuple is:", tup)
print("Minimum number in the tuple:", min_num)
print("Maximum number in the tuple:", max_num)

Find the repeated items of a tuple. 


Print the number in words for Example: 1234 => One Two Three Four 
num = input("Enter a number: ")
num_str = str(num)
word_dict = {
'0': 'Zero',
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
'5': 'Five',
'6': 'Six',
'7': 'Seven',
'8': 'Eight',
'9': 'Nine'
}
for digit in num_str:
print(word_dict.get(digit, 'Invalid digit'), end=" ")

Create a set, add member(s) in a set and perform following operations: intersection of sets, union
of sets, set difference, symmetric difference, clear a set. 
set1 = {1, 2, 3, 4}
set1.add(5)
set1.update([6, 7, 8])
print("set1 after adding members: ", set1)
set2 = {3, 4, 5, 6}
print("intersection of set1 and set2: ", set1.intersection(set2))
print("union of set1 and set2: ", set1.union(set2))
print("set difference of set1 and set2: ", set1.difference(set2))
print("symmetric difference of set1 and set2: ", set1.symmetric_difference(set2))
set1.clear()
print("set1 after clearing all elements: ", set1) 

Find length, maximum and the minimum value in a set.  


s = {3, 7, 1, 9, 2, 8, 5}
length = len(s)
print("The length of the set is:", length)
maximum = max(s)
print("The maximum value in the set is:", maximum)
minimum = min(s)
print("The minimum value in the set is:", minimum)
Apply set function to find the count of number of vowels in a given string. 
def count_vowels(input_str):
input_str = input_str.lower()
vowels = set('aeiou')
count = 0
for char in input_str:
if char in vowels:
count += 1
return count
input_str = "Hello, World!"
count = count_vowels(input_str)
print("The number of vowels in the input string is:", count)

generate 3 random integers between 100 and 999 which is divisible by 5


import random
numbers = []
while len(numbers) < 3:
num = random.randint(100, 999)
if num % 5 == 0 and num not in numbers:
numbers.append(num)
print(numbers)

random lottery pick. generate 100 random lottery tickets and pick two lucky ticketes
from it as a winner
import random
lottery_tickets = []
for i in range(100):
lottery_tickets.append(random.randint(1000, 9999))
winning_tickets = random.sample(lottery_tickets, 2)
print("The two lucky lottery tickets are:")
for ticket in winning_tickets:
print(ticket)

probablity of heads and tails while flipping a coin for 100 times
import random
def coin_toss(n):
heads = 0
tails = 0
for i in range(n):
result = random.randint(0, 1)
if result == 0:
heads += 1
else:
tails += 1
return heads/n, tails/n
if __name__ == '__main__':
n = 100
heads_prob, tails_prob = coin_toss(n)
print(f"The probability of getting heads is {heads_prob:.2f}")
print(f"The probability of getting tails is {tails_prob:.2f}")
remove the random name from list
import random
names = ['Alice', 'Bob', 'Charlie', 'David', 'Emily']
random_index = random.randint(0, len(names) - 1)
random_name = names.pop(random_index)
print('Removed name:', random_name)
print('Remaining names:', names)

get the same number again and again using random module
import random
random.seed(42)
print(random.random())

create strong password


import random
import array
MAX_LEN = 12
DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z']
UPCASE_CHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z']
SYMBOLS = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>',
'*', '(', ')', '<']
COMBINED_LIST = DIGITS + UPCASE_CHARACTERS + LOCASE_CHARACTERS +
SYMBOLS
rand_digit = random.choice(DIGITS)
rand_upper = random.choice(UPCASE_CHARACTERS)
rand_lower = random.choice(LOCASE_CHARACTERS)
rand_symbol = random.choice(SYMBOLS)
temp_pass = rand_digit + rand_upper + rand_lower + rand_symbol
for x in range(MAX_LEN - 4):
temp_pass = temp_pass + random.choice(COMBINED_LIST)
temp_pass_list = array.array('u', temp_pass)
random.shuffle(temp_pass_list)
password = ""
for x in temp_pass_list:
password = password + x
print(password)

print a table of number entered by the user using while loop


table =int(input("Enter the table :"))
start =int(input("Enter the starting number : "))
limit =int(input("Enter the limit :"))
while(start<=limit):
print(start,"*",table,"=",start*table)
start=start+1

write a python program to print even numbers between 1 to n using while loop
start, end = 1, 100
for num in range(start, end + 1):
if num % 2 == 0:
print(num, end = " ")

check number entered is prime or not using while loop


flag = 0
n = int(input('\nEnter whole number to check : '))
i=2
while i <= (n/2):
if (n%i) == 0:
flag = 1
break
else:
i += 1
if n == 1:
print('1 is neither prime nor composite')
elif flag == 0:
print(n,' is a prime number.')
elif flag == 1:
print(n,' is not a prime number.')

fibonacci series up to n terms


n = int(input("Enter the value of 'n': "))
a=0
b=1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a=b
b = sum
sum = a + b

squares of numbers from 1 to n


n=1
while n <= 5:
print (n, '\t', n ** 2)
n += 1

sum of squares of numbers from 1 to n


i,sum = 1,0
n = int(input('Enter the number: '))
while i<2*n:
sum += i*i
i += 2
print('Sum of squares of first',n,'odd natural numbers is',sum)

the cubes of numbers from 1 to n


n = 10
i=1
sum = 0
while(i <= n):
sum += i**3
i += 1
print("Sum is:", sum)

the sum cubes of numbers from 1 to n


def sumOfSeries(n):
sum = 0
for i in range(1, n+1):
sum +=i*i*i
return sum
n=4
print(sumOfSeries(n))

Sum of odd numbers


maximum = int(input(" Please Enter the Maximum Value : "))
Oddtotal = 0
for number in range(1, maximum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, Oddtotal))

Sum of even numbers


maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
number = 1
while number <= maximum:
if(number % 2 == 0):
print("{0}".format(number))
total = total + number
number = number + 1
print("The Sum of Even Numbers from 1 to N = {0}".format(total))

Reverse order of a number


num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))

Factorial
print("Enter the Number: ")
num = int(input())
fact = 1
i=1
while i<=num:
fact = fact*i
i = i+1
print("\nFactorial =", fact)

Armstrong Number
num = int(input("Enter a number: "))
sum = 0
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")

Sum until enter 0


Sum = 0
print("Please Enter 10 Numbers\n")
for i in range(1, 11):
num = int(input("Number %d = " %i))
if num < 0:
break
Sum = Sum + num
print("The Sum of Positive Numbers = ", Sum)

You might also like