Home > Mobile >  how i can fix this problem in python code
how i can fix this problem in python code

Time:01-06

I'm new programmer and I am begginer, this my first time use stack overflow, I trying now to calcul a calculator calcul numbers like normal calculator, I want write something such as (" 7 - 2 * 3") and the code give the result. The code is chaos im just begginer so please just try understand that and help me.

when you try the code input numbers and operators with space like this 5 5. This the code :

from functools import reduce

question = input("Enter your calcul : ")

nums = question.split()

numbers = nums[0::2]

def calcul(num1, num2):
    
    for x in variation:
        
        if x == ' ':
            return num1   num2
        elif x == '-':
            return num1 - num2
        elif x == '*':
            return num1 * num2
        elif x == '/':
            return num1 / num2
    

def wayy(lt):
    for x in lt:
        if ' ' == x :
            yield' '
        if '-' == x :
            yield'-'
        if '*' == x :
            yield'*'
        if '/' == x :
            yield'/'

variations = [] # [   , - , * , / ]
variation = wayy(nums)
for x in variation:
    variations.append(x)

print(variations)

nm = []
for n in numbers:
    n = int(n)
    nm.append(n)

calcule = reduce(calcul, nm)
print(calcule)

I try coding a calculator and i have a problem i think it is in calcul function when i input the numbers the result is "None" I know the problem in function (calcul) but I dont know how I can fix it.

CodePudding user response:

Only change "variation" to "variations" in the "calcul" function.

def calcul(num1, num2):

    for x in variations:
        if x == ' ':
            return num1   num2
        elif x == '-':
            return num1 - num2
        elif x == '*':
            return num1 * num2
        elif x == '/':
            return num1 / num2

Since "variation" is a "Generator" object, but "variations" is a list of Strings (what you need).

  • Related