Python Syntax
This article explains Python syntax.
YouTube Video
Syntax in Python
Indentation
Python uses indentation to define blocks of code. Unlike many other languages that use curly braces {}
to define code blocks, Python uses indentation. Typically, an indentation of four spaces is used, but tabs can also be used. However, you should be careful not to mix spaces and tabs within a single file.
1x = 5
2if x > 0:
3 print("Positive")
4else:
5 print("Non-positive")
Comments
Single-line comment
In Python, comments begin with #
. Everything until the end of the line is treated as a comment.
1# This is a comment
2print("Hello, World!") # This is also a comment
Documentation string (Docstring
)
A docstring
is a string used to describe code, enclosed by triple double quotes """
or triple single quotes '''
. It is mainly used to describe modules, classes, and functions.
1def greet(name):
2 """
3 This function displays a greeting to the specified name.
4
5 Parameters:
6 name (str): The name of the person to greet.
7 """
8 print(f"Hello, {name}!")
Docstring
can be viewed using the help()
function.
1help(greet)
Best Practices for Comments
Best practices for comments include the following points:.
1# Good example
2# Validate user input and display a personalized message
3
4# Ask for the user's name
5name = input("Enter your name: ")
6
7# Ask for the user's age and convert it to an integer
8age = int(input("Enter your age: "))
9
10# Check eligibility based on age
11if age >= 18:
12 # Inform the user that they can register
13 print(f"Welcome, {name}! You are eligible to register.")
14else:
15 # Inform the user that they are underage
16 print(f"Sorry, {name}. You must be at least 18 years old to register.")
17
18# Bad example
19# Store the user's name in the variable 'name'
20name = input("Enter your name: ")
21
22# Convert the input to an integer and store it in 'age'
23age = int(input("Enter your age: "))
24
25# Check if the user is greater than or equal to 18
26if age >= 18:
27 # Print a welcome message
28 print(f"Welcome, {name}! You are eligible to register.")
29else:
30 # Print a rejection message
31 print(f"Sorry, {name}. You must be at least 18 years old to register.")
-
Be clear and concise Comments are used to clearly explain the intent of the code.
-
Do not reiterate the code's meaning Avoid commenting on code that is self-explanatory.
-
Maintain consistency In team development, it is important to maintain uniformity in comment style and format.
Variables and Data Types
In Python, you do not need to specify the type when declaring a variable. The type is automatically determined at the time of assignment.
1x = 10 # Integer
2y = 3.14 # Floating-point number
3name = "Alice" # String (text)
4is_active = True # Boolean value (True or False)
Conditional Statements
Conditional statements use if
, elif
(else if), and else
.
1x = 0
2if x > 0:
3 print("Positive")
4elif x == 0:
5 print("Zero")
6else:
7 print("Negative")
Loops
Python provides for
loops and while
loops, each used in different ways.
for
Statement
The for
statement is typically used to iterate over elements of a list or tuple.
1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3 print(fruit)
while
Statement
The while
statement repeats a loop as long as the condition is true.
1count = 0
2while count < 5:
3 print(count)
4 count += 1
Defining Functions
In Python, functions are defined using the def
keyword.
1def greet(name):
2 print(f"Hello, {name}!")
3
4greet("Alice")
Defining Classes
In Python, you can define classes using the class
keyword, enabling object-oriented programming.
1class Dog:
2 def __init__(self, name):
3 self.name = name
4
5 def bark(self):
6 print("Woof!")
7
8dog = Dog("Fido")
9dog.bark()
Modules and Imports
In Python, the import
keyword is used to import modules and access existing code.
1# Importing the sqrt function from the math module
2from math import sqrt
3
4result = sqrt(16)
5print(result) # Output: 4.0
Errors and Exception Handling
Python's try-except
structure handles errors and unexpected situations.
1# Catching a division-by-zero error example
2try:
3 result = 10 / 0
4except ZeroDivisionError:
5 print("Cannot divide by zero.")
Conclusion
Python's basic syntax is very simple and highly readable. These basics are essential elements for writing Python code.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.