ניתוח נתונים ולמידת מכונה
אמית רננים – חלופה ליחידה 3
בואו נלמד Python
What and Why Python?
2
ChatGPT - Most Popular Development Languages 2025
3
Syntax
4
# This is a comment
print("Hello, World!") # This prints a greeting
if 5 > 2:
print('Five is greater than two! ')
if 3 > 2:
print("Three is also greater than two!")
# Variables
x = 5
y = "John"
print(x)
print(y)
Data Types
5
# Integer
age = 25
print(f"Age: {age}, Type: {type(age)}")
# Float
height = 1.75
print(f"Height: {height}, Type: {type(height)}")
# String
name = "Alice"
print(f"Name: {name}, Type: {type(name)}")
# Boolean
is_blue = True
print(f"Is Blue: {is_blue}, Type: {type(is_blue)}")
Variables and Operators
6
x = 10
y = 3
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
print(x // y) # Floor division
print(x % y) # Modulo (remainder)
print(x ** y) # Exponentiation
Comparison Operators
7
x = 5
y = 10
print(x == y) # Equal to
print(x != y) # Not equal to
print(x < y) # Less than
print(x > y) # Greater than
print(x <= y) # Less than or equal to
print(x >= y) # Greater than or equal to
# Comparing strings
print("apple" < "banana") # True (alphabetical order)
print("python" == "Python") # False (case-sensitive)
Logic Operators
8
x = 5
y = 10
z = 15
# and: True if both conditions are True
print(x < y and y < z) # True
# or: True if at least one condition is True
print(x > y or y < z) # True
# not: Inverts the boolean value
print(not x > y) # True
# Combining operators
print((x < y or y > z) and not (x == z)) # True
Operator Overloading
9
# String Concatenation with +
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Outputs: John Doe
# List Concatenation with +
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Outputs: [1, 2, 3, 4, 5, 6]
# String Repetition with *
cheer = "Hip "
print(cheer * 3 + "Hooray!") # Outputs: Hip Hip Hip Hooray!
# List Repetition with *
pattern = [0, 1]
repeated_pattern = pattern * 3
print(repeated_pattern) # Outputs: [0, 1, 0, 1, 0, 1]
Data Types - Lists
10
fruits = ["apple", "banana", "cherry"]
print(f"Original list: {fruits}")
# Accessing elements
print(f"First fruit: {fruits[0]}")
print(f"Last fruit: {fruits[-1]}")
# Modifying lists
fruits.append("date")
print(f"After append: {fruits}")
fruits.insert(1, "blueberry")
print(f"After insert: {fruits}")
fruits.remove("cherry")
print(f"After remove: {fruits}")
# Slicing
print(f"First two fruits: {fruits[:2]}")
Data Types - Tuples
11
coordinates = (4, 5)
x, y = coordinates # Unpacking a tuple
print(f"X: {x}, Y: {y}")
# Trying to modify a tuple will raise an error
# coordinates[0] = 10 # This would cause an error
Data Types - Sets
12
# Creating a set
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits) # Duplicates automatically removed
# Adding and removing elements
fruits.add("date")
fruits.remove("banana")
# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1.union(set2)) # All elements from both sets
print(set1.intersection(set2)) # Common elements
print(set1.difference(set2)) # Elements in set1 but not in set2
# Checking membership
print("cherry" in fruits)
Data Types - Dictionaries
13
person = {
"name": "John",
"age": 30,
"city": "New York",
"hobbies": ["reading", "swimming", "coding"]
}
print(f"Person: {person}")
# Accessing and modifying
print(f"Name: {person['name']}")
person['job'] = "Developer“
print(f"After adding job: {person}")
# Nested structures
print(f"First hobby: {person['hobbies'][0]}")
# Dictionary methods
# Get with default value
print(person.get("height", "Not specified"))
print(f"Keys: {person.keys()}")
print(f"Values: {person.values()}")
Flow Control – If-Else
14
age = 16
if age >= 18:
print("You can vote!")
elif age >= 16:
print("You can drive but not vote.")
else:
print("You're too young to drive or vote.")
Loops – For Loop
15
# range with one argument (stop)
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
# range with two arguments (start, stop)
for i in range(2, 6):
print(i) # Prints 2, 3, 4, 5
# range with three arguments (start, stop, step)
for i in range(1, 10, 2):
print(i) # Prints 1, 3, 5, 7, 9
# Creating a list from range
numbers = list(range(1, 6))
print(numbers) # [1, 2, 3, 4, 5]
Loops – For Loop cont…
16
# Dictionary keys
student = {"name": "Alice", "age": 17, "grade": "11th"}
print("name" in student) # True (checks keys)
print("Alice" in student) # False (doesn't check values)
# Iterating over dictionary
for key in student:
print(f"{key}: {student[key]}")
# Combined with List Comprehension
numbers = [1, 2, 3, 4, 5]
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(even_squares) # [4, 16]
# Iteration
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Membership testing
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" in fruits) # False
# Works with strings too
word = "Python"
print("th" in word) # True
print("x" in word) # False
List Comprehension
17
# Basic list comprehension
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# List comprehension with condition
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
# Nested list comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# List comprehension vs. traditional for loop
fruits = ["apple", "banana", "cherry"]
uppercase_fruits = [fruit.upper() for fruit in fruits]
print(uppercase_fruits) # ['APPLE', 'BANANA', 'CHERRY']
# Equivalent traditional for loop:
# uppercase_fruits = []
# for fruit in fruits:
# uppercase_fruits.append(fruit.upper())
Loops – While Loop
# While loop
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
# While loop with break
number = 0
while True:
if number == 5:
break
print(f"Number is {number}")
number += 1
18
Functions
19
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Functions cont…
20
def calculate_rectangle_area(length, width):
“””
Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle
width (float): The width of the rectangle
Returns:
float: The area of the rectangle
“””
area = length * width
return area
# Using the function
rect1_area = calculate_rectangle_area(5, 3)
print(f"The area of rectangle 1 is: {rect1_area}")
rect2_area = calculate_rectangle_area(2.5, 4)
print(f"The area of rectangle 2 is: {rect2_area}")
# Function with default parameter
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!“
# Output: Hello, Alice!
print(greet("Alice"))
# Output: Good morning, Bob!
print(greet("Bob", "Good morning"))
# Lambda function
square = lambda x: x ** 2
print(f"Square of 5: {square(5)}")
Libraries
21
import math
print(math.pi)
print(math.sqrt(16))
from random import randint
print(randint(1, 10))
from datetime import datetime current_time = datetime.now() print(f"Current time: {current_time}")
Libraries cont…
22
# NumPy: Numerical computing
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(f"Mean: {np.mean(arr)}")
# Pandas: Data analysis and manipulation
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(df)
# Matplotlib: Data visualization
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.ylabel('some numbers’)
plt.show()
Getting User Input
23
age_str = input("How old are you? ")
age = int(age_str)
print(f"Next year, you'll be {age + 1} years old.")
height_str = input("How tall are you (in meters)? ")
height = float(height_str)
print(f"You are {height * 100} centimeters tall.")
while True:
try:
number = int(input("Enter a number: "))
break
except ValueError:
print("That's not a valid number. Try again.")
print(f"You entered: {number}")
Input validation with simple exception handling:
File Access - Linking Colab to Google Drive
24
(*1)
(*2)
(*3)
File Access – Open File For Read
Open file for read
file1 = open(‘c:\projects\project1\file.txt’) [Windows example]
In Windows, to find out a file’s path, click on it using the right mouse button and select “Copy as path” from the menu.
Read from file
s = file1.read()
print(s)
Search text for a string
s.find(‘<text to search>’) 🡪 Returns character index of the found string
print(s[<index>:<index+100>])
25
File Name
File Path
Exercise Example
26
def sum_even_numbers(numbers):
return sum(num for num in numbers if num % 2 == 0)
# Test the function
result = sum_even_numbers([1, 2, 3, 4, 5, 6])
print(result)
# Output: 12
Homework Assignments
27
Homework Assignments
28