??Ask ChatGTP: ?? Python Learning Series 101 Example Code for Each Topic
Raul E Garcia
Applied Mathematician & Software Engineer, ??Fraud Detection & Benford's Law Expert, Custom Excel apps for Fraud detection, SQL, C#, MVC, SSIS, Azure, Excel VBA, Data Science, Selenium, Matlab, Math studies UCSD UPRM UPR
Yes - we can get the Bite of Python quickly step by step - learn by EXAMPLES below! ??
Introduction - an example of the power of Python:
Here’s a sample Python code that follows a ??functional programming approach to:
? Define a function exp(x, y) - the def command - def exp(x,y)
? Evaluate the function over a range of values using functional programming
? Visualize the results using matplotlib
Example notes: need libs for numpy and matplotlib, use: <<assuming pip is installed>>
pip install matplotlib
pip install numpy
pip stands for "Pip Installs Packages". It’s the package manager for Python, used to install and manage software libraries and dependencies. It's the recommended tool for managing Python packages and comes bundled with Python starting from Python 3.4.
# Python Learning Series - Example Code for Each Topic
Here’s a clear and easy-to-understand list of all Python keywords (reserved words) as of Python 3.12:
Control Flow Keywords
Function and Class Keywords
Exception Handling Keywords
Import Keywords
Variable Scope Keywords
Logical and Comparison Keywords
Object Management Keywords
Special Purpose Keywords
Newer Keywords (Python 3.10+)
?? Important Notes
101. Introduction to Python and Installation (at the end)
print("Hello, World! This is Python.") # Basic print statement for intro - silly it goes to you
# 2. Python Syntax and ??Indentation -
<<Note: indentation - 4 spaces - marks a block of code - do not use tabs - def defines a function>>
def greet(name):
if name: # Correct indentation is crucial in Python
print(f"Hello, {name}!")
else:
print("Hello, World!")
greet("Alice")
<<comments: note indentation before if and print, note ':' after else>>
# 3. Variables and Data Types
name = "John" # String variable
days = 365 # Integer variable
pi = 3.14159 # Float variable
print(f"{name} - {days} days in a year - Pi value: {pi}")
# 4. Input and Output Operations
user_input = input("Enter your name: ")
print(f"Welcome, {user_input}!")
# 5. Comments and Documentation
"""
Triple quotes are used for documentation strings (docstrings)
Useful for documenting functions, classes, and modules.
"""
# 6. Type Conversion and Casting
num_str = "42"
num_int = int(num_str) # Converting string to integer
print(num_int * 2)
# 7. Operators and Expressions
x, y = 10, 5
print(f"Addition: {x + y}, Multiplication: {x y}, Power: {x * y}")
# 8. Control Flow: if, else, elif
<<Note: indentation - 4 spaces - marks a block of code>>
score = 85
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
else:
print("Grade: C")
# 9. Loops: for and while
# Using a for loop
<<Note: indentation - 4 spaces - marks a block of code>>
total = 0
for i in range(1, 6):
total += i
print(f"Total sum: {total}")
# Using a while loop
counter = 3
while counter > 0:
print(f"Countdown: {counter}")
counter -= 1
# 10. Break, Continue, and Pass
for i in range(1, 6):
if i == 3:
continue # Skip number 3
print(i)
# 11. Lists: Creating, Accessing, and Modifying
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Adding element
print(fruits)
# 12. List Comprehensions
squares = [x**2 for x in range(5)]
print(f"Squares: {squares}")
# 13. Tuples: Immutable Sequences
days = ("Monday", "Tuesday", "Wednesday")
print(f"First day of the week: {days[0]}")
# 14. Sets and Their Operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(f"Union: {set1 | set2}, Intersection: {set1 & set2}")
# 15. Dictionaries: Key-Value Pair Management
person = {"name": "Alice", "age": 30}
person["city"] = "New York"
print(person)
# 16. Advanced Dictionary Methods
print(person.get("age", "Unknown")) # Get method with default value
# 17. Working with Strings
message = " Hello World! "
print(message.strip().upper()) # Remove spaces & convert to uppercase
# 18. String Slicing Techniques
word = "Python"
print(word[0:4]) # Prints 'Pyth'
# 19. Python Collections
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
print(Counter(nums))
# 20. Functions and Modules
# Defining a function
<<Here starts functional programming - a powerful way to encapsulate code and complex applications - code each function and then call as needed! ??>>
def add_numbers(a, b):
"""Adds two numbers and returns the result."""
return a + b
result = add_numbers(10, 5)
print(f"Sum: {result}")
# Importing modules
import math
print(f"Square root of 16: {math.sqrt(16)}")
# File Handling
# Writing to a file
with open("sample.txt", "w") as file:
file.write("Hello, this is a sample file.")
# Reading from a file
with open("sample.txt", "r") as file:
content = file.read()
print(f"File Content: {content}")
# Appending to a file
with open("sample.txt", "a") as file:
file.write("\nAdding more data.")
# Object-Oriented Programming (OOP)
class Car:
def init(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.brand} {self.model}")
# Creating objects
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2018)
car1.display_info()
car2.display_info()
# Advanced Python Concepts??
# Decorators
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(f"Wrapper executed before {original_function.__name__}")
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display():
print("Display function executed.")
display()
# Generators
def count_up_to(max_value):
count = 1
while count <= max_value:
yield count
count += 1
for number in count_up_to(5):
print(number)
# Context Manager
class FileManager:
def init(self, filename, mode):
self.filename = filename
self.mode = mode
def enter(self):
self.file = open(self.filename, self.mode)
return self.file
def exit(self, exc_type, exc_value, traceback):
self.file.close()
with FileManager("example.txt", "w") as f:
f.write("This is managed by a context manager.")
print("File written successfully.")
??EXTENDING PYTHON ??
# APIs
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json())
# Data Visualization ??
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y, marker='o')
plt.title("Sample Data Visualization")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
# Automation
import pyautogui
pyautogui.alert("Automation with Python is cool!")
PY INSTALL BACKGROUND:
<<Note: unfortunately installing a Py editor is another topic, visual studio code is free/easy>>
GIVE THE STEPS IN A TEXT BLOCK TO INSTALL PYTHON
<<Note: to avoid a messy windows install when >python --version gives an error: >>
??Best to use the option below - MODIFY - to enable adding the py path
????Click on the ADD PY TO ENV VARIABLES BELOW:
**Steps to Install Python**
1. **Download Python Installer**
- Go to the official Python website: [https://www.python.org/downloads/](https://www.python.org/downloads/)
- Click on the latest stable version (recommended for most users).
2. **Run the Installer**
- Open the downloaded .exe file.
- **Check the box that says "Add Python to PATH"** (important for command-line usage).
<<Fix: see above - this option is on the advanced setup - under modify>>
- Click **"Install Now"** for the default installation or **"Customize installation"** for advanced options.
3. **Verify Installation**
- Open **Command Prompt** (Windows) or **Terminal** (macOS/Linux).
- Run the following command to verify Python is installed correctly:
```
python --version
```
Or use python3 --version if python doesn’t work.
4. **Install pip (if not included)**
Python installers typically include pip, but if missing, install it with:
```
python -m ensurepip --upgrade
```
5. **Install Virtual Environment (Recommended for Projects)**
Create a virtual environment to manage dependencies:
```
python -m venv my_project_env
source my_project_env/bin/activate # On Mac/Linux
my_project_env\Scripts\activate # On Windows
```
6. **Test by Installing a Package**
For example, install requests to confirm everything works:
```
pip install requests
```
My env results - typical IT mess of commands!??
7. **Set Environment Variables (If Needed)** <<messy ??>>
If Python isn’t recognized in the command line, manually add its path to your system’s environment variables.
Now you're ready to code with Python! ??