Python Syntax - A Beginner's Guide
Python syntax is simple and easy to understand, making it a great choice for beginners. Let's go through the basics of Python syntax with examples.
1. Writing and Running Python Code
Python files have a .py
extension. You can run a Python script using:
python script.py
Or use the Python interpreter to execute code line by line.
2. Python Indentation (No Braces {}
)
Python uses indentation (spaces/tabs) to define blocks of code instead of curly brackets {}
.
✅ Correct indentation:
if True:
print("Hello, Python!") # Indented code belongs to the if statement
❌ Incorrect indentation (will cause an error):
if True:
print("Hello, Python!") # IndentationError: expected an indented block
✅ Python recommends using 4 spaces per indentation level.
3. Python Comments
Comments make code more readable. Python supports:
(a) Single-line Comments (#
)
# This is a comment
print("Hello, World!") # Output: Hello, World!
(b) Multi-line Comments (""" """
or ''' '''
)
"""
This is a
multi-line comment
"""
print("Python is easy!")
✅ Use comments to explain complex code!
4. Python Variables and Assignment
Python does not require variable declarations.
x = 10 # Integer
y = "Hello" # String
z = 3.14 # Float
print(x, y, z)
✅ Python is dynamically typed; variable types are determined at runtime.
5. Printing Output (print()
)
name = "Alice"
print("Hello,", name) # Output: Hello, Alice
✅ Use f-strings for better formatting (Python 3.6+):
age = 25
print(f"My age is {age}") # Output: My age is 25
6. Getting User Input (input()
)
name = input("Enter your name: ")
print("Hello,", name)
✅ By default, input()
returns a string. Convert it if needed:
age = int(input("Enter your age: ")) # Converts input to an integer
print("Next year, you'll be", age + 1)
7. Python Data Types
Python supports various data types:
✅ Use type()
to check the data type:
x = 10
print(type(x)) # Output: <class 'int'>
8. Python Operators
Python supports various operators:
(a) Arithmetic Operators
a = 10
b = 5
print(a + b) # Addition: 15
print(a - b) # Subtraction: 5
print(a * b) # Multiplication: 50
print(a / b) # Division: 2.0
print(a // b) # Floor Division: 2
print(a % b) # Modulus: 0
print(a ** b) # Exponentiation: 100000
(b) Comparison Operators
print(10 > 5) # True
print(10 == 5) # False
print(10 != 5) # True
(c) Logical Operators (and
, or
, not
)
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
9. Python Conditional Statements (if
, elif
, else
)
age = 18
if age >= 18:
print("You are an adult.")
elif age == 17:
print("Almost an adult.")
else:
print("You are a minor.")
✅ Indentation is required in conditional statements!
10. Python Loops (for
, while
)
(a) for
Loop
for i in range(5): # Loops from 0 to 4
print(i)
(b) while
Loop
count = 0
while count < 5:
print(count)
count += 1
✅ Use break
to exit a loop and continue
to skip an iteration.
11. Python Functions
Functions help in code reusability.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
✅ Functions make code modular and easy to debug.
12. Python Lists
Lists store multiple items in a single variable.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
fruits.append("orange") # Add an element
print(fruits)
✅ Lists are mutable (modifiable).
13. Python Tuples
Tuples are immutable (cannot be modified).
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
14. Python Dictionaries (dict
)
Dictionaries store key-value pairs.
person = {"name": "Alice", "age": 25}
print(person["name"]) # Output: Alice
person["city"] = "New York" # Add new key-value pair
print(person)
15. Python File Handling
Reading and writing files:
(a) Writing to a File
with open("test.txt", "w") as file:
file.write("Hello, Python!")
(b) Reading a File
with open("test.txt", "r") as file:
print(file.read())
✅ Use with open()
to avoid closing files manually.
16. Exception Handling (try-except
)
Handle errors gracefully:
try:
x = 10 / 0 # Error (division by zero)
except ZeroDivisionError:
print("Cannot divide by zero!")
Conclusion
- Python uses indentation instead of
{}
for blocks of code. - Variables do not require explicit declaration.
- Use
if
,for
,while
,def
to write logical programs. - Functions, loops, and exception handling make Python powerful.
🚀 Mastering Python syntax is the first step in becoming a Python expert!
0 comments:
Post a Comment