1 of 28

ניתוח נתונים ולמידת מכונה

אמית רננים – חלופה ליחידה 3

בואו נלמד Python

מוטי בזר

mottibz@gmail.com

https://www.commridge.com

2 of 28

What and Why Python?

  • High-level programming language - Easy to write and read
  • Interpreted - Code is executed line by line, no compilation needed
  • Easy to learn - Simple syntax
    • print (“Hello World!”)
  • General-purpose and Versatile – Great for developing for the PC, Web, Data analysis, AI and Machine Learning, Scientific computing
  • Large community and extensive libraries
    • Active online community for support
    • PyPI (https://pypi.org/): Python Package Index with over 650,000 projects

2

3 of 28

ChatGPT - Most Popular Development Languages 2025

3

4 of 28

Syntax

  • Uses indentation to define code blocks
    • Emphasizes clean, readable code
  • Comments use # for single line, ''' or """ for multi-line
  • Strings can be defined using '' or "" ('name', "name")
  • Uses colon (:) to start code blocks

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)

5 of 28

Data Types

  • Integers
    • Whole numbers
  • Floating-point
    • Decimal numbers
  • Strings
    • Text
  • Booleans
    • True or False

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

6 of 28

Variables and Operators

  • Variables store data
  • General naming conventions: lowercase, underscores for spaces
  • Basic numeric 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

7 of 28

Comparison Operators

  • Used to compare values
  • Return Boolean results (True or False)

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)

8 of 28

Logic Operators

  • Used to combine conditional statements
  • Main operators: and, or, not

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

9 of 28

Operator Overloading

  • Operators behave differently based on the data types involved
  • This allows for intuitive operations on different types of objects
  • Python has built-in operator overloading for many data types

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]

10 of 28

Data Types - Lists

  • Ordered
  • Mutable collections
    • Can add, remove, or modify elements�within the collection
  • Can contain mixed data types
  • Defined using [ and ]
  • Indexed from 0
  • New code elements: -1, slicing

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

11 of 28

Data Types - Tuples

  • Ordered
  • Immutable collections – Can’t change once created
  • Faster than lists for read-only operations
  • Defined using ( and )

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

12 of 28

Data Types - Sets

  • Unordered collection of unique elements
  • Mutable, but elements are immutable
  • Useful for removing�duplicates and for�set operations
  • Defined using { and }

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)

13 of 28

Data Types - Dictionaries

  • Key-value pairs
  • Unordered
  • Mutable
  • Keys must be unique and�immutable

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

14 of 28

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

15 of 28

Loops – For Loop

  • The range() Function
    • range(start, stop, step)
    • Generates a sequence of numbers
    • Commonly used in for loops

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]

16 of 28

Loops – For Loop cont…

  • The 'in’ keyword: Used for iteration and membership testing

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

17 of 28

List Comprehension

  • Concise way to create lists
  • Combines for loop and list creation into one line
  • Can include conditional statements

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

18 of 28

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

19 of 28

Functions

  • Reusable blocks of code
  • Defined with the def keyword
  • Can have parameters and return values (one or more)

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)

20 of 28

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

21 of 28

Libraries

  • Reusable code organized in a library
  • Import a whole library to use its functions (import…)
  • Import specific functions from a library (from…)
  • Import using another name: import numpy as np

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

22 of 28

Libraries cont…

  • Some popular third-party libraries that we will utilize:

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

23 of 28

Getting User Input

  • Use the input() function to get user input
  • Input() always returns a string
  • Convert the input to other types as needed

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:

24 of 28

File Access - Linking Colab to Google Drive

  • Colab code can’t access your local storage
  • How to:
    • Click the folder icon (*1)
    • Click the drive icon (*2)
    • Approve the connection
    • Your Google Drive will be added to Colab’s files library (*3)

24

(*1)

(*2)

(*3)

25 of 28

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

26 of 28

Exercise Example

  • Challenge: Write a function that takes a list of numbers and returns the sum of all even numbers in the list
  • Example solution (yours can be simpler code):

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

27 of 28

Homework Assignments

  • Variables and Data Types:
    • Create variables for a person's name, age, height (in meters), and whether they are a student or not. Print out a sentence using all these variables
  • Control Structures:
    • Write a program that prints the first 10 numbers of the Fibonacci sequence using a while loop
  • Functions:
    • Create a function called “calculate_bmi” that takes a person's weight (in kg) and height (in meters) as parameters and returns their BMI. Then, write a program that uses this function to calculate and print the BMI for a person who is 70 kg and 1.75 m tall

27

28 of 28

Homework Assignments

  • Lists and Dictionaries:
    • Create a list of dictionaries where each dictionary represents a book with keys for “title”, “author”, and “year”. Add at least 3 books to this list. Then, write a function that takes this list and a year as parameters, and returns all books published after that year

  • Advanced challenge:
    • Create a simple address book program that allows users to:
      • Add a new contact (name, phone number, email)
      • View all contacts
      • Search for a contact by name
      • Update a contact's information
      • Delete a contact
    • Use functions, lists and dictionaries in your implementation. The program should have a menu-based interface that runs until the user chooses to exit

28