Python's syntax is known for its "readability and simplicity", often resembling plain English. It emphasizes clear, logical code structure.
Here's a breakdown of some fundamental Python syntax elements:
Unlike many other programming languages that use curly braces ({}) to define blocks of code, "Python uses indentation". This is one of its most distinctive features.
:)" marks the start of an indented block.if 5 > 2:
print("Five is greater than two!") # This line is inside the if-block
print("The condition is true.")
# This line is outside the if-block
Comments are used to explain code and are ignored by the Python interpreter.
#).# This is a single-line comment
x = 10 # Everything after the '#' is a comment
Docstrings are typically used for multi-line comments or to explain the purpose of modules, functions, classes, and methods. They are enclosed in "triple quotes" (""" or ''').
def multiply(a, b):
"""
This function takes two numbers and returns their product.
This is a docstring.
"""
return a * b
myVar is different from myvar).=) is used to assign a value to a variable.age = 30 # int (integer)
name = "Alice" # str (string)
is_student = True # bool (boolean)
pi_value = 3.14 # float (floating-point number)
if, elif, else)Used for making decisions in your code.
score = 85
if score >= 90:
print("A")
elif score >= 80: # 'elif' is Python's shorthand for 'else if'
print("B")
else:
print("C")
for, while)Used to execute a block of code repeatedly.
for loopIterates over a sequence (like a list, tuple, dictionary, set, or string).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while loopExecutes a set of statements as long as a condition is true.
count = 1
while count <= 5:
print(count)
count = count + 1
Functions are blocks of reusable code defined using the keyword "def".
return" keyword.def greet(person):
"""Greets the person passed in as argument."""
message = "Hello, " + person + "!"
return message
greeting_result = greet("Bob")
print(greeting_result) # Output: Hello, Bob!