Python Programming Fundamentals
Python Basics
Your First Steps in Python
Every language, whether spoken or for programming, has its own set of rules. We call these rules syntax. In English, we use punctuation and grammar to form coherent sentences. In Python, syntax is what allows us to write instructions that a computer can understand and execute. Fortunately, Python's syntax is known for being clean, readable, and intuitive, which makes it a great language for beginners.
Let's start with the most traditional first program: printing "Hello, World!" to the screen. In Python, it's just one simple line.
# This line of code will display a message on the screen.
print("Hello, World!")
Here, print() is a built-in function that tells Python to display output. The text inside the parentheses, "Hello, World!", is the argument we give to the function—it's the specific thing we want it to print. The line starting with a # is a comment. Comments are notes for human readers that Python completely ignores when it runs the code.
Think of a function like
print()as a command, and the argument in parentheses as the details for that command.
The Rules of Indentation
One of the most unique features of Python's syntax is its use of indentation. Unlike many other programming languages that use curly braces {} to group lines of code, Python uses whitespace. How far you indent your code matters a great deal.
This isn't just for style. Indentation tells Python which lines of code belong together in a block. A code block is a group of statements that are executed as a unit. For example, let's look at a simple conditional statement.
temperature = 30
if temperature > 25:
# This line is inside the if block
print("It's a warm day!")
# This line is outside the if block
print("Carry on.")
In this example, the line print("It's a warm day!") is indented. This means it is part of the if statement's code block. It will only run if the condition temperature > 25 is true. Since 30 is greater than 25, you'll see "It's a warm day!" printed.
The final line, print("Carry on."), is not indented, so it sits outside the if block. It will run regardless of the temperature.
The standard convention is to use four spaces for each level of indentation. Consistent indentation is mandatory; mixing tabs and spaces can cause errors.
If you get the indentation wrong, Python will let you know with an error.
if temperature > 25:
print("This will cause an IndentationError!")
This strictness about indentation forces coders to write clean, well-organized code that's easier for everyone to read.
Now that you've seen the basics of Python's structure, you're ready to start building simple programs and exploring what the language can do.
