PYTHON PROGRAMMING
1. Understanding selection, iteration, assignment, and output in Python:
o Selection: Utilizes if, elif, and else statements to execute certain code
based on conditions.
Example:
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You just became an adult.")
else:
print("You are an adult.")
o Iteration: Uses loops to repeat code blocks.
o Assignment: Assigning values to variables using the = operator.
o Output: Displaying information to the user via the print() function.
2. Creating lists (arrays) and adding string values:
o Lists are ordered collections that can hold a variety of data types,
including strings.
o Example:
fruits = ["apple", "banana", "cherry"]
[Link]("orange") # Adding a new string to the list
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
3. Reading and predicting program output:
o Understanding the flow of a program and determining what output will
occur based on given input.
o Example:
x = 10
if x > 5:
print("Greater than five")
else:
print("Not greater than five")
#Predict the output: "Greater than five".
4. Using loops (for, while) to process user input dynamically:
o For loop example:
for i in range(5):
print("Iteration", i)
o While loop example:
count = 0
while count < 5:
print("Count is", count)
count += 1
5. Counting items in a list using len():
o The len() function returns the number of items in a list.
o Example:
o colors = ["red", "blue", "green"]
o print(len(colors)) # Output: 3
6. Debugging errors in code and fixing them:
o Identify syntax errors and logical errors by running the code and observing
the output, using print statements or debuggers.
o Example:
o result = 10 / 0 # This will raise an error: ZeroDivisionError
o Fixing it might involve checking for division by zero beforehand.
7. Using list operations (append(), remove(), sort(), modifying elements):
o Append: Adds an item to the end of the list.
o Remove: Deletes the first occurrence of a specified value.
o Sort: Organizes the list in ascending order.
o Example:
numbers = [5, 3, 8]
[Link](1)
[Link](3)
[Link]()
print(numbers)
# Output: [1, 5, 8]
Writing programs that modify lists dynamically:
Deleting an item from a list:
chores = ["laundry", "dishes", "vacuum"]
[Link]("dishes")
print(chores)
# Output: ['laundry', 'vacuum']
Correcting misspelled words in a list:
misspelled = ["aple", "bannana", "cherry"]
corrected = ["apple" if word == "aple" else word for word in misspelled]
print(corrected)
# Output: ['apple', 'bannana', 'cherry']
Adding new items to a list:
tasks = ["write report", "fix bugs"]
[Link]("review code")
print(tasks) # Output: ['write report', 'fix bugs', 'review code']
Sorting lists alphabetically:
names = ["John", "Alice", "Bob"]
[Link]()
print(names)
# Output: ['Alice', 'Bob', 'John']