היכרות עם פייתון

קישור לחלק השני – רצף תוכנית פייתון.
קישור לחלק השלישי – פונקציות.
קישור לחלק הרביעי – מחלקות.
תרגילים.

מה היא פייתון (Python)

Python is a cross-platform, high-level, object-oriented, and interpreted programming language.

פייתון היא שפת תכנות המתאימה למגוון פלטפורמות כמו win ו-mac. היא שפה עילית ומכוונת עצמים. פייתון היא אחת משפות התכנות הנפוצות ומשתמשים בה בחברות רבות ובין השאר לפיתוח של בינה מלאכותית.

על מנת לעבוד עם פייתון צריך עורך קוד, למשל Visual Studio Code. אפשר להתנסות בפייתון באתרים שונים ברשת למשל: online-python, programiz.

עקרונות בסיסיים בכתיבת קוד פייתון

קוד פייתון נחשב מהפשוטים לכתיבה וידידותי למתחילים. בשפות רבות יש שימוש בתו ; על מנת לסיים שורה ושימוש ב-{} של מנת לסמן בלוק של פקודות. בפייתון, מעבר שורה מספיק ואין סימון לסוף שורה. כשיש בלוק של פקודות תהיה הזחה (כניסה של הטקסט פנימה) שיסמן את תחילת הבלוק. לסיום הבלוק, נחזור אחורה בשורה.

הערות

סימון הערות של שורה אחת יהיה על ידי כתיבת # בתחילת השורה. כדי לכתוב הערה של כמה שורה נסמן שורה ראשונה ואחרונה ב-""".

# Comments in python
# With # at the beginning of the line.
"""
Starting a multi line
comments
"""

פעולות מתמטיות

פעולות חשבון עובדות על מספרים בפייתון עם 2 פעולות נוספות מיוחדות. % מבצע פעולה של הבאת השארית מפעולת החילוק, ** מבצע את פעולת החזקה.

print(2+2)        # prints 4
print(10 - 5)     # prints 5
print(4 * 8)      # prints 32
print(2 / 5)      # prints 0.4
print(8 % 4)      # remainder when 8 is divided by 4, prints 0
print(8 % 3)      # remainder when 8 is divided by 3, prints 2
print(2 ** 4)     # 2 * 2 * 2 * 2, prints 16
print(3 ** 2)     # 3 * 3, prints 9

עוד סימנים מיוחדים שיש בשפות רבות וגם בפייתון הם: =+ שאומר להעלות את הערך שקיים במשתנה במספר כלשהו.

age = 30
age += 10
# Now age is 40

משתנים

משתנים מאחסנים תוצאה של פעולה. בדרך כלל לשימוש עתידי, הצגה או אחסון כלשהו בשלב מאוחר יותר. המשתנים מאוחסנים בצורה מקומית וקיימים כל עוד התוכנית עובדת. ברגע שהיא מסתיימת, המידע בהם לא נשמר.

לכל שפה יש דרך מקובלת לכתיבת שמות משתנים, בפייתון כותבים את שמות המשתנים באותיות קטנות ומשתמשים בקו תחתי להפרדת מילים. למשל: first_name.

first_name = "Dan"
age = 30

סוגי משתנים (Data Types)

מחרוזות

משתנה מסוג מחרוזת מאחסן רצף של תוים. מחרוזת מסמנים עם " או ' בהתחלה ובסוף. אפשר לפרוס מחרוזת על פני כמה שורות עם סימון של "' בהתחלה ובסוף.

first_name = 'John'
last_name = "Doe"

שירשור מחרוזות מתבצע על ידי אופרטור +.

first = "Hello "
second = "World"
long_result = first + second + "!"
# Output: Hello World!

אפשר להפריד את המילים שיש במחרוזת על ידי שימוש בפונקציה split. אם מפעילים את הפונקציה ריקה, היא תפריד את המילים במקום שיש רווח. אם שולחים תו מפריד, כלומר מה מסמן את ההפרדה במשפט, הפונקציה תפריד את המשפט לפי תו ההפרדה.

sentence = "split this string on whitespace into individual words"
print(sentence.split())

todos = 'Finish Assignment,Work on Python Lab,Watch Movie,Go to Grocery Store'
# split todos on a specific character i.e. comma ,
print(todos.split(','))

יש הרבה פונקציות מובנות למחרוזות. נראה כמה נפוצות:

