[Python] How to write a cell from an if statement in Python in Excel?

Discussão em 'Python' iniciado por Stack, Janeiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm learning Python (using MU) and trying to implement it in Excel (with Python in Excel), however I have found some difficulties which I can't understand:

    Cell values are (just an example):

    C1= 1

    C2= 3

    D1:

    i1=xl("C1") #gives value 1


    D2:

    i2=xl("C2") #gives value 3


    F1:

    i3=0 #i3 is defined, just to see what is happening


    F2:

    i4=0 #same as above


    F6:

    if i1<i2:
    i3=i1+i2
    else:
    i3=i1*i2 #comparing values there is no output


    F9:

    i3 #outputs the value and seems to work well


    What I can't understand is why is in this case value of F6 cell none (Python editor says "No output"), even if I adjust the code to:

    if i1<i2:
    i1+i2
    else:
    i1*i2


    If i write

    i1+i2


    in a random python activated cell, it gives off value as expected, but inside the if statement, it doesn't work.

    What seems to work is adding if statement into function:

    def foo(x1, x2):
    if x1<x2:
    return x1+x2
    elif x1>x2:
    return x1*x2
    else:
    return x1

    foo(i1, i2)


    in that case function returns to a cell and cell has a value as expected.

    If there is no way to achieve cell value directly from if statement, I assume using a function is a way to go.

    Continue reading...

Compartilhe esta Página