Welcome to Python Programming!
In the previous chapters, you learned about algorithms and flowcharts—the "blueprints" of a program. Now, it's time to learn Python, the language we use to actually build those programs. Python is famous for being easy to read and write, almost like English! Don't worry if it looks like a lot at once; we will take it one step at a time.
1. Storing Information: Variables and Literals
Before a computer can process data, it needs a place to keep it. Think of a Variable as a storage box with a label on it. You can put a value inside the box and use the label to find it later.
A Literal is the actual value you put inside. For example, in the code score = 10, score is the variable and 10 is the literal.
Naming your "Boxes" (Identifiers)
When naming variables, remember these rules:
- Must start with a letter (a-z, A-Z) or an underscore (_).
- Can contain numbers, but cannot start with one.
- Python is case-sensitive: Score and score are two different boxes!
Quick Review: Use Variables to store values you want to change or remember later. Use Literals when you want to use a value directly in your code.
2. Talking to the Computer: Input and Output
Programs are most useful when they can "talk" to the user.
- print(): This sends information to the screen. print("Hello!")
- input(): This pauses the program and waits for the user to type something on the keyboard.
Common Mistake: Everything a user types into an input() function is treated as a String (text). If you want to use it as a number, you must convert it using int() or float().
3. Data Types: Numbers and Logic
Python needs to know what "kind" of data it is dealing with to perform calculations correctly.
Numbers
- int: Whole numbers (e.g., 5, -10, 100).
- float: Numbers with decimals (e.g., 3.14, -0.5).
Arithmetic Operators
Python can do math just like a calculator:
- + , - , * , / : Basic math.
- // (Floor Division): Divides and rounds down to the nearest whole number.
- % (Modulo): Gives you the remainder of a division. (Great for checking if a number is even or odd!)
- ** (Exponentiation): Power of (e.g., \( 2^{3} \) is written as 2 ** 3).
Booleans and Logic
A Boolean value is either True or False. We use logic operators to combine them:
- and: True only if BOTH sides are true.
- or: True if AT LEAST ONE side is true.
- not: Flips the value (True becomes False).
Key Takeaway: Use int for counting items and float for measurements like weight or height.
4. Working with Text: Strings
A String is a sequence of characters inside quotes. Imagine it like a string of beads, where each bead is a letter or symbol.
String Tricks
- Concatenation (+): Gluing strings together. "Hello" + " " + "World".
- Repetition (*): Repeating a string. "Ha" * 3 becomes "HaHaHa".
- Indexing: Finding a character at a specific spot. Crucial: Python starts counting at 0! "Python"[0] is "P".
- Slicing: Taking a chunk of text. "Python"[0:2] gives you "Py".
Checking your Strings
Python has built-in tests you can use on strings:
- .isdigit(): Is the string all numbers?
- .isalpha(): Is it all letters?
- .isupper() / .islower(): Is it all big or small letters?
Did you know? You can find the ASCII value of a character using ord('A') and turn a number back into a character using chr(65).
5. Organizing Data: Lists and Dictionaries
Sometimes you need to store many pieces of information together.
Lists
A List is an ordered collection of items (like a shopping list). You use square brackets: fruits = ["apple", "banana", "cherry"].
- len(fruits): Tells you how many items are in the list.
- min() / max(): Find the smallest or largest value.
- sum(): Adds up all the numbers in a list.
- in: Checks if an item exists in the list (e.g., "apple" in fruits).
Dictionaries
A Dictionary works like a real-life dictionary or an address book. It uses Keys and Values. student = {"name": "Ali", "age": 16}. To get the name, you ask for student["name"].
Key Takeaway: Use Lists when the order of items matters. Use Dictionaries when you want to label your data for easy lookup.
6. Making Decisions: Selection
Computers make decisions using Selection (if-statements). It’s like a fork in the road.
if (condition):
# do this if true
elif (another condition):
# do this if the first was false but this one is true
else:
# do this if nothing else was true
Memory Aid: Always remember the colon (:) at the end of the if line and indent (space) the code underneath!
7. Doing it Again: Iteration
Iteration (Loops) allows you to repeat code without typing it over and over.
- for loop: Used when you know exactly how many times to repeat (e.g., for i in range(5):).
- while loop: Used when you want to repeat until something changes (e.g., while lives > 0:).
8. Functions: Mini-Programs
A Function is a block of code that performs a specific task. You "call" it whenever you need it.
def greet(name):
return "Hello " + name
- Parameters: The info you give to the function (the name).
- Return value: The "answer" the function gives back.
Local vs. Global Variables
Imagine a Global variable as a public park—everyone in the program can see and use it. A Local variable is like a private backyard inside a function—only that specific function knows it exists.
9. Handling Files
To save data permanently, we use files. Think of it like opening a cabinet, reading a folder, and then closing the cabinet.
- open(): Get the file ready. (Use "r" for reading or "w" for writing).
- read() / readline() / write(): Do the work.
- close(): Always close the file when done to save your work!
Quick Review: Using the with keyword (e.g., with open(...) as f:) is the safest way to handle files because it closes them automatically for you!
10. Using Extra Tools: Import
Python has "toolboxes" called modules that you can borrow. To use them, use the import command.
- import math: Gives you tools like math.sqrt() (square root) and math.ceil() (rounding up).
- import random: Gives you random.randint(1, 10) to pick a random number.
Encouragement: Coding is a skill like playing an instrument. Don't worry if your code doesn't work the first time—debugging is where the real learning happens!