# Transforming a string.
# There are more transformation functions.
######################################
string = "ConvErT ALL tO LoWErCASe"
print(string.lower())
#Output: convert all to lowercase

# Formating string - adding variables
######################################
open_string = "Sammy loves {}."
print(open_string.format("open source"))
# Output: Sammy loves open source.

print("Sammy the {1} has a pet {0}!".format("shark", "pilot fish"))
# Output: Sammy the pilot fish has a pet shark!

# String length
######################################
open_source = "Sammy contributes to open source."
print(len(open_source))
# Output: 33

# Joining strings
######################################
print(",".join(["sharks", "crustaceans", "plankton"]))
# Output: sharks,crustaceans,plankton

# Replace substring with another
######################################
balloon = "Sammy has a balloon."
print(balloon.replace("has","had"))
# Output: Sammy had a balloon.

מספרים

יש שני סוגי מספרים נפוצים int למספרים שלמים ו-float למספרים עשרוניים.

operand_one = 30
operand_two = 7
result = operand_one / operand_two # 30 / 7 = 4.285714285714286
print(result)

בוליאני (Boolean)

משתנה בוליאני הוא משתנה עם שתי אפשרויות בלבד, אמת או שקר. בין משתנים בוליאני אפשר להפעיל אופרטורים לוגיים. למשל אם המשפט הראשון נכון וגם השני ונפעיל ביניהם אופרטור "וגם" אז תתקבל תוצאת אמת.

value_a = True
value_b = False
value_c = True
value_d = False

print(value_a and value_b) # True and False will print False
print(value_a and value_c) # True and True will print True
print(value_a or value_d) # True or False will print True
print(value_b or value_d) # False or False will print False
print(not value_d) # not False will print True

כשמשתמשים באופרטורים של השוואה כמו גדול/קטן/שווה, התוצאה שמתקבלת היא בוליאנית, כלומר האם הביטוי נכון או לא. צריך לשים שהשוואה מתבצעת על ידי שימוש ב ==. שימוש ב = אחד יבצע השמה ולא השוואה.

grades = 85
attendance = 95
has_plagiarized = False
print(not has_plagiarized)

successfully_graduated = (grades > 70) and (attendance > 90) and (not has_plagiarized)
print(successfully_graduated)

רשימות (Lists)

יצירת רשימה נעשית על ידי ערכים המופרדים בפסיק בתוך סוגריים מרובעות. אפשר לשים כערך, רשימה אחרת. רשימה יכולה להכיל סוגים שונים של משתנים.

# grades is a list that contains a collection of grades that are whole numbers
grades = [65, 55, 95, 70, 82, 100, 63, 89, 93]
# Woody Allen movies
woody_allen_movies = ['A Rainy Day In New York', 
    'Cafe Society', 
    'Whatever Words', 
    'Blue Jasmine', 
    'Manhattan']
# 3x3 matrix created using list
matrix = [[1,2,3], [4,5,6], [7,8,9]]

צירוף רשימות ביחד

grades = [65, 55, 95, 70, 82, 100, 63, 89, 93]
new_grades = grades + [65, 55, 95]
print(new_grades )

הוספת ערך לרשימה

אפשר להוסיף ערך לסוף הרשימה.

grades = [65, 55, 95, 70, 82, 100, 63, 89, 93]
grades.append(100)
print(grades)
# Output: [65, 55, 95, 70, 82, 100, 63, 89, 93, 100]

הסרת ערך בודד מהרשימה

אפשר להסיר ערך מהרשימה על ידי שליחת הערך. אם הערך מופיע פעמיים, יוסר המופע הראשון שלו.

grades = [65, 55, 95, 70, 82, 100, 63, 89, 93]
 
# Removes the first occurance of 55
shopping_line.remove(55)
print(grades)

# Output: [65, 95, 70, 82, 100, 63, 89, 93]

ספירת כמות הערכים ברשימה

grades = [55, 55, 95, 70, 82, 100, 63, 89, 93]
numGrades = grades.count(55)

print(numGrades)
# Output: 2

אורך רשימה

grades = [55, 55, 95, 70, 82, 100, 63, 89, 93]
size = len(grades)
print(size) 
# Output: 9

מיון רשימה

grades = [65, 55, 95, 70, 82, 100, 63, 89, 93]
grades.sort()
print(grades)
# Output: [55, 63, 65, 70, 82, 89, 93, 95, 100]

