0% found this document useful (0 votes)
6 views16 pages

Python Programs for Beginners

Uploaded by

jimwhopam
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)
6 views16 pages

Python Programs for Beginners

Uploaded by

jimwhopam
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

PROGRAMS

1. Write a Python program to calculate the factorial of a number.

n= int(input("Enter the no. to find factorial") )


fact=1
for i in range(1,n+1):
fact=fact*i
print(fact)
OUTPUT

2. Write a Python program to generate prime numbers between 1 to n,


where n is provided as input by the user.

def isprime(n):
flag=True
if n<1:
flag=False
elif n>1:
for i in range(2,n):
if (n%i==0):
flag=False

if flag == True:
print("Prime")
else:
print("Not prime")

a= int(input("Enter the no. to check") )


isprime(a)

OUTPUT

3. Write a Python program to find the sum and average of numbers of a given
list.

L = [1,4,6,3]
#finding sum
count = sum(L)
#finding average
avg = count/len(L)

print("sum = ", count)


print("average = ", avg)

OUTPUT

4. Given two sets, set1 and set2, write a Python program to find their union,
intersection, and difference.

A = {1,3,5,6}
B = {1,4,8,7}

# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)

OUTPUT
5. Given a list of numbers, write a Python program to count
the number of times an element occurs in a list and create a dictionary
with element:count as key:value pairs.

def frequency(l):
freq = {}
for item in l:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in [Link]():
print("% d : % d" % (key, value))

l = [1,2,3,1,1,4,5,4,3,2,5]
frequency(l)

OUTPUT

6. Write a Python program to swap the first two and last two
characters of a given string.

string="worldcup"
x=list(string)
temp=x[0]
st=x[1]
x[0]=x[-1]
x[1]=x[-2]
x[-1]=temp
x[-2]=st
print("".join(x))
OUTPUT

7. Write a Python program to create a text file having names of ten Indian
cities.

cities = ["Delhi", "Mumbai", "Bangalore", "Chennai", "Kolkata",


"Hyderabad", "Indore", "Ahmedabad", "Jaipur", "Lucknow"]

file_name = "[Link]"
with open(file_name, 'w') as file:
for city in cities:
[Link](city + '\n')
print("File created successfully with the names of Indian cities.")

OUTPUT

8. Write a Python program to create a text file having atleast five


lines about your college using writelines() function.

clg_info = ["Keshav Mahavidyalaya is an institution that has always


believed in excellence"
"through continuous learning by doing."
"It strive to create leaders of tomorrow by giving shape and providing
direction"
"to the aspirations and dreams of the young minds"
"who step into this temple of learning."]

file_name = "clg_info.txt"
with open(file_name, 'w') as file:
# Write the lines about the college to the file
[Link](line +'\n' for line in clg_info)

print("File created successfully with information about the college.")

OUTPUT

9. Write a Python program which reads the data from three input
files having Employee Names and merges them into one output file.

# List of input file names


input_files = ['[Link]', '[Link]', '[Link]']

# Output file name


output_file = 'merged_employees.txt'

# Function to read data


def merge_files(input_files, output_file):
with open(output_file, 'w') as output:
for input_file in input_files:
with open(input_file, 'r') as input_data:
[Link](input_data.readlines())

merge_files(input_files, output_file)

print("Files merged successfully.")

OUTPUT
[Link] a Python program to count the number of vowels in a file and write
the vowel: count in a dictionary.

def count_vowels(file_path):
vowels = set("aeiouAEIOU")

vowel_counts = {}
with open(file_path, 'r') as file:
content = [Link]()

for char in content:


if char in vowels:
vowel_counts[char] = vowel_counts.get(char, 0) + 1
return vowel_counts

file_path = 'clg_info.txt'

vowel_count_dict = count_vowels(file_path)

# Print the result


print("Vowel Counts:")
for vowel, count in vowel_count_dict.items():
print(f"{vowel}: {count}")
OUTPUT

(File)

[Link] a Python program to create a CSV file having student data: Roll_No,
Enrollment No, Name, Course, Semester.

