Python 打印相同的 "You're eligible for applying to be a US Senator or Representative." 语句,尽管输入的年龄超出了该范围


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的声明就可以打印出来,但事实并非如此。我甚至会输入孩子的年龄,它仍然会打印出相同的语句。

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

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

所以在不定义函数的情况下编写。我不想发布";解决方案";在这里,因为我想让你自己做。

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

您必须收集年龄和公民身份时间,并将其正确传递给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()

最新更新