0% found this document useful (0 votes)
27 views12 pages

Mids Final Practice

The document contains various Python programs demonstrating input/output functions, control flow, loops, data types, and functions. It includes examples for checking numbers, determining leap years, finding the largest number, and performing arithmetic operations. Additionally, it covers creating and manipulating lists, tuples, sets, and directories.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views12 pages

Mids Final Practice

The document contains various Python programs demonstrating input/output functions, control flow, loops, data types, and functions. It includes examples for checking numbers, determining leap years, finding the largest number, and performing arithmetic operations. Additionally, it covers creating and manipulating lists, tuples, sets, and directories.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#Input/ Output Functions

#Write a pyhton program that takes a number as input and checks


whether it is positive, negative or zero.
number = int(input("Enter a number:"))
if number>0:
print("Number is positive")
elif number<0:
print("Number is negative")
else:
print("Number is zero")

#OUTPUT

Enter a number: 65

Number is positive

#Write a program to check if the year is leap or not.


year = int(input("Enter a year:"))
if year % 4 ==0 and year % 100 !=0 and year% 400 == 0:
print("IT IS A LEAP YEAR.")
else:
print ("Not a leap year.")

#OUTPUT

Enter a year: 2024

Not a leap year.

#Take three numbers as input and find the largest number using if-
elif-else.
no1 = int(input("Enter first number:"))
no2= int(input("Enter second number:"))
no3= int(input("Enter third number:"))
if no1>no2 and no1>no3:
print("First number is largest.")
elif no2>no1 and no2>no3:
print ("Second number is largest.")
else:
print("Third number is largest.")

#OUTPUT

Enter first number: 54


Enter second number: 52
Enter third number: 87

Third number is largest.

#Check if a number is even, odd or multiple of 5.


num = int(input("Enter a number:"))
if num%2==0:
if num%5==0:
print("Number is even and multiple of 5")
else:
print("Number is even") #This program
is checking both multiple of 5 and whether it's even or odd at the
same time.
elif num%2!=0:
if num%5==0:
print("Number is odd and multiple of 5.")
else:
print("Number is odd.")

#OUTPUT

Enter a number: 55

Number is odd and multiple of 5.

#Check if a number is even, odd or multiple of 5.


num= int(input("Enter a number:"))
if num% 5 == 0:
print("Number is a multiple of 5.") #This program is checking
only one possiblity whether it's even odd or multiple of 5.
elif num %2 == 0:
print ("Number is even")
else:
print("Number is odd.")

#OUTPUT

Enter a number: 55

Number is a multiple of 5.

#Write a pyhton program for admission eligibility. A student is


eligible for admission if: The students math marks > or equal to 60,
physics marks > or
# equal to 50 and chemistry marks are greater than or equal to 40. Or
the total of all three subjects is 200.
math= int(input("Enter your math marks:"))
chem= int(input("Enter your chemistry marks:"))
phy= int(input("Enter your physics marks"))
total= math+phy+chem
if (math>=60 and phy>=50 and chem>=40) or total >=200:
print("You are eligible for admission.")
else:
print("Sorry, You are not eligible for admission.")

#OUTPUT
Enter your math marks: 65
Enter your chemistry marks: 76
Enter your physics marks 87

You are eligible for admission.

#Write a python program that takes a color input(red, yellow or green)


and prints what a driver should do.
color= input("Enter color (Red, yellow, green.):")
if color == 'red':
print("STOP!")
elif color == 'green':
print(" You can Move.")
elif color == 'yellow':
print("Ready to halt")
else:
print("Invalid color.")

#OUTPUT

Enter color (Red, yellow, green.): red

STOP!

#loop and Iterations

# Write a program to print numbers from 1 to 10 using a for loop.


for i in range(1,11):
print(i)

#OUTPUT

1
2
3
4
5
6
7
8
9
10

#Display all even numbers between 1 and 50.


for i in range(2, 51, 2):
print(i)

#OUTPUT

2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50

#Sum of first n Natural [Link] an integer n from user and find


the sum of all the numbers from 1 to n.
num= int(input("Enter a number:"))
sum = 0
for i in range(1, num+1):
sum +=i
print ("Sum:", sum)

#OUTPUT

Enter a number: 11

Sum: 66

#Print numbers from 10 down to 1 using a loop.


for i in range(10, 0,-1):
print(i)

#OUTPUT

10
9
8
7
6
5
4
3
2
1

# Take a number n and calculate the sum of even and odd numbers
separately.
n = int(input("Enter a number:"))
even_sum = 0
odd_sum = 0
for i in range(1, n+1):
if i %2 == 0:
even_sum +=i
else:
odd_sum +=i
print("Even sum:", even_sum)
print("Odd sum:", odd_sum)

#OUTPUT

Enter a number: 65

Even sum: 1056


Odd sum: 1089

#Check whether a given number is prime or not.


n = int(input("Enter a number:"))
prime = True
for i in range(2, int(n**0.5) +1):
if n % i == 0:
prime = False
break
if prime:
print(n, "is prime")
else:
print(n, "is not a prime")

#OUTPUT

Enter a number: 54

54 is not a prime

#Print the following pattern


# *
# **
# ***
# ****
# *****
for i in range(1, 6):
print("*" * i)
#OUTPUT

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

#DATA TYPES AND TUPLES

# Write a program that takes two integers and prints their sum,
difference, product and quortient.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)

if b != 0:
print("Quotient:", a / b)
else:
print("Cannot divide by zero")

#OUTPUT

Enter first number: 5


Enter second number: 11

Sum: 16
Difference: -6
Product: 55
Quotient: 0.45454545454545453

