Python如何定义一个只接受可用于多行的整数输入的函数

时间:2017-03-29 12:19:09

标签: function python-3.x

我正在尝试将具有用户输入数字的程序编写成多个不同的代码行,并且我试图使其成为如果用户输入除数字之外的其他内容,程序将再次要求用户输入数字正确。我试图定义一个我可以用于所有这些功能的功能,但每次运行程序时,它都会崩溃。非常感谢任何帮助,谢谢。

我的代码:

def error():
    global m1
    global m2
    global w1
    global w2
    while True:
        try:
            int(m1 or m2 or w1 or w2)
        except ValueError:
            try:
                float(m1 or m2 or w1 or w2)
            except ValueError:
                m1 or m2 or w1 or w2=input("please input your response correctly...")
                break

m1=input("\nWhat was your first marking period percentage?")
error()
w1=input("\nWhat is the weighting of the first marking period? (in decimal)")
error()
m2=input("\nWhat was your second marking period percentage?")
error()
w2=input("\nWhat is the weighting of the second marking period? (in decimal)")
error()

3 个答案:

答案 0 :(得分:0)

def user_input(msg):
    inp = input(msg)
    try:
        return int(inp) if inp.isnumeric() else float(inp)
    except ValueError as e:
        return user_input("Please enter a numeric value")


m1=user_input("\nWhat was your first marking period percentage?")
w1=user_input("\nWhat is the weighting of the first marking period? (in decimal)")
m2=user_input("\nWhat was your second marking period percentage?")
w2=user_input("\nWhat is the weighting of the second marking period? (in decimal)")

答案 1 :(得分:0)

您应该编写函数以一次获取一个数字。如果异常在某处被触发,则应该进行处理。请注意下面显示的get_number函数将如何继续询问数字,但也会显示其调用者指定的提示。如果您没有运行Python 3.6或更高版本,则需要在print函数中注释掉对main的调用。

#! /usr/bin/env python3
def main():
    p1 = get_number('What is your 1st marking period percentage? ')
    w1 = get_number('What is the weighting of the 1st marking period? ')
    p2 = get_number('What is your 2nd marking period percentage? ')
    w2 = get_number('What is the weighting of the 2nd marking period? ')
    score = calculate_score((p1, p2), (w1, w2))
    print(f'Your score is {score:.2f}%.')


def get_number(prompt):
    while True:
        try:
            text = input(prompt)
        except EOFError:
            raise SystemExit()
        else:
            try:
                number = float(text)
            except ValueError:
                print('Please enter a number.')
            else:
                break
    return number


def calculate_score(percentages, weights):
    if len(percentages) != len(weights):
        raise ValueError('percentages and weights must have same length')
    return sum(p * w for p, w in zip(percentages, weights)) / sum(weights)


if __name__ == '__main__':
    main()

答案 2 :(得分:0)

通过以下代码,您可以制作仅接受整数值的函数:

 def input_type(a):
      if(type(10)==type(a)):
        print("integer")
      else:
        print("not integer")
 a=int(input())
 input_type(a)