Night 11: Teach your pet a trick
لقد أنهيت هذه الليلة بالفعل باستخدام Python أو الشيفرة الكاذبة. وهي تُحتسب لكلتيهما. تدرّب مرة أخرى إن شئت.
Tonight: teach your pet a trick
- Your pet can learn tricks! You teach a trick once, then use it again and again.
- You will learn one thing: functions.
Words for tonight
| Word | Meaning |
|---|---|
| function | a named block of code; a trick with a name |
| define | say what something is; teach the trick |
| call | use the function; ask for the trick |
Define a function
defmeans define. Then the name, brackets()and a colon:.- The indented lines are the trick.
def wave():
print("*waves*")
print("Hello!")
- Press Run. Nothing happens! You taught the trick, but you did not ask for it.
Call the function
- To use the trick, write its name with brackets:
wave().
def wave():
print("*waves*")
wave()
wave()
- Each call runs all the indented lines of the function.
Why use functions?
| Without a function | With a function |
|---|---|
| copy the same lines again and again | write them once |
| a change means changing every copy | change one place |
| long code that is hard to read | short names like wave() |
Functions can call functions
- A big trick can be made from small tricks.
def wave():
print("*waves*")
def jump():
print("*jumps*")
def party():
wave()
jump()
print("Party time!")
party()
- Define a function before you call it.
- Now teach your pet some tricks in the tasks!
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Teach your pet its first trick. Define a function wave() that prints *waves*. Then call it two times.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Define two more tricks: sit() prints *sits* و spin() prints *spins*. Then call sit(), spin() و sit() again.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Define show(). It calls wave(), then sit(), then prints Ta-da!. Call show() once.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Define bedtime(). It uses a for loop to print Zzz three times. Call it once.
اضغط تشغيل لرؤية المخرجات هنا.