繁体   English   中英

当我写一个字符串时,如何使 integer 在“while true”循环中停止?

[英]How to make an integer in a "while true" loop stop when I write a string?

我正在尝试制作一个计算器,它要求用户输入,直到用户写一个像“stop”这样的字符串,然后用户必须写一个输入操作(+,-,等等)。 我的主要问题是如何让用户在 integer 输入中写入字符串,以及如何在刹车后进行另一个输入? 我已经设法创建了一个无限循环,如何将“i = 0”替换为“i = “stop”?如果用户写入一个字符串,它将导致错误。

i = 0
while True:
    user_input = int("Enter a number: ")
    if user_input = i:
        break

除非您出于特定原因需要他们写“停止”,否则您可以执行以下操作:

i = 0
while True:
    print ("Enter a number", end="")
    x = input()
    x = int(x)
    
    # use x as your input number in your calculator.

这样,用户按下回车键的行为就可以作为您的“停止”检查。 所以用户可以输入一个数字。 当他们按下回车键时,输入作为字符串存储在 x 中。 然后代码将其转换为 int。

要解析关键字停止,您可以执行

x = input()
x = int(x.split("stop")[0].strip())

这基本上是查找单词“stop”并从该点拆分字符串。 第 0 个索引应该包含数字(假设用户首先输入数字,然后是“停止”)。 The.strip() 删除空格。 最后,我们将此字符串(其中包含数字,没有空格)转换为 int。

由于“=”,您的代码无限期运行。 当它到达该行时,它会用 0 覆盖 user_input 的当前值,条件语句将其读取为 false,因此永远不会到达“break”语句。

首先,比较时必须使用双“==”而不是一个“=”。 您还应该在转换为 int 之前进行检查:

i = "stop"
while True:
    print("Enter a number: ")
    user_input = input()
    if user_input == i:
        break
    else:
        intInput = int(user_input) #assuming you are checking for int inputs and properly handling type errors
        # you can now use intInput 

当然,您可以删除“i”并直接检查“if user_input == "stop":" 如果您愿意

暂无
暂无

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

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