Python All Assignment SYBBACA SEM 3

 



Assignment 1

Practice Set

1. Currency Notes Denomination

amount = int(input("Enter the amount to withdraw: "))

# Calculating number of 10, 5, and 1 denomination notes
tens = amount // 10
amount %= 10
fives = amount // 5
amount %= 5
ones = amount

print(f"10 Rs notes: {tens}, 5 Rs notes: {fives}, 1 Rs notes: {ones}")


Sample Input and Output**:

Enter the amount to withdraw: 87
10 Rs notes: 8, 5 Rs notes: 1, 1 Rs notes: 2


2. Income Tax Calculation

salary = float(input("Enter your annual basic salary: "))

if salary < 250000:
    tax = 0
elif 250000 <= salary <= 500000:
    tax = salary * 0.10
else:
    tax = salary * 0.20

print(f"Income tax: Rs. {tax}")


**Sample Input and Output**:

Enter your annual basic salary: 450000
Income tax: Rs. 45000.0


#### 3. Find the Quadrant of a Point

**Code**:
python
x = float(input("Enter x-coordinate: "))
y = float(input("Enter y-coordinate: "))

if x > 0 and y > 0:
    print("The point is in the 1st quadrant.")
elif x < 0 and y > 0:
    print("The point is in the 2nd quadrant.")
elif x < 0 and y < 0:
    print("The point is in the 3rd quadrant.")
elif x > 0 and y < 0:
    print("The point is in the 4th quadrant.")
elif x == 0 and y == 0:
    print("The point is at the origin.")
else:
    print("The point lies on an axis.")
```

**Sample Input and Output**:
```
Enter x-coordinate: -3
Enter y-coordinate: 4
The point is in the 2nd quadrant.
```

---

4. Profit or Loss Calculation

**Code**:
```python
cost_price = float(input("Enter the cost price: "))
selling_price = float(input("Enter the selling price: "))

if selling_price > cost_price:
    profit = selling_price - cost_price
    print(f"Profit of Rs. {profit}")
elif cost_price > selling_price:
    loss = cost_price - selling_price
    print(f"Loss of Rs. {loss}")
else:
    print("No profit, no loss.")
```

**Sample Input and Output**:
```
Enter the cost price: 500
Enter the selling price: 600
Profit of Rs. 100
```

---

**Set A**

1. Sum of Digits of a Number

num = int(input("Enter a number: "))
sum_of_digits = sum(int(digit) for digit in str(num))
print(f"Sum of digits: {sum_of_digits}")
```

**Sample Input and Output**:
```
Enter a number: 1234
Sum of digits: 10
```

---

2. Armstrong Number Check

num = int(input("Enter a number: "))
order = len(str(num))
sum_of_powers = sum(int(digit) ** order for digit in str(num))

if num == sum_of_powers:
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")
```

**Sample Input and Output**:

Enter a number: 153
153 is an Armstrong number.


3. Perfect Number Check

**Code**:
python
num = int(input("Enter a number: "))
sum_of_divisors = sum(i for i in range(1, num) if num % i == 0)

if num == sum_of_divisors:
    print(f"{num} is a perfect number.")
else:
    print(f"{num} is not a perfect number.")


**Sample Input and Output**:

Enter a number: 6
6 is a perfect number.

4. Power Calculation (X^Y)

**Code**:
```python
x = int(input("Enter the base (X): "))
y = int(input("Enter the exponent (Y): "))
result = x ** y
print(f"{x} raised to the power {y} is {result}")
```

**Sample Input and Output**:
```
Enter the base (X): 2
Enter the exponent (Y): 3
2 raised to the power 3 is 8

#### 5. Palindrome Check

**Code**:
python
num = input("Enter a number: ")

if num == num[::-1]:
    print(f"{num} is a palindrome.")
else:
    print(f"{num} is not a palindrome.")


**Sample Input and Output**:

Enter a number: 121
121 is a palindrome.


6. Sum of First and Last Digits

