Python programming codes - Part_2
Tags: beginners, tutorial, python
Published: 2023-09-26 20:53:21

Hi Dev Community 🙋‍♀️
This post it's the following of part 1
if you didn't check it you can click on this link down bellow 👇
[https://dev.to/sattineez/python-programming-codes-part1-1b0l](url)


- Creating a virtual environment 

Note: I personally use and recommend Anaconda for this (it's easier to manage and control the packages) but you can create venv without conda or Pycharm

```
# Create a virtual environment
python -m venv myenv

# Activate the virtual environment (on Windows)
myenv\Scripts\activate

# Activate the virtual environment (on macOS/Linux)
source myenv/bin/activate

# Install packages within the virtual environment
pip install package_name

# Deactivate the virtual environment
deactivate
```

- Lambda functions

```
# Define a lambda function
add = lambda x, y: x + y
result = add(2, 3)
print(result)

# Use lambda function with built-in functions
my_list = [1, 2, 3, 4, 5]
new_list = list(map(lambda x: x * 2, my_list))
print(new_list)
```

- Function programming

```
# Try-except block
try:
    x = 5 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

# Try-except-else block
try:
    x = 5 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Division successful")

# Try-except-finally block
try:
    file = open("myfile.txt", "r")
    contents = file.read()
except:
    print("Error reading file")
finally:
    file.close()

```

- Working with Generators

```
# Create a generator function
def countdown(n):
    while n > 0:
        yield n
        n -= 1

# Use a generator function
for i in countdown(5):
    print(i)

# Create a generator expression
my_list = [1, 2, 3, 4, 5]
my_generator = (x * 2 for x in my_list)

# Use a generator expression
for item in my_generator:
    print(item)
```

- Working with Decorators

```
# Define a decorator function
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function execution")
        result = func(*args, **kwargs)
        print("After function execution")
        return result
    return wrapper

# Use a decorator
@my_decorator
def greet(name):
    print(f"Hello, {name}!")

greet("John")
```

- Using exceptions

```
# Try-except block
try:
    x = 5 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

# Try-except-else block
try:
    x = 5 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Division successful")

# Try-except-finally block
try:
    file = open("myfile.txt", "r")
    contents = file.read()
except:
    print("Error reading file")
finally:
    file.close()

```
- Converting between data types

```
# Convert a string to an integer
my_string = "123"
my_int = int(my_string)

# Convert a string to a float
my_string = "3.14"
my_float = float(my_string)

# Convert an integer to a string
my_int = 123
my_string = str(my_int)

# Convert a list to a set
my_list = [1, 2, 3, 4, 5]
my_set = set(my_list)

``` 
- Dates and time

```
# Import the datetime module
import datetime

# Get the current date and time
now = datetime.datetime.now()

# Format the date and time
formatted = now.strftime("%Y-%m-%d %H:%M:%S")

# Create a datetime object
my_date = datetime.datetime(2022, 4, 1)

# Subtract dates to get a timedelta object
delta = now - my_date

# Get the total number of seconds in a timedelta object
total_seconds = delta.total_seconds()
```
- Calling/Requesting an API

```
# Import the requests module
import requests

# Make a GET request to an API
response = requests.get("https://api.example.com/data")

# Get the status code of the response
status_code = response.status_code

# Get the content of the response as JSON
json_content = response.json()

# Make a POST request to an API with data
data = {"name": "Sara", "age": 26}
response = requests.post("https://api.example.com/data", json=data)

```

- Json module

```
# Import the JSON module
import json

# Convert an object to JSON
my_dict = {"name": "Sara", "age": 26}
json_data = json.dumps(my_dict)

# Convert JSON to an object
json_data = '{"name": "Sara", "age": 26}'
my_dict = json.loads(json_data)

```
- Handling CVS files

```
import csv

# Read data from a CSV file
with open('data.csv', 'r') as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row)

# Write data to a CSV file
data = [
    ['Name', 'Age', 'City'],
    ['John', '30', 'New York'],
    ['Alice', '25', 'London'],
    ['Bob', '35', 'Paris']
]

with open('data.csv', 'w') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerows(data)
```
- SQLite3

```
import sqlite3

# Connect to a database
conn = sqlite3.connect('mydatabase.db')

# Create a cursor
cursor = conn.cursor()

# Execute a SQL query
cursor.execute('''CREATE TABLE users
                  (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')

# Insert data into the table
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Sara Carvalho", "sara@example.com"))

# Retrieve data from the table
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

# Commit the changes and close the connection
conn.commit()
conn.close()

```

Stay tuned for Part_3 😊

(if you see some error please leave a comment)

- Sending emails
(yep existes a lib for that in python)

```
import smtplib
from email.mime.text import MIMEText

# Connect to an SMTP server
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_username'
smtp_password = 'your_password'

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)

# Compose the email message
sender = 'sender@example.com'
recipient = 'recipient@example.com'
subject = 'Hello from Python!'
message = 'This is a test email.'

email = MIMEText(message)
email['Subject'] = subject
email['From'] = sender
email['To'] = recipient

# Send the email
server.sendmail(sender, recipient, email.as_string())

# Close the connection
server.quit()

```