Skip to content

Exercises

3.1 — Write sign.py that reads a number and prints positive, negative, or zero.

3.2 — Write login.py: read a username and password; grant access only if both match expected values (use and). Print distinct messages for wrong user vs. wrong password

3.3 — Write grade.py: read a score 0–100 and print the letter grade (A ≥ 90, B ≥ 80, C ≥ 70, D ≥ 60, else F). Also reject scores outside 0–100 with an error message.

3.4 — Write weekday.py: read a day name and print weekend or weekday. Accept any capitalization

3.5 — Write a program palindrome.py that prompts the user to enter a word and prints if it is a palindrome or not.

A palindrome is a word that reads the same when reversed.

Hints
  • 3.2 — nested if: outer if user == ...: then inner if password == ...:.
  • 3.4 — convert to lower case (.lower()) before comparing.
  • 3.5 — the expression [*word] converts word into a list of characters. The built-in function reversed() takes a sequence and returns its reverse. Then .join() the list of characters to form a new word.

Coding challenge — Number classifier program with a menu

Write a menu-driven program classify.py as follows:

  1. Show a menu:
    1) Classify a number
    2) Check divisibility
    3) Compare two numbers
    
  2. Read the user's choice with input().
  3. Branch on the choice:
  4. 1 — read a number; report whether it's positive/negative/zero and even/odd.
  5. 2 — read a number and a divisor; report whether the first is divisible by the second (n % d == 0), making sure to reject divisor 0 with an appropriate error message.
  6. 3 — read two numbers; report which is larger, or whether they're equal.
  7. If the choice isn't 1, 2, or 3, print Unknown option.
  8. Refuse to proceed on any invalid input

Exit program conditionally

It is often better to exit the program rather than proceeding with invalid input. You can do this conditionally using the built-in exit() function:

choice = input("Enter 1, 2 or 3: ")
if not choice.isdigit():
   exit(f"{choice!r} is not a valid number")
choice = int(choice)
if choice not in (1,2,3):
   exit(f"Unknown option {choice}")