Python is known for its clear and readable syntax. This tutorial will cover the fundamental syntax elements of Python, including comments, indentation, variables, data types, control flow, and functions.
1. Comments
Comments in Python start with the #
symbol and extend to the end of the line. They are ignored by the Python interpreter and are used to add explanations or notes within the code.
# This is a single-line comment
"""
This is a
multi-line comment
"""
2. Indentation
Indentation is crucial in Python and is used to define blocks of code. Use four spaces (or a tab) for each level of indentation consistently.
# Example of indentation
if True:
print("This is indented")
else:
print("This is not indented")
3. Variables and Data Types
Variables are dynamically typed, meaning you don’t need to declare their type explicitly.
# Variable declaration and assignment
my_variable = 42
# Data types
integer_var = 42
float_var = 3.14
string_var = "Hello, Python!"
boolean_var = True
4. Control Flow
4.1. Conditional Statements (if, elif, else)
# Conditional statements
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
4.2. Loops (for, while)
# For loop
for i in range(5):
print(i)
# While loop
counter = 0
while counter < 5:
print(counter)
counter += 1
5. Functions
# Function definition
def greet(name):
return "Hello, " + name + "!"
# Function call
result = greet("Alice")
print(result)
6. Lists
# Lists
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Accessing elements
my_list.append(6) # Adding an element
7. Dictionaries
# Dictionaries
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict['key1']) # Accessing values
my_dict['key3'] = 'value3' # Adding a key-value pair
8. Exception Handling
# Exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
This tutorial provides a brief overview of Python syntax. As you continue learning, explore more advanced topics such as classes, modules, and advanced data structures to become proficient in Python programming. Practice coding regularly to reinforce your understanding of the syntax and concepts.
Next Up: