0% found this document useful (0 votes)
4 views10 pages

SD

The document contains multiple Python programs demonstrating various functionalities including a calculator using Tkinter, grade conversion functions, pattern printing, stack and queue implementations, and file operations. It showcases user input handling, error management, and the use of loops for creating visual patterns. Additionally, it includes examples of tuple usage and directory manipulation using the os module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

SD

The document contains multiple Python programs demonstrating various functionalities including a calculator using Tkinter, grade conversion functions, pattern printing, stack and queue implementations, and file operations. It showcases user input handling, error management, and the use of loops for creating visual patterns. Additionally, it includes examples of tuple usage and directory manipulation using the os module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Ex no:1

import tkinter as tk
import tkinter.messagebox
from tkinter.constants import SUNKEN
window = tk.Tk()
window.title('Calculator-GeeksForGeeks')
frame = tk.Frame(master=window, bg="skyblue", padx=10)
frame.pack()
entry = tk.Entry(master=frame, relief=SUNKEN, borderwidth=3, width=30)
entry.grid(row=0, column=0, columnspan=3, ipady=2, pady=2)
def myclick(number):
entry.insert(tk.END, number)
def equal():
try:
y = str(eval(entry.get()))
entry.delete(0, tk.END)
entry.insert(0, y)
except:
tkinter.messagebox.showinfo("Error", "Syntax Error")

def clear():
entry.delete(0, tk.END)
button_1 = tk.Button(master=frame, text='1', padx=15,
pady=5, width=3, command=lambda: myclick(1))
button_1.grid(row=1, column=0, pady=2)
button_2 = tk.Button(master=frame, text='2', padx=15,
pady=5, width=3, command=lambda: myclick(2))
button_2.grid(row=1, column=1, pady=2)
button_3 = tk.Button(master=frame, text='3', padx=15,
pady=5, width=3, command=lambda: myclick(3))
button_3.grid(row=1, column=2, pady=2)
button_4 = tk.Button(master=frame, text='4', padx=15,
pady=5, width=3, command=lambda: myclick(4))
button_4.grid(row=2, column=0, pady=2)
button_5 = tk.Button(master=frame, text='5', padx=15,
pady=5, width=3, command=lambda: myclick(5))
button_5.grid(row=2, column=1, pady=2)
button_6 = tk.Button(master=frame, text='6', padx=15,
pady=5, width=3, command=lambda: myclick(6))
button_6.grid(row=2, column=2, pady=2)
button_7 = tk.Button(master=frame, text='7', padx=15,
pady=5, width=3, command=lambda: myclick(7))
button_7.grid(row=3, column=0, pady=2)
button_8 = tk.Button(master=frame, text='8', padx=15,
pady=5, width=3, command=lambda: myclick(8))
button_8.grid(row=3, column=1, pady=2)
button_9 = tk.Button(master=frame, text='9', padx=15,
pady=5, width=3, command=lambda: myclick(9))
button_9.grid(row=3, column=2, pady=2)
button_0 = tk.Button(master=frame, text='0', padx=15,
pady=5, width=3, command=lambda: myclick(0))
button_0.grid(row=4, column=1, pady=2)

button_add = tk.Button(master=frame, text="+", padx=15,


pady=5, width=3, command=lambda: myclick('+'))
button_add.grid(row=5, column=0, pady=2)

button_subtract = tk.Button(
master=frame, text="-", padx=15, pady=5, width=3, command=lambda: myclick('-'))
button_subtract.grid(row=5, column=1, pady=2)

button_multiply = tk.Button(
master=frame, text="*", padx=15, pady=5, width=3, command=lambda: myclick('*'))
button_multiply.grid(row=5, column=2, pady=2)

button_div = tk.Button(master=frame, text="/", padx=15,


pady=5, width=3, command=lambda: myclick('/'))
button_div.grid(row=6, column=0, pady=2)

button_clear = tk.Button(master=frame, text="clear",


padx=15, pady=5, width=12, command=clear)
button_clear.grid(row=6, column=1, columnspan=2, pady=2)
button_equal = tk.Button(master=frame, text="=", padx=15,
pady=5, width=9, command=equal)
button_equal.grid(row=7, column=0, columnspan=3, pady=2)

window.mainloop()

program 2
def get_letter_grade(grade):
"""
This function converts a numerical grade to a letter grade.

Args:
grade: A numerical grade between 0 and 100.

Returns:
A letter grade (A, B, C, D, or F).
"""

if grade >= 90:


return "A"
elif grade >= 80:
return "B"
elif grade >= 70:
return "C"
elif grade >= 60:
return "D"
else:
return "F"

def main():
"""
This function prompts the user for a numerical grade, calls the get_letter_grade
function to convert it, and prints the letter grade.
"""

try:
# Get the numerical grade from the user
number_grade = float(input("Enter your numerical grade (0-100): "))

# Input validation - check if grade is between 0 and 100


if not (0 <= number_grade <= 100):
raise ValueError("Grade must be between 0 and 100.")

# Call the function to get the letter grade


letter_grade = get_letter_grade(number_grade)

# Print the letter grade


print(f"Your letter grade for {number_grade} is: {letter_grade}")
except ValueError as e:
print(f"Error: {e}")

if __name__ == "__main__":
main()

program2
M = int(input("Enter The Marks Of Maths(Out OF 100) "))
S = int(input("Enter The Marks Of Science(Out OF 100) "))
E = int(input("Enter The Marks Of English(Out OF 100) "))
TOT=M+S+E
print("Total Marks",TOT,sep=" ")
PER= (M+S+E)/3
print("Percentage",round(PER,2),sep=" ")
#Now I want The Below Code To Be Run Without The Use Of if_else
if(PER>50):
print("A")
elif(PER>0):
print("B")