import csv
student_data = [
["Roll_No", "Enrollment_No", "Name", "Course", "Semester"],
[1, "EN12345", "Raman", "Computer Science", 3],
[2, "EN54321", "Khushi", "Maths", 2],
[3, "EN98765", "Aarav", "Management", 4],
[4, "EN67890", "Neha", "Science", 1],
]
csv_file_name = "student_data.csv"
with open(csv_file_name, mode='w', newline='') as file:
writer = [Link](file)
[Link](student_data)

print("CSV file created successfully.")

OUTPUT

[Link] a Python program library to read the CSV file created in the above
program and
filter out records of II semester students.

import csv
def read_csv(file_path):
with open(file_path, mode='r') as file:
reader = [Link](file)
data = [row for row in reader]
return data

def filter_semester(data, semester):


filtered_data = [record for record in data if record['Semester'] ==
str(semester)]
return filtered_data

csv_file_path = 'student_data.csv'
student_data = read_csv(csv_file_path)
target_semester = 2
filtered_records = filter_semester(student_data, target_semester)
print("Filtered records of semester 2 students:")
for record in filtered_records:
print(record)

OUTPUT

[Link] a Python program using tkinter library to create a GUI to enter


registration details for an event.

import tkinter as tk
from tkinter import messagebox

def submit_registration():
name = entry_name.get()
email = entry_email.get()
phone = entry_phone.get()

if not name or not email or not phone:


