0% found this document useful (0 votes)
0 views8 pages

Python

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

Here's a quick overview of Python to get you started:

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

5. name = "Celeste" # string


6.

7. Data types: Python supports several built-in data types:

◦ int for integers


◦ float for oating-point numbers
◦ str for strings
◦ list, tuple, set, and dict for more complex collections
8. Example:
python
CopyEdit

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):

16. print(f"Hello, {name}!")


17.
18. greet("Celeste")
19.

20. Classes and Objects: Python supports object-oriented programming (OOP). You can
de ne classes using the classkeyword.
Example:
python
CopyEdit

class Person:

21. def __init__(self, name):


fi
fl
fi
22. self.name = name
23.
24. def greet(self):
25. print(f"Hello, {self.name}!")
26.
27. person = Person("Celeste")
28. person.greet()
29.

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

31. print(math.sqrt(16)) # Output: 4.0


32.

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!")

Great! Let’s dive deeper into some key concepts in Python.


1. Variables and Data Types

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:

• int: Integers (whole numbers)


• float: Floating-point numbers (decimals)
• str: Strings (text)
• list: An ordered, mutable collection of elements (similar to arrays in C++)
• tuple: An ordered, immutable collection
• dict: A collection of key-value pairs (like maps or hash tables in C++)
Example of a list and a dictionary:

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:

• For loop (similar to for in C++):


python
CopyEdit
for i in range(5): # range(5) gives numbers 0 to 4
print(i)
• While loop (similar to while in C++):
python
CopyEdit
i = 0
while i < 5:
print(i)
i += 1
3. Functions

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}!")

greet("Celeste") # Output: Hello, Celeste!


greet() # Output: Hello, Guest!
4. Classes and Objects
fi
Python supports object-oriented programming (OOP) with classes. Classes are blueprints for
creating objects (instances), and they can have methods (functions inside the class) and attributes
(variables inside the class).

Basic Class Example:

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}")

my_car = Car("Toyota", "Corolla")


my_car.display_info() # Output: Brand: Toyota, Model:
Corolla
• __init__ method: This is the constructor method used for initialization.
• self: Refers to the instance of the object.
5. Error Handling (Exceptions)

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:

• Practice: Write simple programs to get comfortable with these concepts.


• Explore more libraries: Learn libraries like datetime, requests, or pandas as
you advance.
fi
fi
• Object-Oriented Programming (OOP): Dive deeper into classes, inheritance,
polymorphism, etc.

You might also like