INPUT NOTES COMMENTED
# 1. Data Types and Examples
integers = []
integers.append(int(input("Enter an integer: "))) # Use for
whole numbers, e.g., age
floats = []
floats.append(float(input("Enter a float: "))) # Use for
decimal numbers, e.g., price
strings = []
strings.append(input("Enter a string: ")) # Use for text,
e.g., name
booleans = []
booleans.append(bool(int(input("Enter 1 for True or 0 for
False: ")))) # Use for yes/no questions
tuples = []
tuples.append(tuple(input("Enter comma-separated values for a
tuple: ").split(','))) # Use for fixed collections, e.g.,
coordinates
print("\nData Types Examples:")
print(f"Integer: {integers[0]}")
print(f"Float: {floats[0]}")
print(f"String: {strings[0]}")
print(f"Boolean: {booleans[0]}")
print(f"Tuple: {tuples[0]}")
# 2. Arithmetic Operations
num1 = int(input("Enter first number: ")) # Use when you need
integer math
num2 = float(input("Enter second number: ")) # Use when
precision is important
result = num1 + num2
print(f"Sum: {result}")
# 3. String Operations
first_name = input("Enter your first name: ") # Use for
single-word text input
last_name = input("Enter your last name: ") # Use for single-
word text input
full_name = f"{first_name} {last_name}"
print(f"Full name: {full_name}")
# 4. Lists
my_list = []
item = input("Enter an item for the list: ") # Use for
collecting multiple items
my_list.append(item)
print(f"List: {my_list}")
# 5. Dictionaries
my_dict = {}
key = input("Enter a key for the dictionary: ") # Use for
naming categories
value = input("Enter a value for the dictionary: ") # Use for
assigning to categories
my_dict[key] = value
print(f"Dictionary: {my_dict}")
# 6. Type Conversion
str_num = input("Enter a number as a string: ") # Use when
input might not be a valid number
try:
int_num = int(str_num) # Convert to integer if possible
print(f"Converted to integer: {int_num}")
except ValueError:
print("Cannot convert to integer")
# 7. Conditional Statements
age = int(input("Enter your age: ")) # Use for age-restricted
content
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# 8. Loops
n = int(input("How many times to repeat? ")) # Use for
controlled repetition
for i in range(n):
print(f"Repetition {i+1}")
# 9. Functions
def greet(name):
return f"Hello, {name}!"
user_name = input("Enter your name: ") # Use for personalized
greetings
print(greet(user_name))
# 10. List Comprehension
numbers = [int(x) for x in input("Enter space-separated
numbers: ").split()] # Use for quick list creation
squares = [x**2 for x in numbers]
print(f"Squares: {squares}")
# 11. Error Handling
try:
dividend = int(input("Enter the dividend: ")) # Use when
division is involved
divisor = int(input("Enter the divisor: ")) # Use when
division is involved
divisor = int(input("Enter the divisor: ")) # Use when
division is involved
result = dividend / divisor
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero")
except ValueError:
print("Error: Please enter valid integers")
# 12. File Operations
filename = input("Enter the filename to write to: ") # Use
for file I/O operations
with open(filename, 'w') as f:
f.write(input("Enter text to write to the file: ")) # Use
for content creation
# 13. Multiple Inputs on One Line
x, y = map(int, input("Enter two numbers separated by space:
").split()) # Use for related inputs
print(f"Sum: {x + y}")
# 14. Input Validation
while True:
password = input("Enter a password (at least 8
characters): ") # Use for secure input
if len(password) >= 8:
print("Password accepted")
break
else:
print("Password too short, try again")
# 15. Dictionary with Multiple Data Types
person = {}
person['name'] = input("Enter name: ") # String input for
name
person['age'] = int(input("Enter age: ")) # Integer input for
age
person['height'] = float(input("Enter height in meters: ")) #
Float input for height
person['is_student'] = input("Are you a student? (yes/no):
").lower() == 'yes' # Boolean input
print(f"Person details: {person}")
# 16. Nested Dictionary
address = {}
address['street'] = input("Enter street name: ") # String
input for street
address['number'] = int(input("Enter house number: ")) #
Integer input for house number
address['city'] = input("Enter city: ") # String input for
city
person['address'] = address # Adding nested dictionary
print(f"Updated person details: {person}")
# 17. Dictionary with List Values
skills = {}
skill_name = input("Enter a skill category: ") # e.g.,
"Programming Languages"
skill_list = input("Enter skills (comma-separated):
").split(',') # List input for skills
skills[skill_name] = skill_list
print(f"Skills: {skills}")
# 18. Tuple of Mixed Data Types
# Tuples are immutable, so we create it in one go
person_tuple = (
input("Enter name: "), # String input for name
int(input("Enter age: ")), # Integer input for age
float(input("Enter height in meters: ")), # Float input
for height
input("Are you a student? (yes/no): ").lower() == 'yes' #
Boolean input
)
print(f"Person tuple: {person_tuple}")
# 19. List of Tuples
people = []
num_people = int(input("How many people to add? ")) # Use
when you need to collect a specific number of entries
for i in range(num_people):
person = (
input(f"Enter name for person {i+1}: "),
int(input(f"Enter age for person {i+1}: "))
) # Use tuples for fixed-size collections of related data
people.append(person) # Use append to add items to a list
print(f"List of people: {people}") # Use this structure for
simple databases or tables
# 20. Dictionary with Tuple Keys
coordinates = {}
while True: # Use while True for indefinite loops (when you
don't know how many iterations you need)
x = float(input("Enter x coordinate (or 'q' to quit): "))
if x == 'q':
break # Use break to exit a loop based on a condition
y = float(input("Enter y coordinate: "))
z = float(input("Enter z coordinate: "))
coordinates[(x, y, z)] = input("Enter location name: ") #
Use tuple keys for multi-dimensional data
print(f"Coordinates: {coordinates}") # Useful for mapping
multi-dimensional data to values
# 21. Complex Nested Structure
company = {
'name': input("Enter company name: "),
'employees': []
} # Use nested structures for hierarchical or complex data
num_employees = int(input("How many employees to add? "))
for i in range(num_employees):
employee = {
'name': input(f"Enter name of employee {i+1}: "),
'position': input(f"Enter position of employee {i+1}:
"),
'skills': input(f"Enter skills of employee {i+1}
(comma-separated): ").split(',') # Use split for parsing
input into lists
}
company['employees'].append(employee) # Append to nested
lists within dictionaries
print("\nCompany Structure:")
print(f"Company Name: {company['name']}")
print("Employees:")
for emp in company['employees']: # Use nested loops to
iterate through complex structures
print(f" Name: {emp['name']}")
print(f" Position: {emp['position']}")
print(f" Skills: {', '.join(emp['skills'])}") # Use
join to convert lists to strings
# 22. Enumerate Example
print("\nEnumerate Example:")
fruits = ['apple', 'banana', 'cherry', 'date']
print("List of fruits with index:")
for index, fruit in enumerate(fruits): # Use enumerate when
you need both index and value
print(f" {index}: {fruit}")
# Using enumerate with a custom start index
print("\nList of fruits with custom start index:")
for index, fruit in enumerate(fruits, start=1): # Use start
parameter to begin counting from a specific number
print(f" {index}: {fruit}")
# Enumerate with unpacking in a dictionary
fruit_colors = {'apple': 'red', 'banana': 'yellow', 'cherry':
'red', 'date': 'brown'}
print("\nFruit colors with enumerate:")
for i, (fruit, color) in enumerate(fruit_colors.items(),
start=1): # Use for numbered lists of key-value pairs
print(f" {i}. {fruit}: {color}")
# Enumerate in list comprehension
squared_indices = [i**2 for i, _ in enumerate(fruits)] # Use
in list comprehensions for index-based operations
print("\nSquared indices of fruits:")
for fruit, squared_index in zip(fruits, squared_indices): #
Use zip to iterate over multiple lists simultaneously
print(f" {fruit}: {squared_index}")