Fruit shop management system

Fruit shop management system

MediumFunction Programs · 30 of 39

Write a Python program with functions to add stock, sell fruit and show the inventory of a fruit shop.

Output
Sold 5 apple for Rs 600
Cannot sell 40 mango
apple    qty  45  Rs 120/kg
mango    qty  30  Rs 80/kg

Approach

  1. Keep the stock in a dictionary.
  2. Write one small function per action and a short script that uses them.

Solution

Python
stock = {} def add_fruit(name, qty, price):    item = stock.setdefault(name, {"qty": 0, "price": price})    item["qty"] += qty    item["price"] = price def sell(name, qty):    item = stock.get(name)    if not item or item["qty"] < qty:        return f"Cannot sell {qty} {name}"    item["qty"] -= qty    return f"Sold {qty} {name} for Rs {qty * item['price']}" def show():    for name, item in stock.items():        print(f"{name:<8} qty {item['qty']:>3}  Rs {item['price']}/kg") add_fruit("apple", 50, 120)add_fruit("mango", 30, 80)print(sell("apple", 5))print(sell("mango", 40))show()
Output
Sold 5 apple for Rs 600
Cannot sell 40 mango
apple    qty  45  Rs 120/kg
mango    qty  30  Rs 80/kg

Line by line

Lines 3-6

setdefault creates the fruit on first use; later calls add to the quantity and update the price.

Lines 8-13

sell refuses unknown fruit or too large an order before changing anything.

Lines 15-17

show prints a neat inventory table.

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Return the sum

Return the sum

EasyFunction Programs · 29 of 39

Write a Python function that returns the sum of two numbers, and show the difference between print and return.

Input
10, 15
Output
25 30

Approach

  1. A returned value can be used in further calculations.

Solution

Python
def add(a, b):    return a + b result = add(10, 15)print(result, add(result, 5))
Output
25 30

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Login function

Login function

EasyFunction Programs · 28 of 39

Write a Python function that accepts a username and password and reports whether login succeeded.

Input
admin / Admin@123
Output
Username: admin
Password: Admin@123
Welcome, admin!

Approach

  1. Read both values with input() and compare them inside a function.

Solution

Python
USERS = {"admin": "Admin@123", "asha": "Test#2026"} def login():    user = input("Username: ")    pwd = input("Password: ")    if USERS.get(user) == pwd:        print(f"Welcome, {user}!")        return True    print("Invalid username or password")    return False login()
Outputtyped input: admin, Admin@123
Username: admin
Password: Admin@123
Welcome, admin!

Line by line

Line 6

USERS.get(user) is None for unknown users, so the comparison fails safely.

Line 9

One message for both cases avoids telling an attacker which part was wrong.

Tip

Use getpass.getpass() instead of input() for passwords in a real terminal program, so the password is not shown while typing.

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Odd numbers from 1 to 100

Odd numbers from 1 to 100

EasyFunction Programs · 27 of 39

Write a Python function that returns the odd numbers from 1 to 100.

Output
50 [1, 3, 5, 7, 9] ... [95, 97, 99]

Approach

  1. list(range(1, 101, 2)).

Solution

Python
def odds(limit=100):    return list(range(1, limit + 1, 2)) result = odds()print(len(result), result[:5], "...", result[-3:])
Output
50 [1, 3, 5, 7, 9] ... [95, 97, 99]

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Primes from 1 to 100

Primes from 1 to 100

EasyFunction Programs · 26 of 39

Write a Python function that returns the prime numbers from 1 to 100.

Output
25 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Approach

  1. Reuse a prime test inside a comprehension.

Solution

Python
def is_prime(n):    return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) def primes_upto(limit):    return [n for n in range(1, limit + 1) if is_prime(n)] primes = primes_upto(100)print(len(primes), primes)
Output
25 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Dictionary keyed by first and last letters

Dictionary keyed by first and last letters

EasyFunction Programs · 25 of 39

Write a Python function that maps the first and last letter of each word to the word.

Input
"Python is easy to learn"
Output
{'Pn': 'Python', 'is': 'is', 'ey': 'easy', 'to': 'to', 'ln': 'learn'}

Approach

  1. Key is w[0] + w[-1].

Solution

Python
def word_map(text):    return {w[0] + w[-1]: w for w in text.split()} print(word_map("Python is easy to learn"))
Output
{'Pn': 'Python', 'is': 'is', 'ey': 'easy', 'to': 'to', 'ln': 'learn'}

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Square every dictionary value

Square every dictionary value

EasyFunction Programs · 24 of 39

Write a Python function that returns a new dictionary with every value squared.

Input
{"a": 4, "b": 3, "c": 12, "d": 6}
Output
{'a': 16, 'b': 9, 'c': 144, 'd': 36}

Approach

  1. Dict comprehension.

Solution

Python
def square_values(d):    return {k: v * v for k, v in d.items()} print(square_values({"a": 4, "b": 3, "c": 12, "d": 6}))
Output
{'a': 16, 'b': 9, 'c': 144, 'd': 36}

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Duplicate characters

Duplicate characters

EasyFunction Programs · 23 of 39

Write a Python function that returns the characters that appear more than once.

Input
"Programming"
Output
['g', 'm', 'r']

Approach

  1. Count with Counter and keep counts above 1.

Solution

Python
from collections import Counter def duplicates(text):    counts = Counter(text.lower())    return sorted(ch for ch, n in counts.items() if n > 1) print(duplicates("Programming"))
Output
['g', 'm', 'r']

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Unique values with dict.fromkeys

Unique values with dict.fromkeys

EasyFunction Programs · 22 of 39

Write a Python function to get the unique values of a list in order.

Input
[4, 6, 1, 7, 6, 1, 5]
Output
[4, 6, 1, 7, 5]

Approach

  1. list(dict.fromkeys(items)).

Solution

Python
def unique(items):    return list(dict.fromkeys(items)) print(unique([4, 6, 1, 7, 6, 1, 5]))
Output
[4, 6, 1, 7, 5]

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Does any pair sum to 10?

Does any pair sum to 10?

EasyFunction Programs · 21 of 39

Write a Python function that checks whether any two numbers in a list add up to 10.

Input
[2, 5, 6, 4, 7, 3, 8, 9, 1]
Output
True False

Approach

  1. Keep a set of numbers seen; for each number check whether 10 - n was seen.

Solution

Python
def has_pair(numbers, target=10):    seen = set()    for n in numbers:        if target - n in seen:            return True        seen.add(n)    return False print(has_pair([2, 5, 6, 4, 7, 3, 8, 9, 1]), has_pair([1, 2, 3]))
Output
True False

Line by line

Line 4

If the partner value was already seen, a pair exists. This needs one pass instead of checking every pair.

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs