PYTHON ASSIGNMENT 3
Advanced Use of input()
Student Name: ______________________
Class: ______________________
Date: ______________________
1. Enter a Valid Number
Code:
while True:
user_input = input("Enter a number: ")
try:
number = float(user_input)
print("Valid number:", number)
break
except ValueError:
print("Invalid input")
Explanation:
This program keeps asking the user for input until a valid number is entered. It uses
try/except to prevent crashing when text is entered.
2. No Empty Input
Code:
while True:
name = input("Enter your name: ").strip()
if name == "":
print("Try again")
else:
print("Hello", name)
break
Explanation:
This ensures the user does not enter an empty value. strip() removes spaces.
3. Remove Spaces
Code:
word = input("Enter a word: ")
print([Link]())
Explanation:
strip() removes unnecessary spaces before and after the word.
4. Case Handling
Code:
text = input("Type yes: ").lower()
if text == "yes":
print("Correct")
else:
print("Wrong")
Explanation:
lower() converts all input to lowercase so different cases are accepted.
5. Split Input
Code:
parts = input("Enter two numbers: ").split()
print(float(parts[0]) + float(parts[1]))
Explanation:
split() separates the input into parts. Then numbers are added.
6. Full Name Split
Code:
name = input("Enter full name: ").split()
print("First:", name[0])
print("Last:", name[-1])
Explanation:
This splits full name into parts and prints first and last names.
7. Sentinel Control
Code:
while True:
text = input("Type (exit to stop): ")
if text == "exit":
break
Explanation:
The loop continues until the user types 'exit'.
8. Limited Attempts
Code:
pin = "1234"
for i in range(3):
user = input("Enter PIN: ")
if user == pin:
print("Access granted")
break
else:
print("Blocked")
Explanation:
User has only 3 attempts. If all fail, access is blocked.
9. Smart Calculator
Code:
a, op, b = input("Enter: ").split()
a = float(a)
b = float(b)
if op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(a / b)
Explanation:
This program reads a full expression, splits it, and performs calculation.
10. Input Analyzer
Code:
data = input("Enter anything: ")
try:
float(data)
print("Number")
except:
print("Text")
Explanation:
This checks whether the input is a number or text using try/except.