Python while 循环在输入整数时继续.输入字符串或字符时中断



我是python的新手,并试图弄清楚如何使该程序接受字符串或字符,然后让它拼写出所述字符串/字符。不幸的是,当使用行while word != str() or chr(): word = input("Enter a string or character...")时,即使我输入了字符串/字符,我也经常被提示"输入字符串或字符"。我将如何解决这个问题,以便程序获取一个字符串并脱离 while 循环,以便它可以拼写我输入的任何内容?

word = input("What is your word? ")
while word != str() or chr():
word = input("Enter a string or character...")
for char in word:
print(char)

尝试以下操作:

word = input("What is your word? ")
while type(word) is not str():
word = input("Enter a string or character...")
for char in word:
print(char)

此外,输入将始终为字符串。

如果要检查数字输入,则应执行以下操作:

try:
int(word)
except ValueError:
# input is a string
else:
continue  # input is a number

也许这样的事情会起作用:

word = input("What is your word? ")
while word.isdigit(): # the word contains only digits
word = input("Enter a string or character...")
for char in word:
print(char)

几点注意事项:

  1. 在您的代码中,只要您的输入不为空,word != str()就会成立,因为str()是一种(非常丑陋的(初始化空字符串的方法。
  2. input()的返回类型是 str。如果你想把它当作一个整数或任何其他类型,你必须转换/解析它

最新更新