num = input("Enter a number: ")
first_digit = int(num[0])
last_digit = int(num[-1])
sum_of_digits = first_digit + last_digit
print(f"Sum of first and last digit: {sum_of_digits}")
```

**Sample Input and Output**:

Enter a number: 1234
Sum of first and last digit: 5


### **Set B**

#### 1. Count Even, Odd, and Zero Digits


num = input("Enter a number: ")
evens = sum(1 for digit in num if int(digit) % 2 == 0 and digit != '0')
odds = sum(1 for digit in num if int(digit) % 2 != 0)
zeros = num.count('0')

print(f"Evens: {evens}, Odds: {odds}, Zeros: {zeros}")


**Sample Input and Output**:

Enter a number: 102304
Evens: 3, Odds: 2, Zeros: 2


#### 2. Binary to Decimal Conversion

**Code**:
```python
binary = input("Enter a binary number: ")
decimal = int(binary, 2)
print(f"Decimal equivalent: {decimal}")
```

**Sample Input and Output**:
```
Enter a binary number: 1010
Decimal equivalent: 10
```

---

#### 3. Command Line Integer Check

**Code**:
```python
n = int(input("Enter a number: "))

if 1 <= n <= 50:
    print("Ok")
else:
    print("Out of range")
```

**Sample Input and Output**:
```
Enter a number: 30
Ok
```

---

#### 4. Prime Numbers Till 'n'

**Code**:
```python
n = int(input("Enter a number: "))

for num in range(2, n + 1):
    prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            prime = False
            break
    if prime:
        print(num, end=" ")
```

**Sample Input and Output**:
```
Enter a number: 10
2 3 5 7
```

---

#### 5. Multiplication Table in Range

**Code**:
python

start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))

for i in range(start, end + 1):
    print(f"\nMultiplication table of {i}:")
    for j in range(1, 11):
        print(f"{i} x {j} = {i * j}")
```

**Sample Input and Output**:
```
Enter the start of range: 2
Enter the end of range: 3

Multiplication table of 2:
2 x 1 = 2
2 x 2 = 4
...
3 x 10 = 30

Set C

#### 1. Generate Number Pattern

**Code**:
```python
n = int(input("Enter the number of lines: "))

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