הסרת ערך בודד על פי אינדקס

אפשר להסיר ערך במקום מסויים. אם לא מספקים מקום, יוסר הערך האחרון.

grades = [65, 55, 95, 70, 82, 100, 63, 89, 93]

# Pop the last element
removed_element = grades.pop()

print(grades)
print(removed_element)

# Output:
# [65, 55, 95, 70, 82, 100, 63, 89]
# 93

# Pop the element 100
grades.pop(5)
print(grades)

# Output:
# [65, 55, 95, 70, 82, 63, 89]

הגישה לערכי הרשימה תהיה על ידי האינדקס של הערך שרוצים. האינדקס מתחיל במספר 0.

אפשר גם להשתמש באינדקס שלילי. האיבר האחרון הרשימה יהיה באינדקס 1-, השני לפני הסוף ב: 2- וכן הלאה.

אפשר גם לגשת לחלק מהרשימה על ידי שימוש ב [אינדקס_אחרון:אינדקס_ראשון].

אפשר להסיר ערך מהרשימה על ידי del.

grades = [65, 55, 95, 70, 82, 100, 63, 89, 93]

# access grade 100 at index 5 from grades list
print(grades[5])
# Output: 100

# access 'Cafe Society' from woody_allen movies list at index 1
print(woody_allen_movies[1])
# Output: Cafe Society

# access row [4,5,6] from matrix list at index 1
print(matrix[1])
# Output: [4,5,6]

# access row [4,5,6] from matrix available at index 1 & print number 6
# at index 2 in the same row
print(matrix[1][2])
# Output: 6

# access grade 100 at index -4 (4th from the end) from grades list
print (grades[-4])
# Output: 100

# access first four grades from grades list
print(grades [0:4])
# Output: [65, 55, 95, 70]

# delete grades 55 & 95 from list grades
del grades [1:3]
print(grades)
# Output: [65, 70, 82, 100, 63, 89, 93]

מעבר על איברי הרשימה יתבצע בדרך כלל על ידי שימוש בלולאות.

מילון (Dictionary)

Dictionary הוא אוסף של זוגות של מפתח:ערך (key-value pairs).

יצירה של Dictionary תתבצע בצורה הזאת:

My_dict = {key: value, anotherKey: anotherValue}

ערך של מפתח חייב להיות ייחודי והגישה לערכים לא תהיה על ידי אינדקס כמו ברשימה אלא על ידי פנייה למפתח המתאים לערך.

יצירת Dictionary

# create a dictionary using curly brackets called john
# that stores name, phone, email, course and address
john = {'name': 'John', 
   'phone': 1234567890, 
   'email': 'john.doe@gmail.com', 
   'course: Python v3', 
   'address': '123 Front St City Country'}
print(john)

# create a dictionary using dict() called adam 
# that stores name, phone, email, course
adam = dict ({'name': 'Adam', 'phone': 1234567890, 'email': 'adam.smith@email.com',
'course': 'Python v3'})
print(adam)

גישה לערך ב-Dictionary

john = {'name': 'John', 
   'phone': 1234567890, 
   'email': 'john.doe@gmail.com', 
   'course: Python v3', 
   'address': '123 Front St City Country'}

print(john['name'])
# Output: John
print(john['email'])
# Output: john.doe@gmail.com

עדכון ערך ב-Dictionary

john = {'name': 'John', 
   'phone': 1234567890, 
   'email': 'john.doe@gmail.com', 
   'course: Python v3', 
   'address': '123 Front St City Country'}

john['phone'] = 9876543210
print(john)
# Output: {'name': 'John', 'phone': 9876543210, 'email': 'john.doe@gmail.com', 'course': 'Python v3', 'address': '123 Front St City Country'}

ביטול ערך ב-Dictionary

john = {'name': 'John', 
   'phone': 1234567890, 
   'email': 'john.doe@gmail.com', 
   'course: Python v3', 
   'address': '123 Front St City Country'}

# delete address for john
john.pop('address')
print(john)
# Output: {'name': 'John', 'phone': 1234567890, 'email': 'john.doe@gmail.com', 'course': 'Python v3'}

ביטול Dictionary

john = {'name': 'John', 
   'phone': 1234567890, 
   'email': 'john.doe@gmail.com', 
   'course: Python v3', 
   'address': '123 Front St City Country'}

del john

סט (Set)

