【问题标题】:Run the while-loop again with the same variable and start the script again without closing it?使用相同的变量再次运行while循环并再次启动脚本而不关闭它?
【发布时间】:2021-01-10 04:14:43
【问题描述】:
import random

x = random.randint(0,20)
y = int(input("guess the number from 0 to 20: \n"))

while True:
    if y == x:
        print("well done")
        print(x)
        stoper=input()
        break
    elif y < x:
        print("too low")
        stoper=input()
        break
    elif y > x:
        print("too high")
        stoper=input()
        break
    else:
        stoper=input()
        break 

就是代码。这个脚本从 0 到 20 取一个随机数,让用户猜测它。如果猜测大于/小于数字,程序会打印信息和数字。如何在不改变号码x的情况下再次猜出号码?

如果有人想知道stoper 输入变量是不是这样,scripr 在运行代码后不会立即关闭。至于再次运行而不关闭它,问题是指脚本再次使用新的x和新的猜测而不关闭脚本。

【问题讨论】:

  • 将带有input 的行放入while 循环和break 仅当x==y 时。

标签: python loops variables


【解决方案1】:
from random import randint
x = randint(0,20)
y = int(input("guess the number from 0 to 20: \n"))

while True:
  if y == x:
      for i in range(100): #mimics resetting the screen
          print("")
      print("well done. Try again!")
  elif y < x:
      print("too low")
  elif y > x:
      print("too high")
  y = int(input("guess the number from 0 to 20: \n"))

      

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 2014-06-06
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2016-09-29
    • 2020-10-04
    • 2015-08-18
    • 2019-06-06
    相关资源
    最近更新 更多