elif(PER==0):
print("C")
while per > 50:
print("A")
break
is_a = PER > 50
is_b = PER <= 50 and PER > 0
is_c = PER == 0

# Assign key,val pairs to each grade


grade_values = {
is_a: "A",
is_b: "B",
is_c: "C",
}

# Since only one grade can evaluate to True, grade_values[True] will return the
correct grade
grade = grade_values[True]

print(grade)

program 2
def get_letter_grade(numeric_grade):
if numeric_grade >= 90:
return 'A'
elif numeric_grade >= 80:
return 'B'
elif numeric_grade >= 70:
return 'C'
elif numeric_grade >= 60:
return 'D'
elif numeric_grade >= 50:
return 'Fail'
else:
return 'G'

def main():
try:
# Get user input
numeric_grade = float(input("Enter your numeric grade: "))

# Get the letter grade


letter_grade = get_letter_grade(numeric_grade)

# Print the letter grade


print(f"Your letter grade is: {letter_grade}")
except ValueError:
print("Please enter a valid number.")

if __name__ == "__main__":
main()

program 3
n = 5

# Upper half of the butterfly


for i in range(1, n + 1):
for j in range(i):
print("*", end="")
for j in range(2 * (n - i)):
print(" ", end="")
for j in range(i):
print("*", end="")
print()

# Lower half of the butterfly


for i in range(n, 0, -1):
for j in range(i):
print("*", end="")
for j in range(2 * (n - i)):
print(" ", end="")
for j in range(i):
print("*", end="")
print()

for i in range(5):
for j in range(5):
print("*", end="")
print()

for i in range(5):
for j in range(i):
print(" ", end="")
for j in range(i, 5):
print("* ", end="")
print()

for i in range(5):
for j in range(5, i, -1):
print(" ", end="")
for k in range(i + 1):
print("* ", end="")
print()

n = 5

# Upper half of the diamond


for i in range(n):
for j in range(n - 1, i, -1):
print(" ", end="")
for k in range(i + 1):
print("* ", end="")
print()

# Lower half of the diamond


for i in range(1, n):
for j in range(i):
print(" ", end="")
for k in range(n - 1, i - 1, -1):
print("* ", end="")
print()

n = 5

for i in range(n):
for j in range(n):
if i == 0 or i == n - 1 or j == 0 or j == n - 1:
print("*", end="")
else:
print(" ", end="")
print()

program 4
# Python program to
# demonstrate stack implementation
# using list

stack = []

# append() function to push


# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)

# pop() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)

# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty

queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)

Ex no:3

# define size n = even only


n = 8

# so this heart can be made n//2 part left,


# n//2 part right, and one middle line
# i.e; columns m = n + 1
m = n+1

# loops for upper part


for i in range(n//2-1):
for j in range(m):

# condition for printing stars to GFG upper line


if i == n//2-2 and (j == 0 or j == m-1):
print("*", end=" ")

# condition for printing stars to left upper


elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \
or (j-i == m//2-n//2+3 and j > m//4)):
print("*", end=" ")

# condition for printing stars to right upper


elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \
or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)):
print("*", end=" ")

# condition for printing spaces


else:
print(" ", end=" ")
print()

# loops for lower part


for i in range(n//2-1, n):
for j in range(m):

# condition for printing stars


if (i-j == n//2-1) or (i+j == n-1+m//2):
print('*', end=" ")

# condition for printing GFG


elif i == n//2-1:

if j == m//2-1 or j == m//2+1:
print('G', end=" ")
elif j == m//2:
print('F', end=" ")
else:
print(' ', end=" ")

# condition for printing spaces


else:
print(' ', end=" ")

print()

Ex no:3

n = 5

# Upper half of the butterfly


for i in range(1, n + 1):
for j in range(i):
print("*", end="")
for j in range(2 * (n - i)):
print(" ", end="")
for j in range(i):
print("*", end="")
print()

# Lower half of the butterfly


for i in range(n, 0, -1):
for j in range(i):
print("*", end="")
for j in range(2 * (n - i)):
print(" ", end="")
for j in range(i):
print("*", end="")

Ex no:3

# Python implementation
# to print circle pattern

import math

# function to print circle pattern


def printPattern(radius):
# dist represents distance to the center
# for horizontal movement
for i in range((2 * radius)+1):

# for vertical movement


for j in range((2 * radius)+1):

dist = math.sqrt((i - radius) * (i - radius) +


(j - radius) * (j - radius))

# dist should be in the


# range (radius - 0.5)
# and (radius + 0.5) to print stars(*)
if (dist > radius - 0.5 and dist < radius + 0.5):
print("*",end="")
else:
print(" ",end="")

print()

# Driver code

radius = 6
printPattern(radius)

# This code is contributed


# by Anant Agarwal.

Ex no:4

# Python program to
# demonstrate stack implementation
# using list

stack = []

# append() function to push


# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)

# pop() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty

Ex no:4

queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)

Ex no:4

t = 12345, 54321, 'hello!'


t[0]
12345
t
(12345, 54321, 'hello!')
# Tuples may be nested:
u = t, (1, 2, 3, 4, 5)
u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
# Tuples are immutable:
t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
# but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v
([1, 2, 3], [3, 2, 1])
empty = ()
singleton = 'hello', # <-- note trailing comma
len(empty)
0
len(singleton)
1
singleton
('hello',)
x, y, z = t

Ex no:6

# importing os module
import os

# File name
file = 'file1.txt'

# File location
location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"

# Path
path = os.path.join(location, file)

# Remove the file


# 'file.txt'
os.remove(path)

Ex no:6

import os

# define the name of the directory to be created


path = "/tmp/year"

try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path)

You might also like