5-Lesson Introduction to Python Programming
Lesson 1: Getting Started with Python
High-level, interpreted language known for its readability and simplicity Used for web development, data analysis, automation, and more Setting up your environment Download and install Python from the official website (python.org) Choose a code editor or IDE (e.g., IDLE, Visual Studio Code, PyCharm) Your first program: "Hello, World!" Write and run the classic program to display "Hello, World!" on the console Understand the print() function Lesson 2: Variables and Data Types
Variables
What are variables? Think of variables as labeled boxes where you can store different types of data. They make it easy to manipulate and reference information in your Python programs. Assigning values to variables: You use the = operator to assign a value to a variable. The variable name goes on the left, and the value you want to store goes on the right. Python# Examples of assigning values to variables name = "Alice" # Assigning a string to the variable 'name' age = 30 # Assigning an integer to the variable 'age' price = 19.99 # Assigning a float (decimal number) to the variable 'price' is_student = True # Assigning a boolean value to the variable 'is_student' Naming conventions for variables: Variable names should be descriptive and meaningful. Start with a letter or underscore (_), followed by letters, numbers, or underscores. Avoid using reserved keywords (like if, for, while) as variable names. Use lowercase letters for variable names, and separate words with underscores (e.g., my_variable_name). Data Types
Basic data types: Python has several built-in data types to represent different kinds of information: Integers (int): Whole numbers without decimals (e.g., 5, -10, 0). Floats (float): Numbers with decimals (e.g., 3.14, -0.5, 100.0). Strings (str): Sequences of characters enclosed in single quotes (') or double quotes ("). Used to represent text. Pythongreeting = "Hello, world!" my_name = 'Bob' Booleans (bool): Represent logical values, either True or False. Used for making decisions in your code. You can convert between data types using built-in functions: int(): Converts a value to an integer (if possible). float(): Converts a value to a float (if possible). str(): Converts a value to a string. Python# Examples of type conversion number_str = "123" number_int = int(number_str) # Converts the string "123" to the integer 123 price_float = 25.50 price_str = str(price_float) # Converts the float 25.50 to the string "25.50" Practice
Create variables to store your name, age, favorite color, and whether you like pizza (True or False). Print the values of these variables using the print() function. Convert your age to a string and print the result. Try converting a string like "hello" to an integer and observe what happens. Remember, understanding variables and data types is fundamental to writing Python programs. Practice using them and experimenting with different types to solidify your understanding!
## Lesson 3: Control Flow and Loops
**Conditional Statements (if/elif/else)**
* **Making decisions in your code:** Conditional statements allow your program to execute different blocks of code depending on whether certain conditions are met. This is how you introduce decision-making logic into your programs.
* **Comparison Operators:** These operators are used to compare values and return a Boolean (`True` or `False`) result:
* `==` (equal to)
* `!=` (not equal to)
* `>` (greater than)
* `<` (less than)
* `>=` (greater than or equal to)
* `<=` (less than or equal to)
* **Logical Operators:** These operators combine multiple conditions:
* `and` (both conditions must be True)
* `or` (at least one condition must be True)
* `not` (inverts the truth value of a condition)
**Example: `if/elif/else`**
```python
age = 25
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
```
**Loops (for and while)**
* **Repeating blocks of code:** Loops allow you to execute a block of code repeatedly, either a specific number of times or as long as a certain condition remains true.
* **`for` loops:** Used to iterate over a sequence (like a list or string), executing the code block once for each item in the sequence.
**Example: `for` loop**
```python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
```
* **`while` loops:** Continue executing the code block as long as a specified condition is true. Be careful to ensure the condition eventually becomes false to avoid infinite loops.
**Example: `while` loop**
```python
count = 0
while count < 5:
print("Count:", count)
count += 1 # Increment count by 1
```
**Practice**
1. Write a program that asks the user for their age and tells them if they are eligible to vote (age >= 18).
2. Create a list of numbers and use a `for` loop to calculate their sum.
3. Write a program that uses a `while` loop to print the numbers from 1 to 10.
4. Experiment with combining comparison and logical operators in your conditional statements.
**Key Points**
* Indentation is crucial in Python to define code blocks within control flow structures and loops.
* Use `break` to exit a loop prematurely and `continue` to skip the rest of the current iteration and move to the next one.
* Loops and conditionals are essential building blocks for creating more complex and dynamic programs.
Remember, practice is key to mastering control flow and loops. Keep experimenting and challenging yourself with different scenarios to solidify your understanding!
Lesson 4: Functions
Defining and Calling Functions
Reusable blocks of code: Functions are self-contained blocks of code that perform specific tasks. They help you organize your code, make it more readable, and avoid repetition. def keyword: You use the def keyword to define a function, followed by the function name, parentheses for arguments (if any), and a colon. The code block within the function is indented. Passing arguments: Arguments are values you pass to a function when you call it, allowing the function to work with different data each time it's called. Returning values: Functions can optionally return a value using the return statement. This allows you to get output from the function and use it in other parts of your program. Example: Function Definition and Call
Pythondef greet(name): # Function definition with one argument 'name' """This function greets the person whose name is passed as an argument.""" print("Hello, " + name + "!") greet("Alice") # Function call with the argument "Alice" greet("Bob") # Function call with the argument "Bob"
Built-in Functions
Exploring common functions: Python provides many built-in functions that perform various tasks. Here are a few examples: len(): Returns the length (number of items) of a sequence (e.g., list, string). input(): Prompts the user for input and returns it as a string. type(): Returns the data type of a value. print(): Displays output on the console. int(), float(), str(): Convert between data types (as seen in Lesson 2). Example: Using Built-in Functions
Pythonmy_list = [1, 2, 3, 4] list_length = len(my_list) print("Length of the list:", list_length) # Output: Length of the list: 4 name = input("Enter your name: ") print("Hello,", name, "!") value = 10 data_type = type(value) print("Data type of value:", data_type) # Output: Data type of value: <class 'int'>
Practice
Write a function that takes two numbers as arguments and returns their sum. Create a function that takes a string as input and prints each character on a separate line. Use the input() function to get the user's name and age, and then print a personalized greeting using a function. Experiment with other built-in functions and explore their documentation to learn more about their capabilities. Key Points
Functions promote code reusability and modularity, making your programs easier to manage and understand. Docstrings (the string within triple quotes below the function definition) are used to document what a function does and how to use it. Python's vast library of built-in functions provides powerful tools for various tasks, saving you time and effort. Remember: Functions are your friends! Use them to break down complex problems into smaller, manageable pieces, and make your code more elegant and efficient.
## Lesson 5: Lists and Basic Data Structures
**Lists**
* **Ordered collections:** Lists are versatile data structures that store multiple items in a specific order. You can think of them as a numbered list of things.
* **Creating lists:** Use square brackets `[]` to create a list, separating items with commas.
```python
fruits = ["apple", "banana", "orange"]
numbers = [1, 5, 3, 9, 2]
mixed_list = [10, "hello", True] # Lists can contain different data types
```
* **Accessing elements by index:** Each item in a list has a corresponding index (position), starting from 0. You can access individual elements using their index within square brackets.
```python
first_fruit = fruits[0] # Access the first element (index 0)
print(first_fruit) # Output: apple
second_number = numbers[1] # Access the second element (index 1)
print(second_number) # Output: 5
```
* **Common list operations:**
* `append(item)`: Adds an item to the end of the list
* `insert(index, item)`: Inserts an item at a specific index
* `remove(item)`: Removes the first occurrence of an item
* `pop(index)`: Removes and returns the item at the specified index (defaults to the last item if no index is given)
* `index(item)`: Returns the index of the first occurrence of an item
* `count(item)`: Returns the number of times an item appears in the list
* `sort()`: Sorts the list in ascending order (modifies the original list)
* `reverse()`: Reverses the order of the list (modifies the original list)
```python
fruits.append("grape") # Add "grape" to the end
fruits.insert(1, "kiwi") # Insert "kiwi" at index 1
fruits.remove("banana") # Remove "banana"
last_fruit = fruits.pop() # Remove and return the last item
print(last_fruit) # Output: grape
index_of_orange = fruits.index("orange")
print(index_of_orange) # Output: 2
numbers.sort()
print(numbers) # Output: [1, 2, 3, 5, 9]
numbers.reverse()
print(numbers) # Output: [9, 5, 3, 2, 1]
```
**Other Data Structures (Brief Overview)**
* **Dictionaries:** Store data as key-value pairs, allowing you to access values using their associated keys.
```python
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"]) # Output: Alice
```
* **Tuples:** Similar to lists, but immutable (cannot be changed after creation). Useful for representing fixed collections of data.
```python
coordinates = (3, 5) # Create a tuple
# coordinates[0] = 10 # This would cause an error because tuples are immutable
```
* **Sets:** Unordered collections of unique elements. Useful for removing duplicates and performing set operations (union, intersection, etc.).
```python
my_set = {1, 2, 3, 2} # Creates a set with unique elements {1, 2, 3}
```
**Practice & Further Learning**
1. Create a list of your favorite movies and practice accessing elements, adding new movies, and removing ones you no longer like.
2. Use a dictionary to store information about a person (name, age, address, etc.) and practice retrieving specific details.
3. Explore the official Python documentation for lists, dictionaries, tuples, and sets to learn more about their capabilities and methods.
4. Challenge yourself with coding exercises that involve manipulating and working with these data structures.
**Key Takeaways**
* Lists are fundamental for storing and organizing collections of data.
* Dictionaries provide a flexible way to associate keys with values.
* Tuples offer immutability for data that shouldn't change.
* Sets are handy for working with unique elements and performing set operations.
* Mastering data structures is crucial for writing efficient and effective Python programs.
**Remember:** Keep practicing and experimenting! The more you work with lists and other data structures, the more comfortable you'll become using them to solve various programming challenges. Don't hesitate to consult the Python documentation and online resources for further learning and exploration. Happy coding!
Remember: This is a very basic introduction. Python has a vast ecosystem of libraries and modules. After completing these lessons, students will have a solid foundation to continue their Python journey and explore more advanced topics.