多个raw_input

1 投票
3 回答
2590 浏览
提问于 2025-04-16 12:17
#Print out the menu
print """
###############################################
# 1 - Introduction.                           #
# 2 - Base.                                   #
# 3 - Contact.                                #
###############################################"""

#Get the user's choice
choice = raw_input("")

#Work with choice
print choice
if choice == 1:
    print "# Welcome to xbrEra's first application!      #"
elif choice == 2:
    print "# This application was built in Python 7.2.1.  #"
elif choice == 3:
    print "# Contact me at Blackriver.era@hotmail.com     #"
else:
    print "# Invalid choice!                              #"

这是我的代码。我的问题是,在第一次输入完成后,接下来的输入前面会有“>>> ”这个前缀。我该怎么改这个呢?还有,我的代码总是显示“无效的选择!”请帮帮我,谢谢!

3 个回答

0

我觉得你需要这样写你的换行符:'\n' '你必须输入1、2或3。' '\n'

0
#Print out the menu

ch = """###############################################
# 1 - Introduction.                           #
# 2 - Base.                                   #
# 3 - Contact.                                #
###############################################

  Enter your choice : """

choice = raw_input(ch)
warn = "\n  You must enter 1 or 2 or 3.\n"+\
     "  Enter your choice : "
while choice not in ('1','2','3'):
    choice = raw_input(warn)

print ("# Welcome to xbrEra's first application!      #",
       "# This application was built in Python 7.2.1.  #",
       "# Contact me at Blackriver.era@hotmail.com     #")[int(choice)-1]

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

2

我在当前的代码中总是收到“无效选择!”的提示

raw_input() 在 Python 2.7 中返回的是字符串,所以你需要用字符串来比较

choice == "1"

或者你可以试试用 input() 来代替 raw_input(),这样输入会被当作数字来处理。

另外,你也可以用 int(raw_input()) 来把输入转换成整数,正如 J.F. Sebastian 提到的那样。非整数的输入可能会导致错误,所以最好用 try: except: 这种结构来包裹它,比如

try:
  choice = int(raw_input(), 10)
except ValueError:
  choice = None

补充说明:", 10" 是指十进制,输入可以是带零的,比如 010,这样会把输入当作八进制数字处理。

撰写回答