我想在python中制作一个“猜数字”游戏,我选择最小和最大数字,如果我选择的数字更低或更高,我希望它重复这个问题,我该怎么做?
这是我的代码:
import random
import time
print("Welcome to the guessing game!")
time.sleep(1)
print("Choose your minumum number")
minnum=input("Min: ")
print(" ")
print("Choose your maximum number")
maxnum=input("Max: ")
print(" ")
print("Enter your number")
num = input("Number: ")
print(" ")
q = random.randint(int(minnum), int(maxnum))
def game():
if int(num) < q:
print("The number is higher")
if int(num) > q:
print("The number is lower")
if int(num) == q:
print("Congratulations! you won!")
break
game()
print(" ")
print(" ")
input("Press enter to exit")
答案 0 :(得分:1)
在游戏中移动输入()并将其设为循环:
while
答案 1 :(得分:0)
如果用户输入了错误的猜测,您需要break
循环才能继续,如果正确,则import random
import time
print("Welcome to the guessing game!")
time.sleep(1)
print("Choose your minumum number")
minnum=input("Min: ")
print(" ")
print("Choose your maximum number")
maxnum=input("Max: ")
print(" ")
q = random.randint(int(minnum), int(maxnum))
def game():
while True: #while loop for looping continuously until correct input
print("Enter your number")
num = input("Number: ")
print(" ")
if int(num) < q:
print("The number is higher")
if int(num) > q:
print("The number is lower")
if int(num) == q: #if answer correct stop looping
print("Congratulations! you won!")
break
game()
print(" ")
print(" ")
input("Press enter to exit")
退出循环:
Welcome to the guessing game!
Choose your minumum number
Min: 1
Choose your maximum number
Max: 5
Enter your number
Number: 3
The number is lower
Enter your number
Number: 4
The number is lower
Enter your number
Number: 5
The number is lower
Enter your number
Number: 2
Congratulations! you won!
输出:
script
答案 2 :(得分:0)
如果您愿意,此变体会执行其他验证:
from random import randint
def request_user_input(query):
while True:
try:
return int(input(query))
except ValueError:
continue
def run_game(target):
while True:
guess = request_user_input('Enter your number: ')
if guess < target:
print('The number is higher')
elif guess > target:
print('The number is lower')
else:
print('Congratulations! You won!')
break
if __name__ == '__main__':
min = request_user_input('Min: ')
max = request_user_input('Max: ')
if max < min:
raise ValueError('The maximum value cannot be smaller than the minimum')
run_game(target=randint(min, max + 1))
运行示例
Min: a
Min: 10
Max: 20
Enter your number: 5
The number is higher
Enter your number: 25
The number is lower
Enter your number: 15
The number is higher
Enter your number: 18
The number is higher
Enter your number: 20
The number is lower
Enter your number: 19
Congratulations! You won!