【问题标题】:Using isaplha() and while loop with if condition在 if 条件下使用 isaplha() 和 while 循环
【发布时间】:2020-05-05 00:02:45
【问题描述】:

我还在学习 python 编程。我正在尝试执行的程序将获取用户的姓名和年龄。使用 while 循环,如果用户没有输入年龄的数值,我需要让用户再次输入。但是,它没有给出我想要的输出。我尝试使用 isalpha() 但是,我认为我做错了。

例如,如果我输入一个名字“John”和年龄“d”,它会让用户再次输入。但是,如果我输入姓名“John”和年龄“6”,程序将循环并再次询问姓名和年龄,即使年龄是数字。

这是我的代码 sn-p。

def getName():
b = input("Enter your name: ")
c = input("Enter your age: ")
return b, c

def dispName():
x, y = getName()
while y.isalpha() == True:
    getName()
    if y.isalpha() == False:
        print("Your name is: ")
        print("Your age is ")
        break

dispName()

如何正确使用 while 循环来实现我想要的输出?

【问题讨论】:

  • 请注意,y.isalpha() == False 并不意味着 y 是一个数字。它可以是-!"Hello World" 或任何其他出现任何非字母字符的字符串。您可能需要检查 y.isdigit()try: 以将其转换为整数。

标签: python-3.x


【解决方案1】:
def getName():
    b = input("Enter your name: ")
    c = input("Enter your age: ")
    return b, c

def dispName():
    while(True):
        x,y = getName()
        if not y.isalpha():
            break
    print("Your name is: "+x)
    print("Your age is "+y)

dispName()

【讨论】:

    猜你喜欢
    • 2013-04-20
    • 2019-10-01
    • 1970-01-01
    • 2019-11-07
    • 2019-05-27
    • 2014-06-26
    • 1970-01-01
    • 2019-12-06
    • 2021-03-23
    相关资源
    最近更新 更多