无法在原始输入后输入if语句

2024-04-26 10:14:49 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我在我的项目的while循环中调用一个函数时,它将根据刚刚被调用的函数完全不做任何事情,并且将继续刷新循环,就像什么都没有发生一样。你知道吗

下面是我写的一个简单的例子来演示这个问题。通过运行代码,您将看到一个菜单,您需要从菜单中输入一个选项。执行此操作时,一些“if”语句将检查您选择了哪个选项,并调用和执行它们下面的代码如果该选项不属于任何语句,菜单将刷新:

#!/usr/bin/env python

import os
import time

def test():
    x = True
    while True:
        if not x:
            print "You need to type 1\n"
        choice = raw_input("type 1 here: ")
        if choice == 1:
            print 'Works!\n'
            time.sleep(5)
            break
        else:
            x = False

def test2():
    print "Test123\n"

try:
    while True:
        os.system("clear")

        menu_choice = raw_input("Enter Choice: ")

        if menu_choice == 1:
            test()

        if menu_choice == 2:
            test2()

        if menu_choice == 3:
            os.system("python")

except:
    pass

Tags: 函数代码importtrueiftimeosdef
1条回答
网友
1楼 · 发布于 2024-04-26 10:14:49

如注释中所述,raw_input返回一个字符串,您需要强制转换它。但是,您可能需要为键入的任何内容捕获ValueError,而不是数字。你知道吗

相反,你可以这样做

 if choice == '1'

menu_choice相同

相关问题 更多 >