3.1 def语句与参数
def hello(name):
print('Hello' +' ' + name)
hello('Alice')
hello('Bob')
3.2 返回值和return语句
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is a certain'
elif answerNumber == 2:
return 'Yes'
elif answerNumber == 3:
return 'It is decidely so'
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 replly is no'
elif answerNumber == 8:
return 'Out look not so good'
elif answerNumber == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
3.3 global语句
如果需要在一个函数内修改全局变量,就会使用global语句。如果在函数的顶部有global eggs语句,就告诉python,eggs指代全局变量,所以不要用这个名字
创建局部变量
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
3.4 一个小程序,猜数字
import random
secretNumber = random.randint(1, 20)
print('I am thinkinng of a number between 1 and 20')
# ask the player too guess 6 times
for guessesTaken in range(1, 7):
print('Take a guess')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low')
elif guess > secretNumber:
print('Your guess is too high')
else:
break # this condition is the coorrect guess
if guess == secretNumber:
print('Good job! your guessd my number in' + str(guessesTaken) + 'guesses!')
else:
print('Nope, The number I was thinking of was' + str(secretNumber))
实践项目
编写一个名为collatz()的函数,他有一个名为number的参数,如果参数是偶数,那么collatz()就打印出number//2,并返回该值,如果Number是奇数,collatz()
就打印并返回 3*number + 1
然后编写一个程序,让用户输入一个整数,并不断对这个数调用collatz(),直到函数返回值为1
def collatz(number):
if number % 2 == 0:
return a//2
elif number % 2 !=0:
return 3 * a + 1
try:
a = int(input('please input a number'))
while True:
a = collatz(a)
if a == 1:
print(a)
break
except ValueError:
print('Please input a right int num')