Scope וערכי החזרהScope & return values
return מול print, משתנים מקומיים וגלובליים, ופונקציות טהורות.
return vs print, local and global variables, and pure functions.
01return מול printreturn vs print
זה הבלבול הכי נפוץ אצל מתחילים. print רק מציגה טקסט על המסך, והתוכנית לא יכולה להשתמש בו. return מוסרת ערך בחזרה לקוד שקרא, ואפשר לחשב איתו, לשמור או להשוות.
This is beginners' most common mix-up. print only shows text on screen, and the program can't use it. return hands a value back to the calling code, which can calculate with it, store or compare it.
def show_total(a, b):
print(a + b)
def get_total(a, b):
return a + b
x = show_total(2, 3)
y = get_total(2, 3)
print("x =", x)
print("y =", y, "| y * 10 =", y * 10)5 x = None y = 5 | y * 10 = 50
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
print היא לצעוק את התשובה בחדר: כולם שומעים, אבל אף אחד לא רשם. return היא לכתוב את התשובה על פתק ולמסור אותו ביד: אפשר לשמור, להעתיק ולהשתמש.
print is shouting the answer across the room: everyone hears, nobody wrote it down. return is writing it on a note and handing it over: it can be kept, copied and used.
מחשבים עם תוצאה של פונקציה שרק מדפיסה.
Calculating with the result of a function that only prints.
def average(nums):
print(sum(nums) / len(nums))
score = average([80, 90])
print(score > 85)85.0
Traceback (most recent call last):
File "/Users/you/python-course/rvp.py", line 5, in <module>
print(score > 85)
^^^^^^^^^^
TypeError: '>' not supported between instances of 'NoneType' and 'int'TypeError: '>' not supported between instances of 'NoneType' and 'int': average מחזירה None. משנים ל-return sum(nums) / len(nums).TypeError: '>' not supported between instances of 'NoneType' and 'int': average returns None. Change it to return sum(nums) / len(nums).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02מסגרות: כל קריאה מקבלת משתנים משלהFrames: each call gets its own variables
בכל קריאה לפונקציה Python יוצרת מסגרת חדשה בזיכרון, ובה הפרמטרים והמשתנים המקומיים. כשהפונקציה מחזירה ערך, המסגרת נמחקת. בוויזואלייזר רואים את זה קורה:
On every function call Python creates a new frame in memory holding the parameters and local variable variables. When the function returns, the frame is deleted. Watch it happen in the visualizer:
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
מסגרת היא כמו דף טיוטה שמקבלים לכל תרגיל במבחן: כותבים עליו חישובים, מעבירים רק את התשובה הסופית לדף התשובות, והטיוטה נזרקת.
A frame is like the scrap paper you get for each exam question: you do the working on it, copy only the final answer onto the answer sheet, and the scrap is thrown away.
מנסים להשתמש במשתנה מקומי מחוץ לפונקציה.
Trying to use a local variable outside the function.
def pages_left(total, read):
left = total - read
return left
pages_left(412, 100)
print(left)Traceback (most recent call last):
File "/Users/you/python-course/frames.py", line 6, in <module>
print(left)
^^^^
NameError: name 'left' is not definedNameError: name 'left' is not defined: left חי רק בתוך המסגרת. שומרים את מה שחוזר: left = pages_left(412, 100).NameError: name 'left' is not defined: left lives only in the frame. Keep what comes back: left = pages_left(412, 100).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03scope: מקומי מול גלובליScope: local vs global
טווח הכרה (scope) קובע איפה משתנה מוכר. משתנה גלובלי (ברמת הקובץ) אפשר לקרוא מתוך פונקציה. אבל ברגע שעושים לו השמה בתוך הפונקציה, Python מחליטה שזה משתנה מקומי חדש, וזה מקור לבאגים.
scope decides where a variable is known. A global variable (file-level) variable can be read inside a function. But the moment you assign to it inside the function, Python decides it's a new local, which causes bugs.
rate = 40
def hours(pages):
return pages / rate
def hours_fast(pages):
rate = 60
return pages / rate
print(hours(120), hours_fast(120), rate)3.0 2.0 40
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
משתנה גלובלי הוא כמו שעון על קיר המשרד: כל אחד רואה אותו. אבל אם מישהו תולה שעון משלו בתא שלו, זה שעון אחר, ושעון הקיר לא זז.
A global is like the clock on the office wall: everyone can see it. But if someone hangs their own clock in their cubicle, that's a different clock, and the wall clock doesn't move.
מעדכנים משתנה גלובלי בתוך פונקציה בלי להעביר אותו.
Updating a global inside a function without passing it in.
count = 0
def add_book():
count += 1
add_book()Traceback (most recent call last):
File "/Users/you/python-course/scope.py", line 6, in <module>
add_book()
~~~~~~~~^^
File "/Users/you/python-course/scope.py", line 4, in add_book
count += 1
^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueUnboundLocalError: ה-+= הופך את count למקומי, אבל אין לו ערך עדיין. פותרים עם def add_book(count): return count + 1.UnboundLocalError: the += makes count local, but it has no value yet. Fix: def add_book(count): return count + 1.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
משתנה שנוצר בתוך פעולה קיים רק שם.
A variable made inside an action exists only there.
score = 10
def bonus():
score = 99
return score
print(bonus())
print(score)99 10
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04להחזיר כמה ערכיםReturning several values
return a, b מחזיר טאפל, ובקריאה מפרקים אותו לשני משתנים. return באמצע הפונקציה ("return מוקדם") עוצר אותה מיד, וזה נוח לטיפול במקרים מיוחדים בהתחלה.
return a, b returns a tuple, which the caller unpacks into two variables. A return in the middle ("early return") stops the function at once, handy for handling special cases first.
def stats(pages):
if not pages:
return 0, 0
return min(pages), max(pages)
low, high = stats([412, 96, 1036])
print(low, high)
print(stats([]))96 1036 (0, 0)
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
החזרת כמה ערכים היא כמו לקבל מהקופאית גם קבלה וגם עודף באותה מסירה.
Returning several values is like getting both the receipt and the change from the cashier in one hand-off.
מפרקים למספר משתנים שלא מתאים למה שחוזר.
Unpacking into the wrong number of variables.
def stats(pages):
return min(pages), max(pages)
low, high, avg = stats([1, 2])Traceback (most recent call last):
File "/Users/you/python-course/multi.py", line 4, in <module>
low, high, avg = stats([1, 2])
^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 3, got 2)ValueError: not enough values to unpack (expected 3, got 2): מספר המשתנים בצד שמאל חייב להתאים.ValueError: not enough values to unpack (expected 3, got 2): the number of names on the left must match.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05פונקציות טהורות ותופעות לוואיPure functions and side effects
פונקציה טהורה מחזירה תוצאה שתלויה רק בפרמטרים, ולא משנה כלום בחוץ. תופעת לוואי היא כל דבר נוסף: הדפסה, כתיבה לקובץ, שינוי רשימה שקיבלה. תוכנית טובה מחזיקה את רוב הלוגיקה בפונקציות טהורות.
A pure function returns a result that depends only on its parameters and changes nothing outside. A side effect is anything else: printing, writing a file, changing a list it received. A good program keeps most logic in pure functions.
def add_pure(shelf, title):
return shelf + [title]
def add_inplace(shelf, title):
shelf.append(title)
mine = ["Dune"]
new = add_pure(mine, "Emma")
print(mine, new)
add_inplace(mine, "Emma")
print(mine)['Dune'] ['Dune', 'Emma'] ['Dune', 'Emma']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
פונקציה טהורה היא כמו מחשבון: אותו תרגיל תמיד נותן אותה תשובה, והמחשבון לא כותב לכם במחברת. פונקציה עם תופעות לוואי היא כמו עוזר שגם מסדר לכם את השולחן בלי לשאול.
A pure function is like a calculator: the same sum always gives the same answer, and it never writes in your notebook. A function with side effects is like a helper who also tidies your desk without asking.
ברירת מחדל שהיא רשימה: אותה רשימה משותפת לכל הקריאות. בדיקה כאן חושפת את המלכודת.
A list as a default value: one list shared by every call. A check here exposes the trap.
def add(title, shelf=[]):
shelf.append(title)
return shelf
add("Dune")
second = add("Emma")
assert second == ["Emma"], f"got {second}"Traceback (most recent call last):
File "/Users/you/python-course/pure.py", line 7, in <module>
assert second == ["Emma"], f"got {second}"
^^^^^^^^^^^^^^^^^^
AssertionError: got ['Dune', 'Emma']AssertionError: הרשימה נוצרת פעם אחת כשמגדירים את הפונקציה. כותבים shelf=None ובתוך הפונקציה if shelf is None: shelf = [].AssertionError: the list is created once, when the function is defined. Write shelf=None and inside if shelf is None: shelf = [].צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06פונקציות שקוראות לפונקציותFunctions calling functions
פונקציות קוראות זו לזו, ובכל קריאה נוספת מסגרת מעל הקודמת. זו "מחסנית הקריאות", וזה מה שמופיע ב-Traceback (מפגש 11). מקרה מיוחד: פונקציה שקוראת לעצמה, רקורסיה, חייבת תנאי עצירה.
Functions call each other, each call adding a frame on top of the last. That's the "call stack", and it's what a traceback shows (session 11). A special case: a function calling itself, recursion, which needs a stopping condition.
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
מחסנית קריאות היא כמו ערימת צלחות: מניחים צלחת חדשה למעלה בכל קריאה, ומורידים אותה כשהפונקציה חוזרת.
The call stack is like a pile of plates: a new plate goes on top with each call, and comes off when the function returns.
רקורסיה בלי תנאי עצירה.
Recursion with no stopping condition.
def countdown(n):
print(n)
countdown(n - 1)
countdown(3)3
2
1
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-16
-17
-18
-19
-20
-21
-22
-23
-24
-25
-26
-27
-28
-29
-30
-31
-32
-33
-34
-35
-36
-37
-38
-39
-40
-41
-42
-43
-44
-45
-46
-47
-48
-49
-50
-51
-52
-53
-54
-55
-56
-57
-58
-59
-60
-61
-62
-63
-64
-65
-66
-67
-68
-69
-70
-71
-72
-73
-74
-75
-76
-77
-78
-79
-80
-81
-82
-83
-84
-85
-86
-87
-88
-89
-90
-91
-92
-93
-94
-95
-96
-97
-98
-99
-100
-101
-102
-103
-104
-105
-106
-107
-108
-109
-110
-111
-112
-113
-114
-115
-116
-117
-118
-119
-120
-121
-122
-123
-124
-125
-126
-127
-128
-129
-130
-131
-132
-133
-134
-135
-136
-137
-138
-139
-140
-141
-142
-143
-144
-145
-146
-147
-148
-149
-150
-151
-152
-153
-154
-155
-156
-157
-158
-159
-160
-161
-162
-163
-164
-165
-166
-167
-168
-169
-170
-171
-172
-173
-174
-175
-176
-177
-178
-179
-180
-181
-182
-183
-184
-185
-186
-187
-188
-189
-190
-191
-192
-193
-194
-195
-196
-197
-198
-199
-200
-201
-202
-203
-204
-205
-206
-207
-208
-209
-210
-211
-212
-213
-214
-215
-216
-217
-218
-219
-220
-221
-222
-223
-224
-225
-226
-227
-228
-229
-230
-231
-232
-233
-234
-235
-236
-237
-238
-239
-240
-241
-242
-243
-244
-245
-246
-247
-248
-249
-250
-251
-252
-253
-254
-255
-256
-257
-258
-259
-260
-261
-262
-263
-264
-265
-266
-267
-268
-269
-270
-271
-272
-273
-274
-275
-276
-277
-278
-279
-280
-281
-282
-283
-284
-285
-286
-287
-288
-289
-290
-291
-292
-293
-294
-295
-296
-297
-298
-299
-300
-301
-302
-303
-304
-305
-306
-307
-308
-309
-310
-311
-312
-313
-314
-315
-316
-317
-318
-319
-320
-321
-322
-323
-324
-325
-326
-327
-328
-329
-330
-331
-332
-333
-334
-335
-336
-337
-338
-339
-340
-341
-342
-343
-344
-345
-346
-347
-348
-349
-350
-351
-352
-353
-354
-355
-356
-357
-358
-359
-360
-361
-362
-363
-364
-365
-366
-367
-368
-369
-370
-371
-372
-373
-374
-375
-376
-377
-378
-379
-380
-381
-382
-383
-384
-385
-386
-387
-388
-389
-390
-391
-392
-393
-394
-395
-396
-397
-398
-399
-400
-401
-402
-403
-404
-405
-406
-407
-408
-409
-410
-411
-412
-413
-414
-415
-416
-417
-418
-419
-420
-421
-422
-423
-424
-425
-426
-427
-428
-429
-430
-431
-432
-433
-434
-435
-436
-437
-438
-439
-440
-441
-442
-443
-444
-445
-446
-447
-448
-449
-450
-451
-452
-453
-454
-455
-456
-457
-458
-459
-460
-461
-462
-463
-464
-465
-466
-467
-468
-469
-470
-471
-472
-473
-474
-475
-476
-477
-478
-479
-480
-481
-482
-483
-484
-485
-486
-487
-488
-489
-490
-491
-492
-493
-494
-495
-496
-497
-498
-499
-500
-501
-502
-503
-504
-505
-506
-507
-508
-509
-510
-511
-512
-513
-514
-515
-516
-517
-518
-519
-520
-521
-522
-523
-524
-525
-526
-527
-528
-529
-530
-531
-532
-533
-534
-535
-536
-537
-538
-539
-540
-541
-542
-543
-544
-545
-546
-547
-548
-549
-550
-551
-552
-553
-554
-555
-556
-557
-558
-559
-560
-561
-562
-563
-564
-565
-566
-567
-568
-569
-570
-571
-572
-573
-574
-575
-576
-577
-578
-579
-580
-581
-582
-583
-584
-585
-586
-587
-588
-589
-590
-591
-592
-593
-594
-595
-596
-597
-598
-599
-600
-601
-602
-603
-604
-605
-606
-607
-608
-609
-610
-611
-612
-613
-614
-615
-616
-617
-618
-619
-620
-621
-622
-623
-624
-625
-626
-627
-628
-629
-630
-631
-632
-633
-634
-635
-636
-637
-638
-639
-640
-641
-642
-643
-644
-645
-646
-647
-648
-649
-650
-651
-652
-653
-654
-655
-656
-657
-658
-659
-660
-661
-662
-663
-664
-665
-666
-667
-668
-669
-670
-671
-672
-673
-674
-675
-676
-677
-678
-679
-680
-681
-682
-683
-684
-685
-686
-687
-688
-689
-690
-691
-692
-693
-694
-695
-696
-697
-698
-699
-700
-701
-702
-703
-704
-705
-706
-707
-708
-709
-710
-711
-712
-713
-714
-715
-716
-717
-718
-719
-720
-721
-722
-723
-724
-725
-726
-727
-728
-729
-730
-731
-732
-733
-734
-735
-736
-737
-738
-739
-740
-741
-742
-743
-744
-745
-746
-747
-748
-749
-750
-751
-752
-753
-754
-755
-756
-757
-758
-759
-760
-761
-762
-763
-764
-765
-766
-767
-768
-769
-770
-771
-772
-773
-774
-775
-776
-777
-778
-779
-780
-781
-782
-783
-784
-785
-786
-787
-788
-789
-790
-791
-792
-793
-794
-795
-796
-797
-798
-799
-800
-801
-802
-803
-804
-805
-806
-807
-808
-809
-810
-811
-812
-813
-814
-815
-816
-817
-818
-819
-820
-821
-822
-823
-824
-825
-826
-827
-828
-829
-830
-831
-832
-833
-834
-835
-836
-837
-838
-839
-840
-841
-842
-843
-844
-845
-846
-847
-848
-849
-850
-851
-852
-853
-854
-855
-856
-857
-858
-859
-860
-861
-862
-863
-864
-865
-866
-867
-868
-869
-870
-871
-872
-873
-874
-875
-876
-877
-878
-879
-880
-881
-882
-883
-884
-885
-886
-887
-888
-889
-890
-891
-892
-893
-894
-895
-896
-897
-898
-899
-900
-901
-902
-903
-904
-905
-906
-907
-908
-909
-910
-911
-912
-913
-914
-915
-916
-917
-918
-919
-920
-921
-922
-923
-924
-925
-926
-927
-928
-929
-930
-931
-932
-933
-934
-935
-936
-937
-938
-939
-940
-941
-942
-943
-944
-945
-946
-947
-948
-949
-950
-951
-952
-953
-954
-955
-956
-957
-958
-959
-960
-961
-962
-963
-964
-965
-966
-967
-968
-969
-970
-971
-972
-973
-974
-975
-976
-977
-978
-979
-980
-981
-982
-983
-984
-985
-986
-987
-988
-989
-990
-991
-992
-993
-994
-995
Traceback (most recent call last):
File "/Users/you/python-course/compose.py", line 5, in <module>
countdown(3)
~~~~~~~~~^^^
File "/Users/you/python-course/compose.py", line 3, in countdown
countdown(n - 1)
~~~~~~~~~^^^^^^^
File "/Users/you/python-course/compose.py", line 3, in countdown
countdown(n - 1)
~~~~~~~~~^^^^^^^
File "/Users/you/python-course/compose.py", line 3, in countdown
countdown(n - 1)
~~~~~~~~~^^^^^^^
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceededRecursionError: maximum recursion depth exceeded: מוסיפים if n == 0: return בתחילת הפונקציה.RecursionError: maximum recursion depth exceeded: add if n == 0: return at the top of the function.פעולות קטנות מתחברות לפעולה גדולה.
Small actions combine into a bigger one.
def double(x):
return x * 2
def add_one(x):
return x + 1
print(add_one(double(5)))
print(double(add_one(5)))11 12
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.