生成1到9(包括1到9)之间的随机数。让用户猜测数字,然后告诉他们猜测的数字是否太低,太高或完全正确。 (_Hint:请记住在第一练习中使用用户输入的课程
其他:
让游戏继续进行,直到用户键入“退出” 跟踪用户进行了多少猜测,当游戏结束时,将其打印出来。
我已将程序分为三个功能
import random
# function to generate random number between 1 and 9
def generate():
cpu_number=random.randint(1,9)
print(cpu_number)
# function to input player guess
def player_guess():
player_number=input('Digit a number between 1 and 9\n')
#function to keep asking the player the value unless he writes exit. Also return wrong and right guesses
def game():
right_guesses=0
wrong_guesses=0
while player_guess()!= 'exit':
if player_guess() > generate():
print('Higher value than the value generated!')
wrong_guesses += 1
elif player_guess() < generate():
print('Lower value than the value generated!')
wrong_guesses += 1
else:
print('You have guessed the correct value!!!!')
right_guesses += 1
print('You have entered',right_guesses,'guesses and',wrong_guesses,'guesses')
return right_guesses,wrong_guesses
print(generate())
print(player_guess())
print(game())
我的程序未运行if语句。如果我键入exit,它也不会停止
答案 0 :(得分:1)
import random
# function to generate random number between 1 and 9
def generate():
return random.randint(1,9)
# function to input player guess
def player_guess():
return input('Digit a number between 1 and 9\n')
#function to keep asking the player the value unless he writes exit. Also return wrong and right guesses
def game():
right_guesses=0
wrong_guesses=0
while True:
guess = player_guess()
if guess == 'exit':
break
if int(guess) > generate():
print('Higher value than the value generated!')
wrong_guesses += 1
elif int(guess) < generate():
print('Lower value than the value generated!')
wrong_guesses += 1
else:
print('You have guessed the correct value!!!!')
right_guesses += 1
print('You have entered', right_guesses,'correct guesses and', wrong_guesses,'wrong guesses')
return right_guesses, wrong_guesses
game()
答案 1 :(得分:0)
player_guess
不会为game
中的循环返回任何响应。另外,每个所需的输入似乎多次调用它。