Python from Zero to Functional
Python Syntax and Types
Python's Clean Slate
If you're coming from a language like C++, Java, or JavaScript, the first thing you'll notice about Python is its clean, uncluttered look. It intentionally does away with much of the syntactic noise you might be used to. There are no curly braces {} to define blocks of code and no semicolons ; to terminate lines.
Instead, Python uses indentation. The scope of a loop, function, or conditional statement is defined by how far its lines are indented. This isn't just a stylistic suggestion; it's a rule the interpreter enforces. This design choice forces developers to write code that is visually organized and, in theory, more readable.
# Python: Indentation defines the block
def check_number(n):
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
# JavaScript: Curly braces define the block
function checkNumber(n) {
if (n > 0) {
console.log("Positive");
} else if (n < 0) {
console.log("Negative");
} else {
console.log("Zero");
}
}
While Python's syntax is flexible, the community has established a set of style guidelines to ensure consistency across projects. This guide, known as , is the holy grail of Python formatting. It covers everything from indentation (four spaces, never tabs) to line length and naming conventions.
| Element | Convention | Example |
|---|---|---|
| Variables & Functions | snake_case (all lowercase with underscores) | user_name, calculate_tax() |
| Classes | PascalCase (or CapWords) | class UserProfile: |
| Constants | ALL_CAPS (with underscores) | MAX_CONNECTIONS = 10 |
| Private variables | _leading_underscore (by convention) | self._internal_value |
Dynamic and Strong Typing
Python is a dynamically typed language. This means you don't need to declare a variable's type when you create it. The interpreter figures out the type at runtime based on the value you assign. A variable can even hold values of different types throughout its life.
This is different from statically typed languages like C++ or Java, where you must declare int my_num; and my_num can only ever be an integer. Python's approach offers flexibility and can lead to faster development, but it shifts the burden of type-checking from the compiler to the developer during runtime.
# The type of 'data' changes at runtime
data = 42
print(f"Value: {data}, Type: {type(data)}")
data = "Hello, Python!"
print(f"Value: {data}, Type: {type(data)}")
data = True
print(f"Value: {data}, Type: {type(data)}")
Despite being dynamically typed, Python is also strongly typed. This means the interpreter won't implicitly convert types in most operations. For example, you can't add a string to an integer ("5" + 10) without explicitly converting one of them. This prevents a class of bugs common in weakly typed languages like JavaScript.
The basic, or primitive, data types in Python are immutable, meaning their value cannot be changed after they are created. These include:
- Integers (
int): Whole numbers of unlimited size. - Floats (
float): Numbers with a decimal point. Like in most languages, they are subject to . - Booleans (
bool):TrueorFalse. - Strings (
str): Sequences of Unicode characters.
Working with Strings
String manipulation is a common task, and Python makes it incredibly easy. While you can concatenate strings with the + operator or use the older .format() method, the modern and preferred approach is using f-strings (formatted string literals).
Introduced in Python 3.6, f-strings provide a concise and readable way to embed expressions inside string literals. You simply prefix the string with an f and write expressions inside curly braces {}.
name = "Alice"
_items = 5
price_per_item = 2.50
# Old way: .format()
print("Hello, {}. Your total is ${}.".format(name, items * price_per_item))
# Modern way: f-string
print(f"Hello, {name}. Your total is ${items * price_per_item:.2f}.")
# The :.2f formats the float to two decimal places
Sometimes you need to convert a value from one type to another, a process known as . Python provides straightforward functions for this, like int(), float(), str(), and bool(). A common use case is converting user input, which is always read as a string, into a numeric type for calculations.
# input() always returns a string
age_str = input("Enter your age: ")
# We cast the string to an integer to perform math
if age_str.isdigit(): # Check if the string contains only digits
age_int = int(age_str)
print(f"In 10 years, you will be {age_int + 10} years old.")
else:
print("Invalid input. Please enter a number.")
Now that you have a grasp of Python's syntax and core data types, let's test your understanding.
How does Python define the scope of a code block (e.g., in a loop or function)?
Which of the following best describes Python's type system?
With this foundation, you're ready to explore Python's powerful data structures and control flow.