要求用户猜出在1到9之间生成的数字的程序。如果玩家猜到的太低,太高或相等,将会显示一条消息。仅当玩家键入“退出”时程序才结束。
我创建了三个功能。
import random
#function that creates a random number in between 1 and 9 inclusive
def number_generation():
computer_number=random.randint(1,9)
return computer_number
print(number_generation())
#function that asks the player to input number between 1 and 9
def player_number():
player_num=input('Digit your guess between 1 and 9\n')
return player_num
def guessing_game():
w_answers=0
r_answers=0
cpu_guess=int(number_generation())
player_guess=player_number()
while player_guess!='exit':
if int(player_guess)>cpu_guess:
print('You have guessed to high')
w_answers+=1
elif int(player_guess)<cpu_guess:
print('You have guessed to low')
w_answers+=1
else:
print('You have guessed the correct number')
r_answers+=1
return w_answers,r_answers
print(guessing_game())
它会永远印出您的猜测。
答案 0 :(得分:1)
如评论中所述:
while True
来调用exit()
的{{1}}循环exit
跑步可能看起来像
import random
#function that creates a random number in between 1 and 9 inclusive
def number_generation():
return random.randint(1,9)
#function that asks the player to input number between 1 and 9
def player_number():
player_num=input('Digit your guess between 1 and 9\n')
return player_num
def guessing_game():
w_answers=0
r_answers=0
#CPU guess outside the loop
cpu_guess = int(number_generation())
#While true loop
while True:
#Make the player guess inside
player_guess = player_number()
#If exit is typed, exit
if player_guess.lower() == 'exit':
break
#Else compare the guesses
if int(player_guess)>cpu_guess:
print('You have guessed to high')
w_answers+=1
elif int(player_guess)<cpu_guess:
print('You have guessed to low')
w_answers+=1
else:
print('You have guessed the correct number')
r_answers+=1
return w_answers,r_answers
print(guessing_game())