Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python.ammu (2)

The document outlines various Python programming concepts, including control flow tools, looping, data structures, mathematical operations, file handling, exception handling, class usage, and string manipulation with regular expressions. Each section includes example code snippets demonstrating the respective concepts. The document serves as a comprehensive guide for learning Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python.ammu (2)

The document outlines various Python programming concepts, including control flow tools, looping, data structures, mathematical operations, file handling, exception handling, class usage, and string manipulation with regular expressions. Each section includes example code snippets demonstrating the respective concepts. The document serves as a comprehensive guide for learning Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

S.NO. DATE CONTENT PAGE.NO.

SIGNATURE

1.

SAMPLE CALCULATOR

2. CONTROL FLOW TOOLS

3. LOOPING (FOR LOOP)

4. DATA STRUCTURE

A) USING LIST AS STACK


B) USING LIST AS QUEUE
C) USING LIST AS TUPLE

5. MATHEMATICAL EXPRESSIONS

6. CREATE READ, WRITE, DELETE FILES AND


DIRECTORIES

7. EXCEPTION HANDLING

8. PYTHON PROGRAM USING CLASSES

9. CONNECT WITH MYSQL AND CREATE


ADDRESS BOOK

10. STRING HANDLING WITH REGULAR


EXPRESSION
EX:01 SAMPLE CALCULATOR

# pip install tkinter

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="grey", 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()
OUTPUT:
EX:02 CONTROL FLOW TOOL

# Several elif conditions

print ("1.rainy")

print ("2.warm")

print ("3.very hot")

print ( "4.snowy")

tomorrow = input("Enter your weather: ")

if tomorrow == "warm":

print("I'll go to the sea.")

elif tomorrow == "very hot":

print("I'll go to the forest.")

elif tomorrow == "snowy":

print("I'll build a snowman.")

elif tomorrow == "rainy":

print("I'll stay home.")

else:

print("Weather not recognized.")


OUTPUT:
EX:03 USING FOR LOOP

n=8

# 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()
OUTPUT:
EX:04 DATA STRUCTURES

A) LIST AS STACK:

class Stack:

def __init__(self):

self.stack = []

def push(self, item):

self.stack.append(item)

def pop(self):

if not self.is_empty():

return self.stack.pop()

else:

return "Stack is empty"

def peek(self):

if not self.is_empty():

return self.stack[-1]

else:

return "Stack is empty"

def is_empty(self):

return len(self.stack) == 0

def size(self):

return len(self.stack)

stack = Stack()

while True:

print("1. Push")

print("2. Pop")

print("3. Peek")

print("4. Check if empty")

print("5. Size")

print("6. Exit")
choice = input("Enter your choice: ")

if choice == "1":

item = input("Enter item to push: ")

stack.push(item)

elif choice == "2":

print(stack.pop())

elif choice == "3":

print(stack.peek())

elif choice == "4":

print(stack.is_empty())

elif choice == "5":

print(stack.size())

elif choice == "6":

break

else:

print("Invalid choice")
B) LIST AS QUEUE:

class Queue:

def __init__(self):

self.queue = []

def enqueue(self, item):

self.queue.append(item)

def dequeue(self):

if not self.is_empty():

return self.queue.pop(0)

else:

return "Queue is empty"

def peek(self):

if not self.is_empty():

return self.queue[0]

else:

return "Queue is empty"

def is_empty(self):

return len(self.queue) == 0

def size(self):

return len(self.queue)

queue = Queue()

while True:

print("1. Enqueue")

print("2. Dequeue")

print("3. Peek")

print("4. Check if empty")

print("5. Size")

print("6. Exit")

choice = input("Enter your choice: ")


if choice == "1":

item = input("Enter item to enqueue: ")

queue.enqueue(item)

elif choice == "2":

print(queue.dequeue())

elif choice == "3":

print(queue.peek())

elif choice == "4":

print(queue.is_empty())

elif choice == "5":

print(queue.size())

elif choice == "6":

break

else:

print("Invalid choice")
OUTPUT:
B) LIST AS TUPLE:

aTuple=(123,'abc',4.56,['inner','tuple'],7-9j)

