其實,寫這個是爲了督促自己看書……然後 ……其實沒有然後了,人一鬆懈下來,就……ε=(´ο`*)))唉
第三章 函數
①def語句和參數
先舉一個簡單的例子:
def hello():
print('Hello World!')
hello()
hello()
hello()
Hello World!
Hello World!
#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')
Hello Bob!
print('Hello ')
print('World!')
最後得到的是:
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)
File "/usercode/file.py", line 4, in <module>
print(eggs)
NameError: name 'eggs' is not defined
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)
spam local
bacon local
global
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)
然後接下來,書裏是一個很……的小程序,就不放上來了,或者哪天實在無聊敲一下。
所以就到這裏啦。(✺ω✺)
'''