为什么Python在第一次输入后不打印我的其他输入?
我刚开始学习Python,想写一个程序,可以把用户输入的内容变成大写或小写。
不过,我遇到了一个问题,就是Python能打印出用户输入的第一部分内容,但后面的两部分却打印不出来。我在想,这是不是因为我的缩进写得不对?我是在Google Colab上写的代码,如果你感兴趣的话,可以去那儿试试。
我还希望代码能在用户输入“q”时停止执行,但我不太确定我这样做是否正确。
我尝试调整缩进和重新排列我的代码,但可惜没有效果。这是我的代码:
# user enters inputs
# block 1
input1 = input("Enter a sentence (or use q to quit): ")
if input1 == "q":
print("The user has aborted the program.")
else:
input2 = input("Uppercase or Lowercase? (U/L): ")
# display inputs and either does uppercase or lowercase depending on user input
if (input2 == "U"):
print("The Uppercase of" + " " + input1 + " " + "is" + " " + input1.upper() + ".")
elif (input2 == "L"):
print("The Lowercase of" + " " + input1 + " " + "is" + " " + input1.lower() + ".")
# user enters inputs
# block 2
input3 = input("Enter a sentence (or use q to quit): ")
if (input3 == "q"):
print("The user has aborted the program.")
else:
input4 = input("Uppercase or Lowercase? (U/L): ")
# display inputs and either does uppercase or lowercase depending on user input
if (input4 == "U"):
print("The Uppercase of" + " " + input3 + " " + "is" + " " + input3.upper() + ".")
elif (input4 == "L"):
print("The Lowercase of" + " " + input3 + " " + "is" + " " + input3.lower() + ".")
# user enters inputs
# block 3
input5 = input("Enter a sentence (or use q to quit): ")
if input5 == "q":
print("The user has aborted the program.")
else:
input6 = input("Uppercase or Lowercase? (U/L): ")
# display inputs and either does uppercase or lowercase depending on user input
if (input6 == "U"):
print("The Uppercase of" + " " + input5 + " " + "is" + " " + input5.upper() + ".")
elif (input6 == "L"):
print("The Lowercase of" + " " + input5 + " " + "is" + " " + input5.lower() + ".")
2 个回答
-2
你说的对,缩进确实很重要。确保每个代码块的缩进是一致的。
我不是Python开发者,但我知道在Python中,缩进在定义代码块时很关键。
我在一个网页编译器上测试了你的代码,结果和你想的一样,有三个提示。关于退出的条件,可以试试使用quit()函数来退出你的提示,至于你的“if”条件是没问题的。
看到初学者们在编程中探索真是太好了。继续加油!
-1
你的错误在于,Python 非常重视 空格,所以下面这两个代码块不能有空格,否则它们会被当作第一个代码块的 else 语句来执行。
你只需要把 block2 和 block3 的所有代码缩进,快捷键是 "Shift+Tab"。