Python打印了同样的“你有资格申请成为美国参议员或众议员”声明,尽管输入的年龄超出了该范围

2024-09-29 05:15:19 发布

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

print ( "Welcome! We are going to determine whether you're eligible to be a US Senator or Representative" )

#User Inputs their age and length of citizenship
def userInput(age, citizenshipTime):
    age = int ( input ( "Please enter your age: " ) )
    citizenshipTime = int ( input ( "Enter how long, in years, you've been a US citizen: " ) )
    return userInput

#Eligibility for US Senator and/or Representative position
def eligibility():
    if age >= 50 and citizenshipTime >= 9:
        print( "You're eligible for applying to be a US Senator or Representative." )

    elif age >= 25 and citizenshipTime >= 7:
        print( "You're eligible for applying to be a US Representative." )
    
    else:
        print( "You are not eligibile for either, sorry!" )

#Call the main function
def main():
    user = userInput(age, citizenshipTime)
    eligibility()
    
main()

我想这样做,以便可以打印elif和else语句,但事实并非如此。 我甚至会输入孩子的年龄,但它仍然打印相同的语句


Tags: orandtoreforagedefbe
2条回答

您必须收集年龄和公民身份时间,并将其正确地传递给eligibility()函数:

print ( "Welcome! We are going to determine whether you're eligible to be a US Senator or Representative" )

#User Inputs their age and length of citizenship
def userInput():
    age = int ( input ( "Please enter your age: " ) )
    citizenshipTime = int ( input ( "Enter how long, in years, you've been a US citizen: " ) )
    return age, citizenshipTime

#Eligibility for US Senator and/or Representative position
def eligibility(age, citizenshipTime):
    if age >= 50 and citizenshipTime >= 9:
        print( "You're eligible for applying to be a US Senator or Representative." )

    elif age >= 25 and citizenshipTime >= 7:
        print( "You're eligible for applying to be a US Representative." )
    
    else:
        print( "You are not eligibile for either, sorry!" )

#Call the main function
def main():
    age, citizenshipTime = userInput()
    eligibility(age, citizenshipTime)
    
main()

您忽略了函数userInput()的作用域。 此外,您正在使用变量作为函数中定义的函数的参数。我怀疑这段代码是否会运行

除非你必须为一些项目或家庭作业定义函数,否则我会把它们扔掉,因为你不需要它们来实现像这样的极简功能。简而言之,函数只对重复性任务有用,但这里的情况并非如此

所以写这篇文章时不要定义函数。我不想在这里发布“解决方案”,因为我希望你自己去做

记住逻辑顺序(要求输入->;计算->;打印输出)

相关问题 更多 >