Tutorial in Python Basics
Python Basics for AI Beginners
Python is the main language for AI and data. If you want to learn machine learning or deep learning, you need strong Python basics. This guide stays simple and clear. You can follow it even if you start from zero.
1. What Is Python and Why Do We Use It in AI
- Python has clean and readable syntax.
- Big AI ecosystem. NumPy, Pandas, Matplotlib, PyTorch, TensorFlow.
- Large community and many examples.
- Works on Windows, Linux, and macOS.
Python lets you focus on ideas instead of complex syntax. That helps a lot when you start with AI concepts.
2. Installing Python
Steps
- Go to the official Python website.
- Download the latest stable version of Python 3.
- Install and check the option to add Python to PATH.
- Open a terminal or command prompt.
- Run this command.
python --version
If you see a version number, Python is ready.
3. Your First Python Program
Open a file called hello.py and write.
print("Hello AI world")
Run it.
python hello.py
You see the message in your terminal. This is your first step toward AI coding.
4. Python Syntax Basics
4.1 Indentation
Python uses spaces to mark blocks. No braces. Indentation is important.
if 5 > 3:
print("True")
Use four spaces per level. Keep the style consistent.
4.2 Comments
Use comments to explain code.
# This is a comment
print("Hello") # Inline comment
5. Variables and Data Types
5.1 Creating Variables
x = 10
name = "Sara"
pi = 3.14
is_ai_fun = True
Python detects the type from the value.
5.2 Main Data Types
- int. whole numbers.
- float. decimal numbers.
- str. text strings.
- bool. True or False.
- list. ordered collection.
- tuple. fixed ordered collection.
- dict. key value pairs.
5.3 Lists
numbers = [1, 2, 3, 4]
print(numbers[0]) # First element
numbers.append(5) # Add element
5.4 Dictionaries
student = {
"name": "Sara",
"age": 21,
"field": "AI"
}
print(student["name"])
6. Operators
6.1 Arithmetic Operators
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b) # Integer division
print(a % b) # Remainder
print(a ** b) # Power
6.2 Comparison Operators
x = 5
print(x == 5)
print(x != 5)
print(x > 3)
print(x < 10)
6.3 Logical Operators
age = 20
is_student = True
print(age > 18 and is_student)
print(age < 18 or is_student)
print(not is_student)
7. Control Flow
7.1 if, elif, else
score = 82
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C or lower")
7.2 for Loop
for i in range(5):
print(i)
Loop through a list.
names = ["Ali", "Sara", "Amine"]
for n in names:
print(n)
7.3 while Loop
count = 0
while count < 3:
print("Count:", count)
count += 1
8. Functions
8.1 Defining Functions
def greet(name):
print("Hello", name)
greet("Sara")
8.2 Functions With Return
def add(a, b):
return a + b
result = add(3, 4)
print(result)
Functions help you reuse code and keep projects clean.
9. Modules and Packages
9.1 Importing Modules
import math
print(math.sqrt(16))
9.2 From Import
from math import sqrt
print(sqrt(25))
Modules hold functions and classes. You import them instead of writing everything in one file.
10. Working With Files
# Writing
with open("data.txt", "w") as f:
f.write("AI is fun")
# Reading
with open("data.txt", "r") as f:
content = f.read()
print(content)
File handling is important for data projects. You load datasets and store results.
11. Virtual Environments
Virtual environments keep project packages isolated.
Steps
python -m venv venv
Activate.
venv\Scripts\activate
source venv/bin/activate
After that install packages.
pip install numpy pandas matplotlib
12. First AI Oriented Libraries
12.1 NumPy
NumPy handles arrays and numeric operations.
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)
12.2 Pandas
Pandas handles tables and structured data.
import pandas as pd
data = {
"name": ["Sara", "Ali"],
"score": [90, 85]
}
df = pd.DataFrame(data)
print(df)
12.3 Matplotlib
Matplotlib draws charts.
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [2, 4, 6]
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("y")
plt.title("Simple line")
plt.show()
These three libraries form a strong base for AI and data science.
13. Mini Projects for Python Basics
Project 1. Simple Calculator
- Ask the user for two numbers.
- Ask for an operation. plus, minus, multiply, divide.
- Use if statements.
- Print the result.
Project 2. Student Grades Report
- Store students in a list of dictionaries.
- Each dictionary holds name and grade.
- Loop over the list and print a report.
- Find the highest grade.
Project 3. Simple Data Summary With Pandas
- Create a CSV file with product, price, and quantity.
- Load it with Pandas.
- Compute total revenue.
- Show basic statistics.
These projects connect Python basics with small data tasks. That prepares you for machine learning projects.
14. Typical Errors and How to Avoid Them
- IndentationError. fix spaces and keep alignment.
- NameError. check spelling of variable names.
- TypeError. check types before operations.
- ModuleNotFoundError. install packages with pip and check environment.
Read error messages. They show the line and the type of error. This skill is important for AI work.
15. Next Steps After Python Basics
- Learn more about NumPy and Pandas.
- Study data visualization.
- Start with machine learning. scikit learn.
- Move to deep learning. PyTorch or TensorFlow.
Python basics open the door. AI libraries build on these concepts.
Python Basics in Moroccan Darija
Db l AI kaybda m3a Python. Ila fhamti Python basics, t9der tdkhl l machine learning w deep learning bla t3qid.
1. 3lach Python
- Syntax sahl.
- Libraries kbar. NumPy, Pandas, Matplotlib, PyTorch, TensorFlow.
- Community kbira w resources ktr.
2. Awel Code
print("Salam mn Python")
Run code w shof output f terminal. Hadi bidaya dyalek.
3. Variables
age = 22
name = "Yassine"
is_student = True
Python kayfham type mn value.
4. Lists w Dicts
numbers = [1, 2, 3]
student = {"name": "Aya", "score": 95}
Lists bach t7t data mratba. Dicts bach t7t key value.
5. Loops w Conditions
if age >= 18:
print("Baligh")
else:
print("Sghir")
for n in numbers:
print(n)
6. Functions
def greet(name):
print("Salam", name)
greet("Aya")
Functions kat7afdk code w kat3awnk f projects kbira.
7. Libraries dial Data
import numpy as np
import pandas as pd
NumPy l arrays. Pandas l tables. Hadchi howa base dial AI.
Conclusion
Python basics form the first step toward AI. Learn syntax, variables, data types, loops, and functions. Use NumPy, Pandas, and Matplotlib for data. Build small projects. With these tools, you can start machine learning and deep learning with confidence.