我正在创建一个迷你项目,用户必须猜测随机选择的1到10之间的数字。
我的代码可以达到用户猜测正确数字的程度。它会循环回“restart = 1”,但不会生成新号码吗?
以下是我的意思截图 - https://gyazo.com/1b6c9afc17997e7a0ee059a8b0eeb89e 正如你在那种情况下看到的那样,数字不会从6变化?
获得任何帮助真是太棒了!
# Useful module for selecting random numbers
import random
# Return to this point when user guesses the correct number
restart = 1
while (restart < 10):
# Variable that chooses a random number
Random_Number = (random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# Loop back to this point
loop = 1
# Checks if users number is correct or not
while (loop < 10):
personStr = input("Guess the random number from 1 - 10?: ")
person = int(personStr)
if person == Random_Number:
print ("You are correct!, the number is", Random_Number)
print ("Try to guess the new number!")
restart = restart + 1
elif Random_Number < person:
print ("Your number is smaller than your selected number, try again!")
loop = loop + 1
else:
print ("Your number is larger than your selected number, try again!")
loop = loop + 1
答案 0 :(得分:1)
您必须为第二个循环添加break
:
if person == Random_Number:
print ("You are correct!, the number is", Random_Number)
print ("Try to guess the new number!")
restart = restart + 1
break
答案 1 :(得分:1)
添加一个中断以退出循环。
# Useful module for selecting random numbers
import random
# Return to this point when user guesses the correct number
restart = 1
while (restart < 10):
# Variable that chooses a random number
Random_Number = (random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# Loop back to this point
loop = 1
# Checks if users number is correct or not
while (loop < 10):
personStr = input("Guess the random number from 1 - 10?: ")
person = int(personStr)
if person == Random_Number:
print ("You are correct!, the number is", Random_Number)
print ("Try to guess the new number!")
restart = restart + 1
break # add a break here
elif Random_Number < person:
print ("Your number is smaller than your selected number, try again!")
loop = loop + 1
else:
print ("Your number is larger than your selected number, try again!")
loop = loop + 1
答案 2 :(得分:0)
使用Random_Number = random.randint(1, 10)
生成1到10的随机整数,并在条件语句后使用break;
。
答案 3 :(得分:-1)
听起来你正在寻找random.shuffle
然后使用循环作为索引,如下所示:
# Useful module for selecting random numbers
import random
# Return to this point when user guesses the correct number
restart = 0
rand_nums = random.shuffle(range(1, 11)).
# ^Assuming you only want one of each in range (1,11)
while restart < 10:
restart += 1
# Loop back to this point
loop = 1
# Checks if users number is correct or not
while loop < 10:
loop += 1
personStr = input("Guess the random number from 1 - 10?: ")
person = int(personStr)
if person == rand_nums[restart]:
print ("You are correct!, the number is", rand_nums[restart])
print ("Try to guess the new number!")
break
elif rand_nums[restart] < person:
print ("Your number is smaller than your selected number, try again!")
else:
print ("Your number is larger than your selected number, try again!")
编辑:正如其他人所说,你可能想要break
出于你的条件。上面的代码现在也包括了。