Below are 10 typed Python programs that utilize the Optional type from the typing module, along with type annotations for undefined functions.
Program 1: Safe Division
from typing import Optional
def safe_divide(x: float, y: float) -> Optional[float]:
"""Divides x by y, returning None if y is zero."""
if y == 0:
return None
return x / y
result = safe_divide(10, 2)
print(result) # Output: 5.0
Program 2: Find User by ID
from typing import Optional, Dict
def find_user_by_id(user_id: int, database: Dict[int, str]) -> Optional[str]:
"""Finds a user by their ID in the database, returning None if not found."""
return database.get(user_id, None)
users_db = {1: "Alice", 2: "Bob"}
user = find_user_by_id(1, users_db)
print(user) # Output: Alice
Program 3: Get First Element
from typing import List, Optional
def get_first_element(elements: List[int]) -> Optional[int]:
"""Returns the first element of the list, or None if the list is empty."""
return elements[0] if elements else None
first = get_first_element([1, 2, 3])
print(first) # Output: 1
Program 4: Lookup Price
from typing import Optional, Dict
def lookup_price(item: str, prices: Dict[str, float]) -> Optional[float]:
"""Looks up the price of an item and returns None if the item doesn't exist."""
return prices.get(item)
price_list = {"apple": 0.5, "banana": 0.75}
price = lookup_price("orange", price_list)
print(price) # Output: None
Program 5: Parse Integer
from typing import Optional
def parse_integer(value: str) -> Optional[int]:
"""Parses a string to an integer, returning None if conversion fails."""
try:
return int(value)
except ValueError:
return None
number = parse_integer("42")
print(number) # Output: 42
invalid_number = parse_integer("abc")
print(invalid_number) # Output: None
Program 6: Get Element from Dictionary
from typing import Optional, Dict
def get_value(key: str, data: Dict[str, int]) -> Optional[int]:
"""Gets the value for a given key from the dictionary, returning None if not found."""
return data.get(key)
data_dict = {'a': 1, 'b': 2}
value = get_value('a', data_dict)
print(value) # Output: 1
missing_value = get_value('c', data_dict)
print(missing_value) # Output: None
Program 7: Find Maximum Value
from typing import List, Optional
def find_maximum(numbers: List[int]) -> Optional[int]:
"""Returns the maximum value in the list, or None if the list is empty."""
return max(numbers) if numbers else None
max_value = find_maximum([1, 3, 5])
print(max_value) # Output: 5
empty_max = find_maximum([])
print(empty_max) # Output: None
Program 8: Get User Email
from typing import Optional, Dict
def get_user_email(user_id: int, user_data: Dict[int, Dict[str, str]]) -> Optional[str]:
"""Retrieves a user's email by ID, returning None if not found."""
user = user_data.get(user_id)
return user['email'] if user else None
users_info = {1: {'name': 'Alice', 'email': 'alice@example.com'}}
email = get_user_email(1, users_info)
print(email) # Output: alice@example.com
missing_email = get_user_email(2, users_info)
print(missing_email) # Output: None
Program 9: Remove Item from List
from typing import List, Optional
def remove_item(items: List[str], item: str) -> Optional[List[str]]:
"""Removes an item from the list and returns the updated list or None if the item was not found."""
if item in items:
items.remove(item)
return items
return None
updated_list = remove_item(['apple', 'banana', 'orange'], 'banana')
print(updated_list) # Output: ['apple', 'orange']
not_found = remove_item(['apple', 'orange'], 'grape')
print(not_found) # Output: None
Program 10: Get Age
from typing import Optional, Dict
def get_age(person_id: int, info: Dict[int, Dict[str, int]]) -> Optional[int]:
"""Gets the age of a person by ID, returning None if not found."""
person = info.get(person_id)
return person['age'] if person else None
people_info = {1: {'name': 'Alice', 'age': 30}}
age = get_age(1, people_info)
print(age) # Output: 30
missing_age = get_age(2, people_info)
print(missing_age) # Output: None
These programs demonstrate the use of the Optional type in various scenarios, providing None where a value may not be available. Each program also includes comments explaining the functionality and type annotations.