它不调用python3中的函数?

时间:2016-06-08 13:40:13

标签: python-3.x fractions

我正在使用python3制作简单的分数计算器。 我仍然可以为choice输入输入,但它不会调用任何函数;加,减,除和乘。 我错过了什么? 提前谢谢!

from fractions import Fraction
class Thefraction():

    def add(a,b):
        print('The result is %s' % (a+b))
    def subtract(a,b):
        print('The result is %s' % (a-b))
    def divide(a,b):
        print('The result is %s' % (a*b))
    def multiply(a,b):
        print('The result is %s' % (a/b))

    if __name__=='__main__':
        try:
            a = Fraction(input('Please type first fraction '))
            b = Fraction(input('Please type second fraction '))
            choice = input('Please select one of these 1. add 2. subtract 3. divide 4.multiply ')
            if choice ==1:
                add(a,b)
            if choice==2:
                subtract(a,b)
            if choice==3:
                divide(a,b)
            if choice==4:
                multiply(a,b)

        except ValueError:
            print('No fraction')

1 个答案:

答案 0 :(得分:2)

当您在输入中键入内容时,会将其另存为字符串而不是整数。因此,您可以将if语句更改为:choice =='1'或使用choice =int(choice)

示例:

choice = input('Please select one of these 1. add 2. subtract 3. divide 4.multiply ')
        if choice == '1':
            add(a,b)
        if choice== '2':
            subtract(a,b)
        if choice== '3':
            divide(a,b)
        if choice== '4':
            multiply(a,b)

或者:

choice = input('Please select one of these 1. add 2. subtract 3. divide 4.multiply ')
choice = int(choice)
            if choice ==1:
                add(a,b)
            if choice ==2:
                subtract(a,b)
            if choice ==3:
                divide(a,b)
            if choice ==4:
                multiply(a,b)