将所学的知识综合起来,编写一个更完整的程序
# This is a guess the number game.
import random
secretNumber = random.randint(1,20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessTanken 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 correct guess!
if guess == secretNumber:
print('God job! You guessed my number in ' + str(guessTaken) + 'guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
函数时将代码逻辑分组的主要方式。
因为函数中的变量存在于它们自己的局部作用域内,所以一个函数中的代码不能直接影响其他函数中变量的值。
函数是很好的工具,能帮助你组织代码。可以认为它们是黑盒。它们以参数的形式接收输入,以返回值的形式产生输出。它们内部的代码不会影响其他函数中的变量。