我需要一个python程序,使用while,for和if循环:
# initial print statement after setting a random
A secret random integer between 100 and 200 has been generated.
Can you guess what it is?
Make a guess between 100 and 200: 180
Wrong number! The secret number is less than 180.
Make a guess between 100 and 179: 140
Wrong number! The secret number is larger than 140.
Make a guess between 141 and 179: 130
Invalid input! Please make a guess between 141 and 179.
Make a guess between 141 and 179: 155
Wrong number! The secret number is larger than 155.
Make a guess between 156 and 179: 162
Congratulation! You got the right number.
应该在100到200之间生成一个随机数,每次从用户输入后该范围应该动态变化
代码
from random import *
rand = int(randint(100,200))
usr_inp = int(input("Enter a number between 0 and 100: "))
low_range = 0
up_range = 0
if usr_inp != rand:
for i in range(int(low_range), int(up_range)):
if usr_inp > rand:
print("Wrong number! The secret number is lesser than ", usr_inp)
up_range = usr_inp
elif usr_inp < rand:
print("Wrong number! The secret number is larger than ", usr_inp)
low_range = usr_inp
else:
print("Invalid Input")
else:
print("Congratulation, you got the right number")
答案 0 :(得分:2)
这是一种方法,但没有任何for循环:
import random
running = True
answer = random.randint(100, 200)
print("A secret random integer between 100 and 200 has been generated.\nCan you guess what it is?")
low = 100
high = 200
while running:
usr_inp = int(input("Make a guess between "+str(low)+" and "+str(high)+": "))
if usr_inp < low or usr_inp > high:
print("Invalid input! Please make a guess between "+str(low)+" and "+str(high)+": ")
elif usr_inp < answer:
print("Wrong number! The secret number is larger than "+str(usr_inp)+".")
low = usr_inp + 1
elif usr_inp > answer:
print("Wrong number! The secret number is less than "+str(usr_inp)+".")
high = usr_inp - 1
elif usr_inp == answer:
print("Congratulations! You got the right number.")
running = False
答案 1 :(得分:0)
您不需要遍历范围内的所有数字。
import random
upper = 200
lower = 100
num = int(random.randrange(lower,upper))
print(num)
usr_inp = int(input("Enter a number between " + str(lower) + " and "+ str(upper) + ": "))
while(usr_inp != num):
if(num > usr_inp):
lower = usr_inp
elif(num < usr_inp):
upper = usr_inp
usr_inp = int(input("Enter a number between " + str(lower) + " and "+ str(upper) + ": "))
print("Congratulation, you got the right number")