Python Syntax
Python is a high-level, interpreted programming language known for its simplicity and readability. This chapter provides an overview of the basic syntax of Python, including examples to illustrate each concept.
1. Comments
Comments in Python start with the hash character (#
) and extend to the end of the line. Comments are ignored by the Python interpreter and are used to add notes or explanations in the code.
Example:
# This is a comment
print("Hello, World!") # This is another comment
2. Variables
Variables in Python are used to store data values. A variable is created the moment you first assign a value to it.
Example:
x = 5
y = "Hello"
print(x)
print(y)
3. Data Types
Python has several built-in data types, including integers, floats, strings, lists, tuples, dictionaries, and more.
Example:
x = 5 # int
y = 5.5 # float
z = "Hello" # string
a = [1, 2, 3] # list
b = (1, 2, 3) # tuple
c = {"name": "Alice", "age": 25} # dictionary
4. Print Function
The print()
function is used to output data to the console.
Example:
print("Hello, World!")
print(x)
print(y + " World!")
5. Indentation
Indentation is very important in Python. It is used to define the level of code blocks, such as functions, loops, and conditional statements. Python uses whitespace (spaces or tabs) for indentation, not braces.
Example:
if x > 0:
print("x is positive")
else:
print("x is not positive")
6. Conditional Statements
Conditional statements are used to perform different actions based on different conditions. The most common conditional statements in Python are if
, elif
, and else
.
Example:
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
7. Loops
Loops are used to execute a block of code repeatedly. Python provides two types of loops: for
loops and while
loops.
7.1 For Loop
Example:
for i in range(5):
print(i)
7.2 While Loop
Example:
i = 0
while i < 5:
print(i)
i += 1
8. Functions
Functions are defined using the def
keyword. They are used to encapsulate code that performs a specific task.
Example:
def greet(name):
print("Hello, " + name)
greet("Alice")
greet("Bob")
9. Classes and Objects
Python is an object-oriented programming language. You can define your own classes and create objects from those classes.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
p1 = Person("Alice", 25)
p1.greet()
p2 = Person("Bob", 30)
p2.greet()
Conclusion
This chapter provided an overview of the basic syntax of Python, covering comments, variables, data types, the print function, indentation, conditional statements, loops, functions, and classes and objects. Understanding these basic concepts is essential for writing Python programs.