[Link]("Incomplete Form", "Please fill in all the
fields.")
return

message = f"Registration Details:\nName: {name}\nEmail: {email}\


nPhone: {phone}"
[Link]("Registration Successful", message)
entry_name.delete(0, [Link])
entry_email.delete(0, [Link])
entry_phone.delete(0, [Link])

#main window
root = [Link]()
[Link]("Event Registration")

label_name = [Link](root, text="Name:")


label_name.grid(row=0, column=0, padx=10, pady=10, sticky=tk.E)

entry_name = [Link](root)
entry_name.grid(row=0, column=1, padx=10, pady=10, sticky=tk.W)

label_email = [Link](root, text="Email:")


label_email.grid(row=1, column=0, padx=10, pady=10, sticky=tk.E)

entry_email = [Link](root)
entry_email.grid(row=1, column=1, padx=10, pady=10, sticky=tk.W)

label_phone = [Link](root, text="Phone:")


label_phone.grid(row=2, column=0, padx=10, pady=10, sticky=tk.E)

entry_phone = [Link](root)
entry_phone.grid(row=2, column=1, padx=10, pady=10, sticky=tk.W)

submit_button = [Link](root, text="Submit",


command=submit_registration)
submit_button.grid(row=3, column=0, columnspan=2, pady=20)

[Link]()
OUTPUT

[Link] a Python program using tkinter library to create a calculator to


perform addition,
subtraction, multiplication, and division of two numbers entered by the
user.

import tkinter as tk
from tkinter import messagebox

def calculate():
try:
num1 = float(entry_num1.get())
num2 = float(entry_num2.get())

if [Link]() == "Addition":
result = num1 + num2
elif [Link]() == "Subtraction":
result = num1 - num2
elif [Link]() == "Multiplication":
result = num1 * num2
elif [Link]() == "Division":
if num2 == 0:
[Link]("Error", "Cannot divide by zero.")
return
result = num1 / num2

result_label.config(text=f"Result: {result}")

except ValueError:
[Link]("Error", "Please enter valid numeric
values.")

# Create the main window


root = [Link]()
[Link]("Simple Calculator")

entry_num1 = [Link](root)
entry_num1.grid(row=0, column=0, padx=10, pady=10)

entry_num2 = [Link](root)
entry_num2.grid(row=0, column=1, padx=10, pady=10)

operation = [Link]()
[Link]("Addition")

operation_menu = [Link](root, operation, "Addition",


"Subtraction", "Multiplication", "Division")
operation_menu.grid(row=1, column=0, columnspan=2, pady=10)

calculate_button = [Link](root, text="Calculate", command=calculate)


calculate_button.grid(row=2, column=0, columnspan=2, pady=10)

result_label = [Link](root, text="Result: ")


result_label.grid(row=3, column=0, columnspan=2, pady=10)

[Link]()

OUTPUT
[Link] a Python program using tkinter library to create an age calculator to
calculate age when DOB is entered.

import tkinter as tk
from tkinter import messagebox
from datetime import datetime

def calculate_age():
try:
dob_str = entry_dob.get()
dob_date = [Link](dob_str, "%Y-%m-%d")

current_date = [Link]()
age = current_date.year - dob_date.year - ((current_date.month,
current_date.day) < (dob_date.month, dob_date.day))

age_label.config(text=f"Age: {age} years")

except ValueError:
[Link]("Error", "Please enter a valid date in the
format YYYY-MM-DD.")

root = [Link]()
[Link]("Age Calculator")

entry_dob = [Link](root)
entry_dob.grid(row=0, column=0, padx=10, pady=10)

calculate_button = [Link](root, text="Calculate Age",


command=calculate_age)
calculate_button.grid(row=1, column=0, pady=10)

age_label = [Link](root, text="Age: ")


age_label.grid(row=2, column=0, pady=10)

[Link]()

OUTPUT

[Link] a Python program using tkinter library to read and write student
details namely Roll_No, Enrollment_No, Name, course, Semester through a
form and write the entered details to a CSV file.

import tkinter as tk
from tkinter import messagebox
import csv

def save_student_details():
try:
roll_no = entry_roll_no.get()
enrollment_no = entry_enrollment_no.get()
name = entry_name.get()
course = entry_course.get()
semester = entry_semester.get()

if not roll_no or not enrollment_no or not name or not course or not


semester:
[Link]("Incomplete Form", "Please fill in all
the fields.")
return

with open('student_details.csv', mode='a', newline='') as file:


writer = [Link](file)
[Link]([roll_no, enrollment_no, name, course,
semester])

[Link]("Success", "Student details saved


successfully.")

entry_roll_no.delete(0, [Link])
entry_enrollment_no.delete(0, [Link])
entry_name.delete(0, [Link])
entry_course.delete(0, [Link])
entry_semester.delete(0, [Link])

except Exception as e:
[Link]("Error", f"An error occurred: {str(e)}")

root = [Link]()
[Link]("Student Details Form")

label_roll_no = [Link](root, text="Roll No:")


label_roll_no.grid(row=0, column=0, padx=10, pady=10, sticky=tk.E)

entry_roll_no = [Link](root)
entry_roll_no.grid(row=0, column=1, padx=10, pady=10, sticky=tk.W)

label_enrollment_no = [Link](root, text="Enrollment No:")


label_enrollment_no.grid(row=1, column=0, padx=10, pady=10,
sticky=tk.E)

entry_enrollment_no = [Link](root)
entry_enrollment_no.grid(row=1, column=1, padx=10, pady=10,
sticky=tk.W)

label_name = [Link](root, text="Name:")


label_name.grid(row=2, column=0, padx=10, pady=10, sticky=tk.E)

entry_name = [Link](root)
entry_name.grid(row=2, column=1, padx=10, pady=10, sticky=tk.W)

label_course = [Link](root, text="Course:")


label_course.grid(row=3, column=0, padx=10, pady=10, sticky=tk.E)

entry_course = [Link](root)
entry_course.grid(row=3, column=1, padx=10, pady=10, sticky=tk.W)

label_semester = [Link](root, text="Semester:")


label_semester.grid(row=4, column=0, padx=10, pady=10, sticky=tk.E)

entry_semester = [Link](root)
entry_semester.grid(row=4, column=1, padx=10, pady=10, sticky=tk.W)

submit_button = [Link](root, text="Save Details",


command=save_student_details)
submit_button.grid(row=5, column=0, columnspan=2, pady=20)

[Link]()

OUTPUT
(File)

You might also like