**Sample Input and Output**:
```
Enter the number of lines: 4
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1


Assignment 8

Practice set

1. Python GUI to import Tkinter package, create a window, and set its title:

python
import tkinter as tk

# Create the main window
root = tk.Tk()

# Set the title of the window
root.title("My Tkinter Window")

# Run the application
root.mainloop()


---

2. Python GUI program to create two buttons: Exit and Hello:

python
import tkinter as tk

def say_hello():
    print("Hello!")

# Create the main window
root = tk.Tk()

# Create 'Hello' button
hello_button = tk.Button(root, text="Hello", command=say_hello)
hello_button.pack()

# Create 'Exit' button
exit_button = tk.Button(root, text="Exit", command=root.quit)
exit_button.pack()

# Run the application
root.mainloop()


---

3. Python GUI program to create a Checkbutton widget:

python
import tkinter as tk

# Create the main window
root = tk.Tk()

# Create a Checkbutton widget
check_button = tk.Checkbutton(root, text="Check me")
check_button.pack()

# Run the application
root.mainloop()


---

4. Python GUI program to create three single-line text boxes (Entry widgets):

python
import tkinter as tk

# Create the main window
root = tk.Tk()

# Create three single-line text boxes
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
entry3 = tk.Entry(root)

# Pack the text boxes
entry1.pack()
entry2.pack()
entry3.pack()

# Run the application
root.mainloop()


---

5. Python GUI program to create three RadioButton widgets:

python
import tkinter as tk

# Create the main window
root = tk.Tk()

# Variable to hold the selected value
selected_option = tk.IntVar()

# Create radio buttons
radio1 = tk.Radiobutton(root, text="Option 1", variable=selected_option, value=1)
radio2 = tk.Radiobutton(root, text="Option 2", variable=selected_option, value=2)
radio3 = tk.Radiobutton(root, text="Option 3", variable=selected_option, value=3)

# Pack the radio buttons
radio1.pack()
radio2.pack()
radio3.pack()

# Run the application
root.mainloop()


---

6. Python GUI program to create a Listbox widget:

python
import tkinter as tk

# Create the main window
root = tk.Tk()

# Create a Listbox widget
listbox = tk.Listbox(root)

# Add items to the Listbox
listbox.insert(1, "Item 1")
listbox.insert(2, "Item 2")
listbox.insert(3, "Item 3")

# Pack the Listbox
listbox.pack()

# Run the application
root.mainloop()


Set A:

---

1. Python GUI program to display an alert message when a button is pressed:

python
import tkinter as tk
from tkinter import messagebox

def show_alert():
    messagebox.showinfo("Alert", "Button Pressed!")

# Create the main window
root = tk.Tk()

# Create a button to trigger the alert
alert_button = tk.Button(root, text="Click Me", command=show_alert)
alert_button.pack()

# Run the application
root.mainloop()


---

2. Python GUI program to create a background with changing colors:

python
import tkinter as tk
import random

def change_color():
    colors = ['red', 'green', 'blue', 'yellow', 'purple', 'orange']
    root.configure(bg=random.choice(colors))

# Create the main window
root = tk.Tk()

# Create a button to change background color
color_button = tk.Button(root, text="Change Color", command=change_color)
color_button.pack()

# Run the application
root.mainloop()


---

3. Python GUI program to create a label and change the label font style (font name,
bold, size):

python
import tkinter as tk

# Create the main window
root = tk.Tk()

# Create a label with a specific font
label = tk.Label(root, text="Hello, Tkinter!", font=("Helvetica", 16, "bold"))
label.pack()

# Run the application
root.mainloop()


---

4. Python GUI program to create a Text widget, insert and delete strings:

python
import tkinter as tk

# Create the main window
root = tk.Tk()

# Create a Text widget
text_widget = tk.Text(root, height=5, width=40)
text_widget.pack()

# Insert a string at the beginning
text_widget.insert(tk.END, "Welcome to Tkinter Text Widget")

# Insert a string into the current text
text_widget.insert(tk.END, " - Enjoy coding")

# Function to delete the first and last character
def delete_chars():
    text_widget.delete("1.0", "1.1")  # Delete the first character
    text_widget.delete("end-2c")      # Delete the last character

# Create a button to trigger deletion
delete_button = tk.Button(root, text="Delete", command=delete_chars)
delete_button.pack()

# Run the application
root.mainloop()


---

5. Python GUI program to accept dimensions of a cylinder and display the surface area
and volume:

python
import tkinter as tk
import math

def calculate():
    radius = float(entry_radius.get())
    height = float(entry_height.get())
    surface_area = 2 * math.pi * radius * (radius + height)
    volume = math.pi * radius2 * height
    result_label.config(text=f"Surface Area: {surface_area:.2f}\nVolume: {volume:.2f}")

# Create the main window
root = tk.Tk()

# Create input fields
tk.Label(root, text="Radius:").pack()
entry_radius = tk.Entry(root)
entry_radius.pack()

tk.Label(root, text="Height:").pack()
entry_height = tk.Entry(root)
entry_height.pack()

# Create a button to calculate the surface area and volume
calc_button = tk.Button(root, text="Calculate", command=calculate)
calc_button.pack()

# Label to display the result
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()


---

6. Python GUI program to take an input string and change the letters to uppercase when
a button is pressed:

python
import tkinter as tk

def to_uppercase():
    input_text = entry.get()
    result_label.config(text=input_text.upper())

# Create the main window
root = tk.Tk()

# Create an Entry widget for input
entry = tk.Entry(root)
entry.pack()

# Create a button to convert the text to uppercase
uppercase_button = tk.Button(root, text="To Uppercase", command=to_uppercase)
uppercase_button.pack()

# Create a label to display the result
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()

SET B
Here are the Python Tkinter-based GUI programs for Set B:

---

1. Python GUI program to take input of your date of birth and output your age when a
button is pressed:

python
import tkinter as tk
from datetime import datetime

def calculate_age():
    dob = entry_dob.get()  # Get date of birth input in YYYY-MM-DD format
    birth_date = datetime.strptime(dob, "%Y-%m-%d")
    today = datetime.today()
    age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month,
birth_date.day))
    result_label.config(text=f"Your Age: {age} years")

# Create the main window
root = tk.Tk()

# Create input field for date of birth
tk.Label(root, text="Enter your Date of Birth (YYYY-MM-DD):").pack()
entry_dob = tk.Entry(root)
entry_dob.pack()

# Create a button to calculate age
calc_button = tk.Button(root, text="Calculate Age", command=calculate_age)
calc_button.pack()

# Label to display the result
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()


---

2. Python GUI program to alter a sentence (replace spaces with *, reverse case, and
replace digits with ?):

python
import tkinter as tk

def alter_sentence():
    sentence = entry.get()
    altered_sentence = ""
    for char in sentence:
        if char == " ":
            altered_sentence += "*"
        elif char.isdigit():
            altered_sentence += "?"
        elif char.isalpha():
            altered_sentence += char.swapcase()
        else:
            altered_sentence += char
    result_label.config(text=altered_sentence)

# Create the main window
root = tk.Tk()

# Create input field for the sentence
tk.Label(root, text="Enter a sentence:").pack()
entry = tk.Entry(root, width=40)
entry.pack()

# Create a button to alter the sentence
alter_button = tk.Button(root, text="Alter Sentence", command=alter_sentence)
alter_button.pack()

# Label to display the altered sentence
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()


---

3. Python GUI program to create a digital clock:

python
import tkinter as tk
from time import strftime

def update_time():
    current_time = strftime("%H:%M:%S %p")
    label.config(text=current_time)
    label.after(1000, update_time)

# Create the main window
root = tk.Tk()

# Create a label to display time
label = tk.Label(root, font=("Helvetica", 48), bg="black", fg="white")
label.pack()

# Update the time every second
update_time()

# Run the application
root.mainloop()


---

4. Python GUI program to generate a random password with upper and lower case letters:

python
import tkinter as tk
import random
import string

def generate_password():
    password = ''.join(random.choices(string.ascii_letters, k=8))  # 8-character password
    result_label.config(text=f"Generated Password: {password}")

# Create the main window
root = tk.Tk()

# Create a button to generate password
generate_button = tk.Button(root, text="Generate Password", command=generate_password)
generate_button.pack()

# Label to display the generated password
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()


---

5. Python GUI program to display each digit of a number in words:

python
import tkinter as tk

digit_words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine"]

def number_to_words():
    number = entry.get()
    words = " ".join(digit_words[int(digit)] for digit in number)
    result_label.config(text=words)

# Create the main window
root = tk.Tk()

# Create input field for the number
tk.Label(root, text="Enter a number:").pack()
entry = tk.Entry(root)
entry.pack()

# Create a button to display the number in words
convert_button = tk.Button(root, text="Convert to Words", command=number_to_words)
convert_button.pack()

# Label to display the result
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()


6. Python GUI program to convert and display decimal number to binary, octal, and
hexadecimal:

python
import tkinter as tk

def convert_number():
    number = int(entry.get())
    binary = bin(number)[2:]
    octal = oct(number)[2:]
    hexadecimal = hex(number)[2:].upper()
    result_label.config(text=f"Binary: {binary}\nOctal: {octal}\nHexadecimal:
{hexadecimal}")

# Create the main window
root = tk.Tk()

# Create input field for the decimal number
tk.Label(root, text="Enter a decimal number:").pack()
entry = tk.Entry(root)
entry.pack()

# Create a button to convert the number
convert_button = tk.Button(root, text="Convert", command=convert_number)
convert_button.pack()

# Label to display the result
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()


7. Python GUI program to add, print, and delete items from a Listbox:

python
import tkinter as tk

def add_item():
    listbox.insert(tk.END, entry.get())

def print_item():
    selected_item = listbox.get(tk.ACTIVE)
    result_label.config(text=f"Selected Item: {selected_item}")

def delete_item():
    listbox.delete(tk.ACTIVE)

# Create the main window
root = tk.Tk()

# Create an input field
entry = tk.Entry(root)
entry.pack()

# Create buttons for adding, printing, and deleting items
add_button = tk.Button(root, text="Add Item", command=add_item)
add_button.pack()

print_button = tk.Button(root, text="Print Item", command=print_item)
print_button.pack()

delete_button = tk.Button(root, text="Delete Item", command=delete_item)
delete_button.pack()

# Create a Listbox widget
listbox = tk.Listbox(root)
listbox.pack()

# Label to display the selected item
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()

8. Python GUI program to add a menu bar with color options to change the background
color:

python
import tkinter as tk

def change_bg(color):
    root.config(bg=color)

# Create the main window
root = tk.Tk()
root.title("Color Menu")

# Create a menu bar
menu_bar = tk.Menu(root)

# Create a "Colors" menu
colors_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Colors", menu=colors_menu)

# Add color options to the "Colors" menu
colors_menu.add_command(label="Red", command=lambda: change_bg("red"))
colors_menu.add_command(label="Green", command=lambda: change_bg("green"))
colors_menu.add_command(label="Blue", command=lambda: change_bg("blue"))

# Display the menu bar
root.config(menu=menu_bar)

# Run the application
root.mainloop()

9. Python GUI program to check if a number is Prime, Perfect, or Armstrong using radio
buttons:

python
import tkinter as tk

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

def is_perfect(n):
    return sum(i for i in range(1, n) if n % i == 0) == n

def is_armstrong(n):
    return sum(int(digit)len(str(n)) for digit in str(n)) == n

def check_number():
    n = int(entry.get())
    if selected_option.get() == 1:
        result = "Prime" if is_prime(n) else "Not Prime"
    elif selected_option.get() == 2:
        result = "Perfect" if is_perfect(n) else "Not Perfect"
    elif selected_option.get() == 3:
        result = "Armstrong" if is_armstrong(n) else "Not Armstrong"
    result_label.config(text=result)

# Create the main window
root = tk.Tk()

# Create input field for the number
tk.Label(root, text="Enter a number:").pack()
entry = tk.Entry(root)
entry.pack()

# Create radio buttons for Prime, Perfect, and Armstrong checks
selected_option = tk.IntVar()
prime_button = tk.Radiobutton(root, text="Prime", variable=selected_option, value=1)
prime_button.pack()

perfect_button = tk.Radiobutton(root, text="Perfect", variable=selected_option, value=2)
perfect_button.pack()

armstrong_button = tk.Radiobutton(root, text="Armstrong", variable=selected_option,
value=3)
armstrong_button.pack()

# Create a button to check the number
check_button = tk.Button(root, text="Check", command=check_number)
check_button.pack()

# Label to display the result
result_label = tk.Label(root, text="")
result_label.pack()

# Run the application
root.mainloop()


10. Python GUI program to create a label and change its font style (font name, bold,
size) using checkbuttons:

python
import tkinter as tk

def update_font():
    font_name = "Helvetica" if var_helvetica.get() else "Arial"
    font_size = 16 if var_size.get() else 12
    font_style = "bold" if var_bold.get() else "normal"
    label.config(font=(font_name, font_size, font_style))

# Create the main window
root = tk.Tk()

# Create a label
label = tk.Label(root, text="Sample Text", font=("Arial", 12))
label.pack()

# Create checkbuttons to control font styles
var_helvetica = tk.IntVar()
check_helvetica = tk.Checkbutton(root, text="Helvetica", variable=var_helvetica,
command=update_font)
check_helvetica.pack()

var_bold = tk.IntVar()
check_bold = tk.Checkbutton(root, text="Bold", variable=var_bold, command=update_font)
check_bold.pack()

var_size = tk.IntVar()
check_size = tk.Checkbutton(root, text="Increase Size", variable=var_size,
command=update_font)
check_size.pack()

# Run the application
root.mainloop()

SET C

---

1. Python GUI program to implement a simple calculator:

python
import tkinter as tk

# Function to update the expression in the entry field
def click_button(item):
    current = entry_field.get()
    entry_field.delete(0, tk.END)
    entry_field.insert(tk.END, current + str(item))

# Function to clear the entry field
def clear():
    entry_field.delete(0, tk.END)

# Function to evaluate the expression and show the result
def evaluate():
    try:
        result = str(eval(entry_field.get()))  # Evaluate the expression
        entry_field.delete(0, tk.END)
        entry_field.insert(tk.END, result)
    except:
        entry_field.delete(0, tk.END)
        entry_field.insert(tk.END, "Error")

# Create the main window
root = tk.Tk()
root.title("Simple Calculator")

# Create an entry field for the calculator display
entry_field = tk.Entry(root, width=16, font=('Arial', 24), borderwidth=5,
justify='right')
entry_field.grid(row=0, column=0, columnspan=4)

# Define the button layout
buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+'
]

# Create and place buttons on the grid
row = 1
col = 0
for button in buttons:
    if button == '=':
        btn = tk.Button(root, text=button, width=10, height=3, command=evaluate)
    else:
        btn = tk.Button(root, text=button, width=10, height=3, command=lambda
x=button: click_button(x))
    btn.grid(row=row, column=col, padx=5, pady=5)
    col += 1
    if col > 3:
        col = 0
        row += 1

# Clear button
clear_button = tk.Button(root, text="C", width=10, height=3, command=clear)
clear_button.grid(row=row, column=col, padx=5, pady=5)

# Run the application
root.mainloop()