Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It's widely used in scientific computing, data science, machine learning, automation (preferred language when automating tasks via scripts), and backend web development.
Python emphasizes code readability and has a syntax that allows developers to write fewer lines of code than other languages like C++ or Java.
1. Execution Order
Python executes code line-by-line, from top to bottom, unless directed otherwise by control structures (like loops or conditionals).
print("First line")
print("Second line")
First line
Second line
2. Printing Text
The print()
function is used to output strings or other data types.
print("Python is fun!")
Strings should be enclosed in quotes (
' '
or" "
), or you will get a syntax error.
- To output a string containing quotation
" "
characters, one possible solution to this is to use a backslash\
, aka the escape character, before each quote character inside the string. → This tells Python we want to interpret the quote"
as a character inside the string, not as a quote that ends the string.
print("They said, \"Hello, world!\"")
- To embed expressions inside string literals, we can use[[07. Strings#2. f-strings | f-string]]. We can include variables, expressions, and even function calls inside the curly braces.
# Basic variable insertion
print(f"My name is {name} and I am {age} years old.")
# Expressions
print(f"In 5 years, I'll be {age + 5} years old.")
# Calling methods
print(f"My name in uppercase is {name.upper()}.")
3. Code Errors
Errors occur when the program encounters something it cannot process, like syntax or logical mistakes. There are many types of programming errors such as syntax errors, runtime errors, and logical errors.
- Syntax errors: These are easy to fix because the error message usually tells you exactly where the mistake is. It happens when your code violates Python’s rules (like a typo or missing punctuation).
print("Hello world) # Missing closing quote
- Runtime errors: These happen while the program is running. The syntax is correct, but something unexpected occurs, like trying to divide by zero. They can be tricky to fix because they don’t always happen every time the program runs.
x = 10 / 0 # Division by zero
- Logical errors: The program runs fine, but the output is wrong. These errors, also called bugs, don’t crash the program, making them harder to detect. You have to figure out where the code isn’t doing what you intended.
def add_numbers(a, b):
return a - b # Meant to add but using subtraction
print(add_numbers(5, 3)) # Expected 8, but gets 2
4. Comments
Comments are lines in your code that the Python interpreter ignores. They are used to annotate and explain code.
# This is a comment
print("This will print") # Inline comment