Set הוא אוסף לא מסודר של ערכים ולא יכול להיות בו ערך כפול, כל הערכים ייחודיים. אם יש ערך כפול הוא יוסר.

יצירת set

# movies to watch for john
john_movies_wishlist = {'Titanic', 'Die Hard', 'Pulp Fiction', 'Forrest Gump', 'Parasite', 'Die Hard'}
# movies to watch for adam
adam_movies_wishlist = {'Psycho', 'The Lion King', 'Titanic', 'Parasite', 'Gladiator', 'Coco'}

# note: duplicate items from a set are automatically removed
print(john_movies_wishlist)
# Output: {'Parasite', 'Die Hard', 'Pulp Fiction', 'Forrest Gump', 'Titanic'}

# note: items do not appear in the same order as written
print(adam_movies_wishlist)
# Output: {'Parasite', 'Gladiator', 'Psycho', 'The Lion King', 'Titanic', 'Coco'}

פעולות שניתן לבצע על set

אפשר למצוא ערכים שנמצאים ב-set אחד ולא באחר, ערכים שמשותפים לשני set, שנמצאים לפחות באחד מהם ועוד.

# movies to watch for john
john_movies_wishlist = {'Titanic', 'Die Hard', 'Pulp Fiction', 'Forrest Gump', 'Parasite', 'Die Hard'}
# movies to watch for adam
adam_movies_wishlist = {'Psycho', 'The Lion King', 'Titanic', 'Parasite', 'Gladiator', 'Coco'}

# movies in John’s wishlist but not Adam’s
print(john_movies_wishlist - adam_movies_wishlist)
# Output: {'Pulp Fiction', 'Die Hard', 'Forrest Gump'}

# movies in either John's wishlist or Adam's wishlist or in both wishlists
print(john_movies_wishlist | adam_movies_wishlist)
# Output: {'Coco', 'Parasite', 'Gladiator', 'Titanic', 'Pulp Fiction', 'The Lion King', 'Forrest Gump', 'Psycho', 'Die Hard'}

# movies in both John's wishlist and Adam's wishlist
print(john_movies_wishlist & adam_movies_wishlist)
# Output: {'Titanic', 'Parasite'}

# movies in either John's wishlist or Adam's wishlist but not in both
print(john_movies_wishlist ^ adam_movies_wishlist)
# Output: {'Coco','Gladiator', 'The Lion King', 'Pulp Fiction', 'Forrest Gump', 'Psycho', 'Die Hard'}

Tuple

Tuple (אין מילה בעברית, אפשר להשתמש במילה רשומה) דומה לרשימה (list), אבל ההבדל הוא בצורת היצירה של המשתנה ובכך שב-Tuple אי אפשר לשנות ערכים אחרי שהגדרנו אותו.

יצירת Tuple

# create a tuple of first five odd numbers
odd_numbers = (1, 3, 5, 7, 9)

print(odd_numbers)
(1, 3, 5, 7, 9)

odd_numbers[1] = 2 # Will give ERROR

אפשר להגדיר Tuple ולפרק את הערכים שלו למשתנים שנגדיר.

# create a tuple called student while PACKING name, age, course and 
# phone number
# note: as you can see parantheses are optional while packing values 
# into tuple

student = 'John Doe', 27, 'Python v3', 1234567890
print (student)
# Output: ('John Doe', 27, 'Python v3', 1234567890)

# let's unpack the values from student tuple into individual variables
name, age, course, phone = student

print (name)
print (age)
print (course)
print (phone)

# Output: John Doe
# Output: 27
# Output: Python v3
# Output: 1234567890

גישה לערכים ב-Tuple

student = 'John Doe', 27, 'Python v3', 1234567890

# let's unpack the values from student tuple into individual variables
name, age, course, phone = student

# get course from student tuple using indexing
print(student[2])
# Output: Python v3

# get course from student tuple using negative indexing, -1 is the last element
print(student[-2])
# Output: Python v3

# get course from student tuple using slicing
print(student[2:3])
# Output: ('Python v3’,)

המרה מסוג משתנה אחד לאחר

# num_one of type integer
nun_one = 50
# num_two of type string
num_two_str = "150.75"
# num_two explicitly converted from string to number
num_two = float(num_two_str)

מעבר לחלק 2 רצף קוד בפייתון: תנאים ולולאות.

ניווט במאמר

מאמרים אחרונים

Weekly Tutorial