其實,寫這個是為了督促自己看書……然后 ……其實沒有然后了,人一松懈下來,就……ε=(′ο`*)))唉
第三章 函數(shù)
①def語句和參數(shù)
先舉一個簡單的例子:
- def hello():
- print('Hello World!')
- hello()
- hello()
- hello()
- #include<bits/stdc++.h>
- using namespace std;
- void hello()
- {
- cout<<'Hello World!\n';
- }
- int main()
- {
- hello();
- hello();
- hello();
- return 0;
- }
- def hello(name):
- print('Hello '+name+'!')
- hello('Alice')
- hello('Bob')
- print('Hello ')
- print('World!')
- print('Hello ',end='')
- print('World!')
- print('cats','dogs','mice')
- #output:cats dogs mice
- print('cats','dogs','mice',sep=',')
- #output:cats,dogs,mice
---------言歸正傳-------- import random
- def getAnswer(answerNumber):
- if answerNumber==1:
- return 'It is certain'
- elif answerNumber==2:
- return 'It is decidedly so'
- elif answerNumber==3:
- return 'Yes'
- elif answerNumber==4:
- return 'Reply hazy try again'
- elif answerNumber==5:
- return 'Ask again later'
- elif answerNumber==6:
- return 'Concentrate and ask again'
- elif answerNumber==7:
- return 'My reply is no'
- elif answerNumber==8:
- return 'Outlook not so good'
- elif answerNumber==9:
- return 'Very doubtful'
- r=random.randint(1,9)
- fortune=getAnswer(r)
- print(fortune)
- r=random.randint(1,9)
- fortune=getAnswer(r)
- print(fortune)
這里也可以寫成一行:print(getAnswer(random.randint(1,9)))
- def spam():
- eggs=31337
- spam()
- print(eggs)
- def spam():
- eggs=99
- bacon()
- print(eggs)
- def bacon():
- ham=101
- eggs=10
- spam()
- def spam():
- print(eggs)
- eggs=42
- spam()
- print(eggs)
- def spam():
- eggs='spam local'
- print(eggs)
- def bacon():
- eggs='bacon local'
- print(eggs)
- spam()
- print(eggs)
- eggs='global'
- bacon()
- print(eggs)
- def spam():
- global eggs
- eggs='spam'
- eggs='global'
- spam()
- print(eggs)
- def spam():
- global eggs
- eggs='spam'#this is global
- def bacon():
- eggs='bacon'#this is local
- def ham():
- print(eggs)#this if global
- eggs=42#this is global
- spam()
- print(eggs)