Python Programming Fundamentals
Syntax and Scripting
From Rules to Running Code
Knowing what a variable or a loop is doesn't mean you can write code in any language. Every programming language has its own grammar, or syntax, that dictates how you must write instructions. Python's syntax is known for being clean and readable, largely because it treats whitespace as part of the code itself.
Unlike many other languages that use curly braces {} or keywords like begin and end to define blocks of code, Python uses indentation. This isn't just a matter of style; it's a rule. A consistent level of indentation groups statements together. Get it wrong, and your code won't run.
# In Python, indentation defines the scope of the if statement.
user_age = 20
if user_age >= 18:
print("You are old enough to vote.") # This line is inside the if block
print("Please register if you haven't.") # This line is also inside
print("This line runs regardless.") # This line is outside the if block
Writing Readable Python
Beyond indentation, Python has a set of community-agreed-upon style guidelines. Following them makes your code easier for others (and your future self) to read. For variable and function names, the convention is to use , where words are separated by underscores.
Good:
first_name,calculate_interestNot-so-good:firstName,CalculateInterest
To explain your code, you use comments and docstrings. A hash symbol (#) creates a single-line comment, which is ignored by the interpreter. It’s useful for short notes.
For more formal documentation, especially for functions, you use . These are multi-line strings created with triple quotes (""" or ''').
# This is a single-line comment.
def calculate_tax(income):
"""Calculate the income tax based on a simple flat rate.
Args:
income (float): The total income.
Returns:
float: The calculated tax amount.
"""
tax_rate = 0.20
return income * tax_rate
# You can view a function's docstring like this:
print(calculate_tax.__doc__)
Data That Adapts
Python uses . This means you don't have to declare a variable's data type when you create it. The interpreter figures out the type (like integer, string, or boolean) at runtime based on the value you assign. A variable can even hold different types of data at different points in the program.
# The same variable `data` holds different types.
data = 42 # Python knows this is an integer.
print(type(data))
data = "Hello!" # Now it's a string.
print(type(data))
data = True # And now a boolean.
print(type(data))
This flexibility is powerful, but it requires careful management when you need a specific data type, especially when handling user input. The input() function, for example, always returns a string, even if the user types numbers.
If you ask for a user's age and they enter "25",
input()gives you the string'25', not the number25. You can't do maths with a string.
To solve this, you perform type casting by explicitly converting the value to the desired type using functions like int(), float(), or str().
# Get user input as a string
age_str = input("Enter your age: ")
# Cast the string to an integer
age_num = int(age_str)
# Now you can perform calculations
years_until_100 = 100 - age_num
When you need to embed variables or expressions inside strings, the modern and most readable way is with . You prefix the string with an f and place your variables inside curly braces.
name = "Alex"
age = 30
# Using an f-string to create a formatted message
message = f"Hello, my name is {name} and I am {age} years old."
print(message)
# Output: Hello, my name is Alex and I am 30 years old.
Now that you understand the basic rules of writing Python, let's test your knowledge.
In Python, what is the primary purpose of indentation?
According to Python's community style guidelines, what is the conventional way to name a variable that consists of multiple words, like 'user age'?