Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining variable in if [duplicate]

I am trying to call a function in an if, save the value in a variable and check if the value is equal to something. Have tried:

def funk():
    return ("Some text")

msg=""
if (msg=funk()) == "Some resut":
  print ("Result 1")

I am getting a syntax error. Can this be done?

I'm coming from C and I know that this can work:

#include <stdio.h>

char funk()
{
    return 'a';
}
int main()
{
    char a;
    if( a=funk() == 'a' )
        printf("Hello, World!\n");
    return 0;
}

Is this possible in python?

P.S. The functions are simple so it is easier to understand what I want. I will not use the some functions in my program. If you give me a MINUS please explain in comment so I can make better questions in the future

like image 655
kemis Avatar asked Nov 29 '16 01:11

kemis


People also ask

Can you have duplicate variable names in a project?

It is legal for 2 variables in different scope to have same name.

Can you have duplicate variable names in a project why or how?

Assign Common, Useful Names Each variable name must be unique—even if the variables are different types, their names cannot be identical.

Is it legal to define local variable with the same identifier in nested blocks?

The local variable declaration space of a block includes any nested blocks. Thus, within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block.


1 Answers

Python purposely doesn't support it because it hurts readability. It needs to be two lines.

msg = funk()
if msg == "Some result":
    print("Result 1")
like image 64
John Kugelman Avatar answered Oct 04 '22 23:10

John Kugelman