Search code examples
pythoncalculator

why my 'else' function work when there is 'if' function that performing?


if i use '/' than its ok, but if i use any other option, than 'else' function is working but shouldnt

I tried to replace this 'else' somewhere, but this didnt work

print('шо ти, голова?')

what = input('пиши шо хоч (+, -, *, /) : ')

if what == '+':
    a = input('до якого числа будем додавати?: ')
    b = input('яке число будем додавати?: ')
    c = float(a) + float(b)
    print(float(c))

if what == '-':
    a = input('від якого числа будем віднімати?: ')
    b = input('яке число будем віднімати?: ')
    c = float(a) - float(b)
    print(float(c))

if what == '*':
    a = input('яке число будем множити?: ')
    b = input('на яке число будем множити?: ')
    c = float(a) * float(b)
    print(float(c))

if what == '/':
    a = input('яке число будем ділити?: ')
    b = input('на яке число будем ділити?: ')
    c = float(a) / float(b)
    print(float(c))

else: print("ти шото не то вибрав, друже!")




Solution

  • The issue your facing is because the else keyword is only related to the last if-statement in your code, which happens to be this: if what == '/':

    To fix this issue, you have to use the elif keyword, which is the python equivalent for else if.

    Here is the corrected code:

    print('шо ти, голова?')
    
    what = input('пиши шо хоч (+, -, *, /) : ')
    
    if what == '+':
        a = input('до якого числа будем додавати?: ')
        b = input('яке число будем додавати?: ')
        c = float(a) + float(b)
        print(float(c))
    
    elif what == '-':
        a = input('від якого числа будем віднімати?: ')
        b = input('яке число будем віднімати?: ')
        c = float(a) - float(b)
        print(float(c))
    
    elif what == '*':
        a = input('яке число будем множити?: ')
        b = input('на яке число будем множити?: ')
        c = float(a) * float(b)
        print(float(c))
    
    elif what == '/':
        a = input('яке число будем ділити?: ')
        b = input('на яке число будем ділити?: ')
        c = float(a) / float(b)
        print(float(c))
    
    else:
        print("ти шото не то вибрав, друже!")