Skip to content
Snippets Groups Projects
Commit 8af6a1b4 authored by Jöran Frey's avatar Jöran Frey
Browse files

added sokution of last weeks exercise and this weeks new exercise made some...

added sokution of last weeks exercise and this weeks new exercise made some minor corrections for the lecture
parent a9351032
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Extra Exercises
%% Cell type:markdown id: tags:
## Build a Contact Manager
Write a Python program that manages a list of contacts. Programm functions that allow a User to add, search, delete, and display contacts.
```Hint```: the basic framework is already there, you just have to programme the functions
%% Cell type:code id: tags:
``` python
# Contact Manager Program
# List to store contacts with some examples
contacts = [
{"name": "Alice Johnson", "phone": "1234567890", "email": "alice@example.com"},
{"name": "Bob Smith", "phone": "9876543210", "email": "bob.smith@example.com"},
{"name": "Charlie Brown", "phone": "5556667777", "email": "charlie.brown@example.com"},
{"name": "John Do", "phone": "1112223333", "email": "diana.prince@example.com"}
]
def display_menu():
"""Displays the menu."""
print("\nContact Manager")
print("1. Add Contact")
print("2. Search Contact")
print("3. Delete Contact")
print("4. Display All Contacts")
print("5. Exit")
def add_contact():
"""Adds a new contact."""
print("\nYou chose 1. Add Contact")
name = input("Enter name: ").strip()
phone = input("Enter phone number: ").strip()
email = input("Enter email address: ").strip()
# Check for duplicates
for contact in contacts:
if contact["name"].lower() == name.lower():
print("Contact with this name already exists.")
return
contacts.append({"name": name, "phone": phone, "email": email})
print("Contact added successfully!")
def search_contact():
"""Searches for a contact by name."""
print("\nYou chose 2. Search Contact")
search_name = input("Enter the name to search: ").strip()
found = False
for contact in contacts:
if search_name.lower() in contact["name"].lower():
print(f"Found: Name: {contact['name']}, Phone: {contact['phone']}, Email: {contact['email']}")
found = True
if not found:
print("No contacts found with that name.")
def delete_contact():
"""Deletes a contact."""
print("\nYou chose 3. Delete Contact")
delete_name = input("Enter the name of the contact to delete: ").strip()
for contact in contacts:
if contact["name"].lower() == delete_name.lower():
contacts.remove(contact)
print("Contact deleted successfully!")
return
print("Contact not found.")
def display_all_contacts():
"""Displays all contacts."""
print("\nYou chose 4. Display All Contacts")
if not contacts:
print("No contacts to display.")
return
for idx, contact in enumerate(contacts, start=1):
print(f"{idx}. Name: {contact['name']}, Phone: {contact['phone']}, Email: {contact['email']}")
def main():
"""Main program loop."""
while True:
display_menu()
choice = input("Enter your choice: ").strip()
if choice == "1":
add_contact()
elif choice == "2":
search_contact()
elif choice == "3":
delete_contact()
elif choice == "4":
display_all_contacts()
elif choice == "5":
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Execute main
main()
def delete_contact():
print("you chose 3. delete a contact")
"""Deletes a contact."""
def display_all_contacts():
print("you chose 4. display all contacts")
"""Displays all contacts."""
def main():
"""Main programm loop."""
while True:
display_menu()
choice = input("Enter your choice: ").strip()
if choice == "1":
add_contact()
elif choice == "2":
search_contact()
elif choice == "3":
delete_contact()
elif choice == "4":
display_all_contacts()
else:
print("Invalid choice. Please try again.")
# Execute main
main()
```
%% Output
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
you chose 1. Add Contact
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
you chose 1. Add Contact
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
you chose 2. Search Contact
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
Invalid choice. Please try again.
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
you chose 1. Add Contact
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
Invalid choice. Please try again.
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
Invalid choice. Please try again.
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
Invalid choice. Please try again.
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
Invalid choice. Please try again.
Contact Manager
1. Add Contact
2. Search Contact
3. Update Contact
4. Delete Contact
5. Display All Contacts
6. Exit
%% Cell type:markdown id: tags:
## Create a Simple Bank Account System
Build a program that simulates a basic bank account system. Users can deposit, withdraw, and check their balance through a menu-driven interface.
* Add a PIN system to log in (only 3 attempts allowed)
Give the following Functionality
* Check Balance
* Deposit Money
* Withdraw Money
* Exit
%% Cell type:code id: tags:
``` python
# Bank Account System
# Initial balance and PIN
balance = 0.05
PIN = "1234" # Default PIN
attempts = 3 # Number of allowed attempts
def display_menu():
"""Displays the menu."""
print("\nBank Account System")
print("1. Check Balance")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Exit")
def login():
"""Authenticates the user with a PIN system."""
global attempts
while attempts > 0:
entered_pin = input("Enter your PIN: ").strip()
if entered_pin == PIN:
print("Login successful!")
return True
else:
attempts -= 1
print(f"Incorrect PIN. {attempts} attempt(s) remaining.")
print("Too many failed attempts. Exiting system.")
return False
def check_balance():
"""Displays the current balance."""
print(f"Your current balance is: ${balance:.2f}")
def deposit_money():
"""Deposits money into the account."""
global balance
try:
amount = float(input("Enter the amount to deposit: ").strip())
if amount <= 0:
print("Invalid amount. Please enter a positive number.")
else:
balance += amount
print(f"You have successfully deposited ${amount:.2f}. Your new balance is ${balance:.2f}.")
except ValueError:
print("Invalid input! Please enter a valid number.")
def withdraw_money():
"""Withdraws money from the account."""
global balance
try:
amount = float(input("Enter the amount to withdraw: ").strip())
if amount <= 0:
print("Invalid amount. Please enter a positive number.")
elif amount > balance:
print("Insufficient funds! You cannot withdraw more than your current balance.")
else:
balance -= amount
print(f"You have successfully withdrawn ${amount:.2f}. Your new balance is ${balance:.2f}.")
except ValueError:
print("Invalid input! Please enter a valid number.")
def main():
"""Main program loop."""
if not login():
return # Exit the program if login fails
while True:
display_menu()
choice = input("Enter your choice: ").strip()
if choice == "1":
check_balance()
elif choice == "2":
deposit_money()
elif choice == "3":
withdraw_money()
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Execute main
main()
```
%% Output
Incorrect PIN. 2 attempt(s) remaining.
Incorrect PIN. 1 attempt(s) remaining.
Incorrect PIN. 0 attempt(s) remaining.
Too many failed attempts. Exiting system.
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment