Python Basics: Lists, Tuples, Dictionaries, Formatted Input/Output, and If-Els
1. List
A list is an ordered, mutable collection of items, and it allows duplicates. Lists are defined by square
brackets [].
Basic Operations:
- Creating a List: my_list = [1, 2, 3, 4, 5]
- Accessing Items: print(my_list[0]) # Outputs: 1
- Modifying Items: my_list[2] = 10 # Changes the third item to 10
- Appending and Removing Items:
my_list.append(6) # Adds 6 to the end
my_list.remove(4) # Removes the first occurrence of 4
Useful Functions:
- len(my_list) - Returns the number of items
- sorted(my_list) - Returns a sorted version of the list
- my_list.pop() - Removes the last item and returns it
2. Tuple
A tuple is an ordered, immutable collection. Tuples are defined by parentheses () and are often used
for storing multiple items that should not change.
Basic Operations:
- Creating a Tuple: my_tuple = (1, 2, 3)
- Accessing Items: print(my_tuple[1]) # Outputs: 2
- Tuple Unpacking:
a, b, c = my_tuple
print(a, b, c) # Outputs: 1 2 3
Useful Functions:
- len(my_tuple) - Returns the length
- my_tuple.count(2) - Counts occurrences of an item
- my_tuple.index(3) - Returns the index of the first occurrence of 3
3. Dictionary
A dictionary is a collection of key-value pairs. It is unordered, mutable, and defined with curly braces
{}. Each key must be unique.
Basic Operations:
- Creating a Dictionary: my_dict = {"name": "Alice", "age": 25}
- Accessing and Modifying Items: print(my_dict["name"]) # Outputs: Alice
- Adding and Removing Items:
my_dict["city"] = "New York" # Adds a new key-value pair
del my_dict["name"] # Deletes the 'name' key
Useful Functions:
- my_dict.keys() - Returns all keys
- my_dict.values() - Returns all values
- my_dict.items() - Returns all key-value pairs
4. Formatted Input and Output
Basic Input:
- Taking Input: name = input("Enter your name: ")
- Converting Input: age = int(input("Enter your age: "))
Formatted Output with `print`:
- Basic Formatting: print("Hello, {}. You are {} years old.".format(name, age))
- f-Strings: print(f"Hello, {name}. You are {age} years old.")
Common Formatting Functions:
- Formatting Numbers: number = 123.45678, print(f"{number:.2f}") # Outputs: 123.46
- Padding and Alignment: print(f"{name:<10}") # Left-aligns name in a 10-character field
5. if else Statement
The `if else` statement allows for conditional execution based on whether a condition is `True` or
`False`.
Basic Structure:
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
if elif else Chain:
score = int(input("Enter your score: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Nested if Statements:
age = int(input("Enter your age: "))
is_student = input("Are you a student? (yes/no): ")
if age < 18:
if is_student == "yes":
print("You are a minor student.")
else:
print("You are a minor.")
else:
print("You are an adult.")