繁体   English   中英

高/低游戏

[英]Higher/Lower game

import random

user_name = input('What is your name?')
print("Welcome to the higher/lower game,", user_name + "!")
lower = int(input("Enter the lower bound:"))
upper = int(input("Enter the upper bound:"))
correct_num = random.randint(lower, upper)

if lower > upper:
    lower = int(input("Enter the lower bound:"))
    upper = int(input("Enter the upper bound:"))
else:
    correct_num = 0

guess = True
while guess:
    print("Great, now guess a number between", str(lower), "and", str(upper), ":")
    user_guess = int(input('Enter guess:'))
    if user_guess < correct_num:
        print("Nope, too low!")
    elif user_guess > correct_num:
        print("Nope, too high")
    else:
        user_guess == correct_num
        print("You got it!")
        break

这是我所拥有的。 我需要帮助从下限和上限输入中选择一个随机数。

您在代码中分配了两次 upper 和 lower 。 您可以消除它,它应该可以正常工作。

lower = int(input("Enter the lower bound:"))
upper = int(input("Enter the upper bound:"))

if lower > upper:
    correct_num = random.randint(lower, upper)
else:
    correct_num = 0 

此外,您可以通过删除guess = True并将循环更改为while True:来简化代码,因为您永远不会更改变量来中断循环,而是使用break来停止循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM