Introduction:
Python is a high-level, interpreted programming language known for its simplicity and readability. This documentation provides an overview of Python's syntax, highlighting its key components and providing relevant coding examples.
1. Variables and Data Types:
In Python, variables are used to store data. The language is dynamically typed, meaning you don't need to declare a variable's type explicitly. Here are some common data types in Python:
- Integer:
num = 42
- Float:
pi = 3.14
- String:
name = "John"
- Boolean:
is_valid = True
2. Control Flow:
Python supports conditional statements and loops for controlling program flow.
- if-else statements:
pythonage = 25
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
- for loop:
pythonfruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
3. Functions:
Functions allow you to organize code into reusable blocks.
pythondef greet(name):
return "Hello, " + name
message = greet("Alice")
print(message)
4. Lists and Dictionaries:
- Lists: Ordered, mutable collections of items.
pythonnumbers = [1, 2, 3, 4, 5]
- Dictionaries: Unordered, mutable key-value pairs.
pythonperson = {"name": "John", "age": 30, "city": "New York"}
5. Classes and Objects:
Python is an object-oriented language, and classes are used to define objects.
pythonclass Car:
def __init__(self, make, model):
self.make = make
self.model = model
def display_info(self):
return f"{self.make} {self.model}"
my_car = Car("Toyota", "Corolla")
print(my_car.display_info())
6. Exception Handling:
Python provides a way to handle errors gracefully with try-except blocks.
pythontry:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Conclusion:
This documentation provides a brief overview of Python's syntax, covering variables, control flow, functions, data structures, classes, and exception handling. Python's straightforward syntax makes it an excellent choice for various programming tasks.
0 Comments