如何确保字符串不包含字母,如果包含字母,如何保持程序运行?

2024-04-25 14:15:13 发布

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

def calcwages(totalWages, totalHours):
    weeklyWages = totalWages * totalHours
    return weeklyWages

def main():
    hours = input("Enter how many hours you work")
    wage = 7.50
    total = calcwages(wage, hours)
    print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
      .format(**locals()))

main()

我想这样做,如果用户输入一个字符串4小时,程序会让用户知道这是一个不可接受的响应,而再次运行它。我尝试使用while循环,但在检查字符串中的字母时遇到了一些问题。你知道吗


Tags: 字符串用户inputreturnmaindefhowtotal
3条回答

您可以使用isdigit()进行检查,但是默认的isdigit()方法只适用于int而不适用于float,因此您可以定义自己的isdigit(),这两种方法都适用:

def isdigit(d):
    try:
        float(d)
        return True
    except ValueError:
        return False

然后你可以做:

def calcwages(totalWages, totalHours):
    weeklyWages = totalWages * totalHours
    return weeklyWages

def main():
    hours = input("Enter how many hours you work ")
    if isdigit(hours):
        hours = float(hours)
        wage = 7.50
        total = calcwages(wage, hours)

        print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'.format(**locals()))
    else:
        print("please enter numbers only")
        return main()
    return total

main()

输出:

Enter how many hours you work three
please enter numbers only
Enter how many hours you work four
please enter numbers only
Enter how many hours you work 3.4
Wages for 3.4 hours at $7.50 per hour are $25.50.

Useisdigit()-如果字符串只包含数字,则返回true,否则返回false

def calcwages(totalWages, totalHours):
    return  totalWages * totalHours
def main(): 
    hours = input("Enter how many hours you work")
    while  hours.isdigit() == False : 
        hours = input("Enter digits only")
    wage = 7.50 
    total = calcwages(wage, hours)
    print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.' .format(**locals()))
main()

Python提供isdigit()函数来检查给定的字符串是否只有数字。 你可以这样使用它。你知道吗

def main():
    while True:
        hours = input("Enter how many hours you work: ")
        if hours.isdigit():
            break
        print('Please only use numbers.')
    # ...

请注意,十进制数不适用于此方法。你知道吗

相关问题 更多 >