#Create a list of favorite movies. 1) print the list . 2) Add one


movie . 3) Remove one movie. 4) Display the final list

movies = ["Harry Potter", "Twilight", "Avengers", "Coco", "Frozen"]

print("Original List:", movies)

# Add a movie
[Link]("Moana")

# Remove a movie
[Link]("Frozen")

print("Final List:", movies)

#OUTPUT
Original List: ['Harry Potter', 'Twilight', 'Avengers', 'Coco',
'Frozen']
Final List: ['Harry Potter', 'Twilight', 'Avengers', 'Coco', 'Moana']

#Create a tuple of 5 numbers. 1) Display the first and last elements.


2) Print a slice of the tuple. 3) Try modifying one value and observe
the eroor.

numbers = (10, 20, 30, 40, 50)

print("First element:", numbers[0])


print("Last element:", numbers[-1])

# Slice
print("Slice (2nd to 4th):", numbers[1:4])

# Trying to modify value (this will give an error)


#numbers[0] = 100
# Uncomment the upper line to see error

#OUTPUT

First element: 10
Last element: 50
Slice (2nd to 4th): (20, 30, 40)

# Create a dictionary for a student with keys: name, roll no, and
marks. Print each value using its key.

student = {
"name": "Umm-e-farwa Hanif",
"roll no": 5,
"marks": 89
}

print("Name:", student["name"])
print("Roll No:", student["roll no"])
print("Marks:", student["marks"])

#OUTPUT

Name: Umm-e-farwa Hanif


Roll No: 5
Marks: 89

#Write a program to create two sets and finds their union and
intersection.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print("Union:", [Link](set2))
print("Intersection:", [Link](set2))

#OUTPUT

Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}

# Write a program that takes a tuple of numbers and prints: 1)


Maximum value. 2) Minimium value. 3) Sum of all numbers.

# Reset built-in functions if they were overwritten


try:
del sum
del min
del max
except:
pass
numbers = (12, 45, 67, 23, 89)

maximum_value = max(numbers)
minimum_value = min(numbers)
total = sum(numbers)

print("Maximum:", maximum_value)
print("Minimum:", minimum_value)
print("Sum:", total)

#OUTPUT

Maximum: 89
Minimum: 12
Sum: 236

#FUNCTIONS AND ABSTRACTIONS

# Create a function that takes a name and prints a greeting.


def greet(name):
print("Hello,", name + "!")
greet("Farwa")

#OUTPUT

Hello, Farwa!

#Create four functions: add, subtract, multiply and divide.

def add(a,b):
return a+ b
def subtract(a,b):
return a-b
def multiply(a,b):
return a*b
def divide(a,b):
if b==0:
return "Cannot divide by zero!"
return a/b

print("Add:", add(5,3))
print("Subtract:", subtract(10,4))
print("Multiply:", multiply(6,7))
print("Divide:", divide(20, 5))

#OUTPUT

Add: 8
Subtract: 6
Multiply: 42
Divide: 4.0

#Write a function that returns the largest of 3 numbers.

def largest(a,b,c):
return max(a,b,c)

print("Largest number:", largest (12,25,7))

#OUTPUT

Largest number: 25

#Write a function that counts vowels in a string.

def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for ch in text:
if ch in vowels:
count +=1
return count

print("Vowels count:",
count_vowels("My name is farwa."))

#Output:

Vowels count: 5

#Write a function that checks if a numbers is prime.

def is_prime(n):
if n<= 1:
return False
for i in range (2, int(n**0.5) + 1):
if n%i == 0:
return False
return True

print("Prime check:", is_prime(17))

#OUTPUT:

Prime check: True

#Write a function that calculates factorial.

def factorial(n):
result = 1
for i in range(1, n+1):
result *=i
return result

print("Factorial:", factorial(6))

#OUTPUT:

Factorial: 720

#Write a function that reverses a string.

def reverse_string(text):
return text[:: -1]
print("Reversed:", reverse_string("Python"))

#OUTPUT:

Reversed: nohtyP

#Write a function that prints Fibnacci series.

def fibonacci(n):
a, b = 0,1
for i in range(n):
print(a , end= " ")
a,b = b, a+b
fibonacci(10)

#OUTPUT:

0 1 1 2 3 5 8 13 21 34

#DIRECTORIES

#Write a program to create a directory.


[Link]("New folder")
print("Folder created!")
#output:

Folder created!

#Write a program to change directory.

[Link]("New folder")
print([Link]())

#OUTPUT:

C:\Users\user\my_folder\New folder

#THIS PROGRAM IS NOT IN MIDS... JUST EXECUTED IT TO REMOVE AND AVOID


FURTHER ERRORS.
if not [Link]("New folder"):
[Link]("New folder")
print("folder created")
else:
print("already exist")

folder created

#Write a program to remove(delete) a directory.

[Link]("New Folder")
print("Folder remover!")

Folder remover!

#Write a program to list all files and folders in a directory.

items= [Link]()
print(items)

#OUTPUT:

[]

#wRITE a program to do all the above directory program combined.


(CHANGED THE FOLDER NAME HERE .)

import os

# 1. Create a directory
[Link]("my_folder")
print("Directory created: my_folder")

# 2. Change directory
[Link]("my_folder")
print("Current directory:", [Link]())

# 3. Go back to parent directory to list contents


[Link]("..")
print("Files and folders in current directory:", [Link]())

# 4. Remove the directory


[Link]("my_folder")
print("Directory removed: my_folder")

#OUTPUT:

Directory created: my_folder


Current directory: C:\Users\user\my_folder\New folder\my_folder
Files and folders in current directory: ['my_folder']
Directory removed: my_folder

You might also like