【问题标题】:How to validate inputs with 2 messages?python3如何使用 2 条消息验证输入?python3
【发布时间】:2016-08-05 01:51:45
【问题描述】:

我有工资总额的例子,但我不想接受任何字符串值。我试图用 while true 语句解决它,但用第一个代码问题执行。

我想要这些输出:

输入本周的工作时间:asd

请为整数

输入本周的工作小时数:10

输入时薪:asd

请浮点数

输入时薪:20.01

谁来帮忙

我的代码

当真时:

       try:

           hours = int(input('Enter the hours worked this week: '))

           pay_rate = float(input('Enter the hourly pay rate: '))

           gross_pay = hours * pay_rate

           print('Gross pay: $', format(gross_pay, ',.2f'))

       except ValueError:

                        print('please integer number)

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    这是我在需要验证多个用户输入并请求不同类型时通常使用的功能。

    def get_input(typ, msg, err):
        while True:
            try:
                return typ(input(msg))
            except ValueError:
                print("Please enter {0}".format(err))
    
    
    hours = get_input(int, 'Enter the hours worked this week: ', 'an intger number')
    pay_rate = get_input(float, 'Enter the hourly pay rate: ', 'a float number')
    gross_pay = hours * pay_rate
    print('Gross pay: $', format(gross_pay, ',.2f'))
    

    【讨论】:

    • 感谢 Steven ,这段代码对我有帮助,因为我是学习 python 的初学者。
    【解决方案2】:

    试试这个:

    def hoursGet():
        hours = input("Enter the hours worked this week: ")
        try:
            hours = int(hours)
            return hours
        except ValueError:
            print ("please integer number")
            hoursGet()
    

    只需为其他问题编写其他函数,替换printed 语句和数据类型。

    【讨论】:

    • 最后,只需按照您想要的顺序调用所有函数,它应该可以正常工作。
    • 感谢 Sid,何时运行您的代码。它不接受字符串值,但不再问我同一个问题刚刚移至第二个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2015-09-16
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多