In the previous article, we learned how to install Python on our computer. Continuing with the Python tutorial series, today we will dive into a fundamental and extremely important topic: Python Syntax.

What is Python Syntax?

Python Syntax refers to the rules for writing Python code. Python is famous for its simple, clear, and easy-to-read syntax, making it accessible to programming beginners.

Basic Python Syntax

1. Printing to the Screen (print)

The most basic command to display information on the screen is print:

python
print("Hello, World!")

Output:

shell
Hello, World!

2. Indentation

Unlike many other programming languages, Python uses whitespace (spaces or tabs) to define code blocks:

python
if 5 > 2:
    print("5 is greater than 2")

3. Comments

Comments help the reader understand the purpose of the code:

python
# This is a comment
print("Hello")  # This is also a comment

4. Variables and Data Types

Python does not require declaring a data type when creating variables:

python
x = 5  # integer
y = 3.14  # float
name = "CodeTutHub"  # string

5. Rules for Naming Variables

  • Starts with a letter or underscore (_).
  • Can include numbers but not start with them.
  • Case-sensitive (myVar is different from myvar).

Example:

python
my_var = 10
_var2 = "Hello"

Conditional Statements

Python supports logical conditions using if, elif, and else:

python
x = 10

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

Loops

for Loop

python
for i in range(3):
    print(i)

Output:

shell
0
1
2

while Loop

python
i = 0
while i < 3:
    print(i)
    i += 1

Functions

Functions in Python are defined using the keyword def:

python
def greet(name):
    print("Hello, " + name)

greet("Python")

Output:

python
Hello, Python

Common Syntax Errors

  • Forgetting the colon (:) after conditionals or loops.
  • Incorrect indentation.
  • Forgetting closing brackets or quotation marks.

Common error example:

python
# Incorrect: missing colon
if x > 5
    print("Syntax error")

Conclusion

Python is an easy-to-learn programming language with clear syntax, perfect for beginners. Mastering Python syntax is the first critical step toward becoming a proficient programmer.

In the next article, we will explore various data types in detail and learn how to use them effectively in Python.

Stay tuned for more Python tutorials on CodeTutHub.com for effective learning and practical Python programming!