Python User Input
Learn to create interactive programs that respond to user input
āØļø Understanding User Input
User input allows your programs to be interactive and dynamic. Python provides the
input()
function to capture user input from the keyboard, making your programs responsive to user needs and creating engaging experiences.
# Getting different types of input from user
number = int(input("Enter a number: ")) # Integer
decimal = float(input("Enter a decimal: ")) # Float
text = input("Enter some text: ") # String
is_valid = input("Enter True or False: ") # Bool string
The input() Function
The
input()
function is Python's built-in way to get user input. It always returns a string, regardless of what the user types.
# Basic input example
name = input("What is your name? ")
print(f"Hello, {name}!")
# Input with different prompts
age = input("How old are you? ")
city = input("Which city do you live in? ")
print(f"Nice to meet you, {name}!")
print(f"You are {age} years old and live in {city}.")
# Example interaction:
# What is your name? Alice
# How old are you? 25
# Which city do you live in? New York
# Hello, Alice!
# Nice to meet you, Alice!
# You are 25 years old and live in New York.
ā ļø Important Note
The
input()
function always returns a
string
, even if the user enters numbers. You need to convert the input to the appropriate data type if needed.
Converting Input Types
Since
input()
always returns strings, you often need to convert the input to other data types for calculations or comparisons.
Integer Input
# Convert to integer
age_str = input("Enter your age: ")
age = int(age_str)
# Or do it in one line
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")
print(f"Type of age: {type(age)}")
Float Input
# Convert to float
height = float(input("Enter your height in meters: "))
weight = float(input("Enter your weight in kg: "))
bmi = weight / (height ** 2)
print(f"Your BMI is: {bmi:.2f}")
Boolean Input
# Convert to boolean
response = input("Do you like Python? (yes/no): ")
likes_python = response.lower() in ['yes', 'y', 'true', '1']
print(f"Likes Python: {likes_python}")
print(f"Type: {type(likes_python)}")
List Input
# Convert to list
numbers_str = input("Enter numbers separated by commas: ")
numbers = [int(x.strip()) for x in numbers_str.split(',')]
print(f"Numbers: {numbers}")
print(f"Sum: {sum(numbers)}")
Input Validation
It's important to check user input to make sure it's valid before using it in your program.
# Check if age is a valid number
while True:
age = input("Enter your age: ")
try:
age = int(age)
if age >= 0 and age <= 120:
print(f"Your age is {age}")
break
else:
print("Age must be between 0 and 120")
except ValueError:
print("Please enter a valid number")
# Make sure name is not empty
while True:
name = input("Enter your name: ").strip()
if name:
print(f"Hello {name}!")
break
print("Name cannot be empty")
# Check if color choice is valid
colors = ['red', 'blue', 'green']
while True:
color = input(f"Choose a color ({', '.join(colors)}): ").lower()
if color in colors:
print(f"You chose {color}")
break
print("Invalid color choice")
# Example interaction:
# Enter your age: abc
# Please enter a valid number
# Enter your age: 25
# Your age is 25
# Enter your name:
# Name cannot be empty
# Enter your name: John
# Hello John!
# Choose a color (red, blue, green): yellow
# Invalid color choice
# Choose a color (red, blue, green): blue
# You chose blue
Getting Multiple Inputs
Let's learn simple ways to get multiple inputs from users.
š¹ Basic Multiple Inputs
# Getting basic information
name = input("What's your name? ")
age = input("How old are you? ")
print(f"Hello {name}, you are {age} years old!")
š¹ Getting Multiple Numbers
# Getting two numbers and adding them
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
total = num1 + num2
print(f"The sum is: {total}")
š¹ Using a Simple Loop
# Getting names of 3 friends
friends = []
for i in range(3):
name = input(f"Enter friend {i+1}'s name: ")
friends.append(name)
print("Your friends are:", friends)
š¹ Simple Stop Condition
# Keep getting input until user types 'stop'
colors = []
print("Enter colors (type 'stop' to finish):")
while True:
color = input("Enter a color: ")
if color == 'stop':
break
colors.append(color)
print("Your colors are:", colors)
Advanced Input Techniques
import getpass
import sys
def secure_login():
"""Demonstrate secure password input."""
print("š Secure Login Demo")
username = input("Username: ")
# Use getpass for hidden password input
try:
password = getpass.getpass("Password: ")
print(f"Login attempt for user: {username}")
print(f"Password length: {len(password)} characters")
# Note: Never print actual passwords!
except KeyboardInterrupt:
print("\nLogin cancelled.")
return None
return username, password
def get_multiline_input():
"""Get multiple lines of input from user."""
print("š Enter your message (press Ctrl+D or Ctrl+Z to finish):")
lines = []
try:
while True:
line = input()
lines.append(line)
except EOFError:
pass # User pressed Ctrl+D (Unix) or Ctrl+Z (Windows)
return '\n'.join(lines)
def interactive_calculator():
"""Interactive calculator with continuous input."""
print("š§® Interactive Calculator")
print("Enter expressions (type 'quit' to exit):")
while True:
try:
expression = input(">>> ")
if expression.lower() in ['quit', 'exit', 'q']:
break
# Evaluate the expression safely
result = eval(expression)
print(f"Result: {result}")
except (ValueError, SyntaxError, NameError) as e:
print(f"Error: Invalid expression - {e}")
except ZeroDivisionError:
print("Error: Division by zero!")
except KeyboardInterrupt:
print("\nCalculator interrupted.")
break
# Example usage
if __name__ == "__main__":
print("Choose a demo:")
print("1. Secure Login")
print("2. Multiline Input")
print("3. Interactive Calculator")
choice = input("Enter choice (1-3): ")
if choice == "1":
credentials = secure_login()
if credentials:
print("Login demo completed!")
elif choice == "2":
message = get_multiline_input()
print(f"\nYou entered:\n{message}")
elif choice == "3":
interactive_calculator()
else:
print("Invalid choice!")
# Note: The getpass module hides password input from the terminal
# This is important for security when handling sensitive information
Real-World Application: Student Registration System
import re
from datetime import datetime
class StudentRegistrationSystem:
"""Complete student registration system with input validation."""
def __init__(self):
self.students = []
self.student_id_counter = 1000
def validate_email(self, email):
"""Validate email format."""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def validate_phone(self, phone):
"""Validate phone number format."""
# Remove all non-digit characters
digits = re.sub(r'\D', '', phone)
# Valid if 10 or 11 digits (with country code)
return len(digits) in [10, 11]
def get_student_info(self):
"""Collect and validate student information."""
print("š Student Registration System")
print("=" * 40)
# Get and validate name
while True:
first_name = input("First Name: ").strip()
if first_name and first_name.isalpha():
break
print("ā Please enter a valid first name (letters only)")
while True:
last_name = input("Last Name: ").strip()
if last_name and last_name.isalpha():
break
print("ā Please enter a valid last name (letters only)")
# Get and validate age
while True:
try:
age = int(input("Age: "))
if 16 <= age <= 100:
break
print("ā Age must be between 16 and 100")
except ValueError:
print("ā Please enter a valid age (number)")
# Get and validate email
while True:
email = input("Email: ").strip().lower()
if self.validate_email(email):
# Check if email already exists
if not any(student['email'] == email for student in self.students):
break
print("ā Email already registered")
else:
print("ā Please enter a valid email address")
# Get and validate phone
while True:
phone = input("Phone Number: ").strip()
if self.validate_phone(phone):
break
print("ā Please enter a valid phone number (10-11 digits)")
# Get program of study
programs = ['Computer Science', 'Engineering', 'Business', 'Arts', 'Science']
print(f"\nAvailable Programs: {', '.join(programs)}")
while True:
program = input("Program of Study: ").strip()
if program in programs:
break
print(f"ā Please choose from: {', '.join(programs)}")
# Get courses
print("\nEnter courses (one per line, press Enter on empty line to finish):")
courses = []
while True:
course = input(f"Course {len(courses) + 1}: ").strip()
if not course:
break
courses.append(course)
if not courses:
print("ā At least one course is required")
return self.get_student_info()
# Confirm information
student_info = {
'id': self.student_id_counter,
'first_name': first_name,
'last_name': last_name,
'age': age,
'email': email,
'phone': phone,
'program': program,
'courses': courses,
'registration_date': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
return student_info
def display_student_info(self, student):
"""Display formatted student information."""
print("\n" + "=" * 50)
print("š STUDENT INFORMATION")
print("=" * 50)
print(f"Student ID: {student['id']}")
print(f"Name: {student['first_name']} {student['last_name']}")
print(f"Age: {student['age']}")
print(f"Email: {student['email']}")
print(f"Phone: {student['phone']}")
print(f"Program: {student['program']}")
print(f"Courses: {', '.join(student['courses'])}")
print(f"Registration Date: {student['registration_date']}")
print("=" * 50)
def confirm_registration(self, student):
"""Confirm registration with user."""
self.display_student_info(student)
while True:
confirm = input("\nConfirm registration? (yes/no): ").lower().strip()
if confirm in ['yes', 'y']:
self.students.append(student)
self.student_id_counter += 1
print(f"ā
Registration successful! Student ID: {student['id']}")
return True
elif confirm in ['no', 'n']:
print("ā Registration cancelled.")
return False
else:
print("Please enter 'yes' or 'no'")
def register_student(self):
"""Complete student registration process."""
try:
student_info = self.get_student_info()
return self.confirm_registration(student_info)
except KeyboardInterrupt:
print("\nā Registration cancelled by user.")
return False
def list_students(self):
"""List all registered students."""
if not self.students:
print("š No students registered yet.")
return
print(f"\nš REGISTERED STUDENTS ({len(self.students)} total)")
print("=" * 60)
for student in self.students:
print(f"ID: {student['id']} | {student['first_name']} {student['last_name']} | {student['program']}")
print("=" * 60)
def run(self):
"""Main program loop."""
print("š Welcome to Student Registration System")
while True:
print("\nš MAIN MENU")
print("1. Register New Student")
print("2. List All Students")
print("3. Exit")
choice = input("\nEnter your choice (1-3): ").strip()
if choice == '1':
self.register_student()
elif choice == '2':
self.list_students()
elif choice == '3':
print("š Thank you for using Student Registration System!")
break
else:
print("ā Invalid choice. Please enter 1, 2, or 3.")
# Example usage
if __name__ == "__main__":
system = StudentRegistrationSystem()
system.run()
# Example interaction:
# š Student Registration System
# ========================================
# First Name: John
# Last Name: Doe
# Age: 20
# Email: [email protected]
# Phone Number: 555-123-4567
#
# Available Programs: Computer Science, Engineering, Business, Arts, Science
# Program of Study: Computer Science
#
# Enter courses (one per line, press Enter on empty line to finish):
# Course 1: Python Programming
# Course 2: Data Structures
# Course 3:
#
# ==================================================
# š STUDENT INFORMATION
# ==================================================
# Student ID: 1000
# Name: John Doe
# Age: 20
# Email: [email protected]
# Phone: 555-123-4567
# Program: Computer Science
# Courses: Python Programming, Data Structures
# Registration Date: 2024-01-15 14:30:25
# ==================================================
#
# Confirm registration? (yes/no): yes
# ā
Registration successful! Student ID: 1000
šļø Practice Exercise: Simple Quiz
Let's create a basic quiz that:
- Asks for your name
- Asks 2 simple questions
- Shows your score
# Simple quiz game
def run_quiz():
# Get player name
name = input("What's your name? ")
print(f"Hi {name}! Let's play a quiz!")
score = 0
total_questions = 2
# Question 1
print("\nQuestion 1: What is the capital of France?")
print("A) London")
print("B) Paris")
print("C) Rome")
answer1 = input("Your answer (A/B/C): ").upper()
if answer1 == "B":
print("Correct!")
score += 1
else:
print("Wrong! The answer is Paris")
# Question 2
print("\nQuestion 2: What is 5 + 3?")
print("A) 7")
print("B) 8")
print("C) 9")
answer2 = input("Your answer (A/B/C): ").upper()
if answer2 == "B":
print("Correct!")
score += 1
else:
print("Wrong! The answer is 8")
# Show results
print("\n--- Quiz Results ---")
print(f"Player: {name}")
print(f"Score: {score}/{total_questions}")
print("Thanks for playing!")
# Run the quiz
run_quiz()