anotherTuple=(None,'something to see here')

emptiestPossibleTuple=(1,2,3,4,5)

print(aTuple)

print(anotherTuple)

print(emptiestPossibleTuple)

print(aTuple+anotherTuple)
OUTPUT:
EX:05 MATHEMATICAL OPERATION

def calculator():

while True:

print("1. Addition")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

print("5. Exit")

choice = int(input("Enter your choice: "))

if choice == 5:

break

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

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

if choice == 1:

result = num1 + num2

elif choice == 2:

result = num1 - num2

elif choice == 3:

result = num1 * num2

elif choice == 4:

if num2 != 0:

result = num1 / num2

else:

print("Error: Division by zero!")

continue

else:

print("Error: Invalid choice!")

continue

print(f"The result is: {result}")

calculator()
OUTPUT:
EX:06 FILES USING CREATE, DELETE, READ AND WRITE

import os

def main():

while True:

print("\nFile and Directory Operations")

print("1. Create Directory")

print("2. Delete Directory")

print("3. Create File")

print("4. Delete File")

print("5. Read File")

print("6. Write File")

print("7. Exit")

choice = input("Enter your choice: ")

if choice == "1":

print("creating the directory")

os.mkdir(input("Enter directory name: "))

print("the directory has been created")

elif choice == "2":

print("removing the directory")

os.rmdir(input("Enter directory name: "))

print("directory has been removed")

elif choice == "3":

print("creating the file")

open(input("Enter file name: "), 'w').close()

print("the file has been created")

elif choice == "4":

print("removing the file")

os.remove(input("Enter file name: "))

print ("file is deleted")

elif choice == "5":


print ("Reading the content of file")

print(open(input("Enter file name: "), 'r').read())

print("the content has been read")

elif choice == "6":

print("writing the content to file")

open(input("Enter file name: "), 'w').write(input("Enter content: "))

print("the content has been written")

elif choice == "7":

break

else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()
OUTPUT:
EX:07 EXCEPTION HANDLING

def get_dynamic_value():

while True:

try:

num = int(input("Enter a number: "))

return num

except ValueError:

print("Invalid input. Please enter a number.")

def divide_numbers(num1, num2):

try:

result = num1 / num2

return result

except ZeroDivisionError:

print("Error: Division by zero!")

return None

def main():

num1 = get_dynamic_value()

num2 = get_dynamic_value()

result = divide_numbers(num1, num2)

if result is not None:

print("Result:", result)

if __name__ == "__main__":

main()
OUTPUT:
EX:08 PROGRAM USING CLASS

class GradeCalculator:

def __init__(self, marks):

self.marks = marks

def calculate_percentage(self):

return (self.marks / 100) * 100

def calculate_grade(self):

percentage = self.calculate_percentage()

if percentage >= 90:

return "A"

elif percentage >= 80:

return "B"

elif percentage >= 70:

return "C"

elif percentage >= 60:

return "D"

else:

return "F"

def get_dynamic_value(prompt):

while True:

try:

value = int(input(prompt))

return value

except ValueError:

print("Invalid input. Please enter a number.")

def main():

marks = get_dynamic_value("Enter marks out of 100: ")

calculator = GradeCalculator(marks)

percentage = calculator.calculate_percentage()

grade = calculator.calculate_grade()
print(f"Marks: {marks}")

print(f"Percentage: {percentage}%")

print(f"Grade: {grade}")

if __name__ == "__main__":

main()
OUTPUT:
EX: 10 STRING HANDLING AND REGULAR EXPRESSION

import re

def validate_email(email):

pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"

if re.match(pattern, email):

return True

return False

def count_vowels(text):

vowels = "aeiouAEIOU"

count = 0

for char in text:

if char in vowels:

count += 1

return count

def extract_numbers(text):

numbers = re.findall(r"\d+", text)

return numbers

def main():

email = input("Enter an email: ")

if validate_email(email):

print("Valid email")

else:

print("Invalid email")

text = input("Enter a text: ")

print("Vowel count:", count_vowels(text))

print("Extracted numbers:", extract_numbers(text))

if __name__ == "__main__":

main()
OUTPUT:

You might also like