即使在用户输入之后,If语句也不运行

2024-09-30 16:24:45 发布

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

optionone = 0    #DEFINING BOTH VARIABLES 
optiontwo = 0

class first_day_morning:    #WORKING 
    optionone = input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")


def first_choice(optionone):        #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
     if optionone == 1: 
         time.sleep(1)
        print('')
        print("You have chosen to get out of the house for once")
    elif optionone == 2: 
        time.sleep(1)
        print('')
        print("DO LATER")
    else: 
        time.sleep(1)
        print('')
        print("please choose a valid option")

first_choice(int(input()))

我试图让用户输入决定if语句的结果,如果用户输入1,则会发生一些事情,如果用户输入2,则会发生其他事情,如果用户输入任何其他内容,则if语句会再次运行,因为只有1或2是有效输入。然而,问题是无论用户输入什么,if语句都不会运行,也不会显示错误。我尝试了try/Exception,以防由于某种原因没有显示错误(try Exception ValueError:),但似乎没有任何效果。我还尝试将输入指定为str、int、float、no specification、raw_input等。但没有任何效果,有人能帮我吗

另外,我正在使用Visual Studio代码

As you can see, the if statement does not run as no error is shown even after user input.


Tags: to用户youinputiftimeissleep
3条回答

当程序运行时,将计算类主体,这意味着input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")将提示输入。然后,该值将保留在first_day_morning.optionone中,但是first_choiceoptionone是不同的。它等于最后一行int(input())上提供的参数,该参数将自动提示输入另一个输入,然后将其转换为整数。根据我认为您试图实现的目标,我建议您删除该类并将最后一行更改为:

first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
def first_choice():
    print('')
    print("You have chosen to get out of the house for once")

def second_choice():
    print('')
    print("DO LATER")

def third_choice():
    print('')
    print("please choose a valid option")


while True:

    print("""Select a choice""")

    c = int(input('enter your choice:'))
    if c == 1:
        first_choice()
    elif c == 2:
        second_choice()
    elif c == 3:
        third_choice()
    elif c == 4:
        break

我真的不明白你想在这里完成什么,但代码对我来说很有用,一些来自初学者的提示: -您定义了optiontwo,但从未使用过它 -你在类中用输入填充optionone,不知道为什么,因为从未使用过 不确定您想要什么,但请尝试以下方法:

import time

def first_choice(optionone):        #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
    if optionone == 1: 
        time.sleep(1)
        print('')
        print("You have chosen to get out of the house for once")
    elif optionone == 2: 
        time.sleep(1)
        print('')
        print("DO LATER")
    else: 
        time.sleep(1)
        print('')
        print("please choose a valid option")

first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))

虽然,在控制台中测试它,但不确定vscode是否正确,但在sublime中运行不会要求输入

相关问题 更多 >