Python
Python
Python
1. Syntax: Python is known for its clean and readable syntax, which makes it great for
beginners. It doesn’t require semicolons at the end of statements like C++ does, and it
uses indentation to de ne code blocks instead of curly braces {}.
Example:
python
CopyEdit
if True:
2. print("Hello, world!")
3.
4. Variables: You don’t need to declare the type of a variable in Python. The type is inferred
automatically when you assign a value.
Example:
python
CopyEdit
x = 5 # integer
my_list = [1, 2, 3]
9. my_tuple = (1, 2, 3)
fl
fi
10. my_dict = {'key': 'value'}
11.
12. Control ow: Python uses if, else, elif for conditional statements, and for or
while for loops.
Example:
python
CopyEdit
for i in range(3):
13. print(i)
14.
15. Functions: Functions are de ned using the def keyword, followed by the function name
and parameters in parentheses.
Example:
python
CopyEdit
def greet(name):
20. Classes and Objects: Python supports object-oriented programming (OOP). You can
de ne classes using the classkeyword.
Example:
python
CopyEdit
class Person:
30. Libraries and Packages: Python has a large standard library that includes many useful
modules like math, random, os, and more. You can install additional packages using
pip.
Example:
python
CopyEdit
import math
33. Error handling: Python uses try and except blocks to handle errors.
Example:
python
CopyEdit
try:
34. x = 10 / 0
35. except ZeroDivisionError:
36. print("Cannot divide by zero!")
In Python, variables don't require explicit type declaration, and the types are dynamic, meaning
you can change a variable's type after assignment.
Example:
python
CopyEdit
x = 5 # Integer
x = "Hello" # Now it's a string
Python also has built-in functions to check the type of a variable:
python
CopyEdit
x = 10
print(type(x)) # <class 'int'>
Here are some common data types:
python
CopyEdit
my_list = [1, 2, 3, "Python"]
my_dict = {"name": "Celeste", "age": 30}
2. Control Flow
Python uses if, elif, else, and loops (for, while) for control ow. This is similar to C+
+ but without curly braces, using indentation instead.
If Statements:
python
CopyEdit
x = 10
if x > 5:
print("x is greater than 5")
fl
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
Loops:
In Python, functions are de ned using the def keyword. You can pass arguments to functions,
and functions can return values using the return keyword.
python
CopyEdit
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
Default Arguments: You can provide default values for function parameters.
python
CopyEdit
def greet(name="Guest"):
print(f"Hello, {name}!")
python
CopyEdit
class Car:
def __init__(self, brand, model):
self.brand = brand # Attribute
self.model = model # Attribute
def display_info(self):
print(f"Brand: {self.brand}, Model: {self.model}")
Python handles errors through try, except, and finally blocks. This is useful when you
want to catch exceptions (errors) and handle them gracefully, instead of the program crashing.
Example:
python
CopyEdit
try:
x = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always run.")
Multiple Exceptions: You can handle different types of exceptions using multiple except
blocks.
python
CopyEdit
try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("That's not a valid number!")
6. List Comprehension
List comprehensions allow you to create lists in a concise way, making your code more readable
and ef cient.
python
CopyEdit
# Create a list of squares
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
You can also add conditions to the comprehension:
python
CopyEdit
even_squares = [x**2 for x in range(5) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16]
7. Modules and Libraries
Python has a vast ecosystem of built-in and third-party libraries that you can use in your projects.
You can import a module with the import statement.
Example:
python
CopyEdit
import math
print(math.sqrt(16)) # Output: 4.0
You can also import speci c functions or classes:
python
CopyEdit
from math import sqrt
print(sqrt(16)) # Output: 4.0
Next Steps: