Home > Net >  How do I get a variable inside of an "if" statement to be a global variable?
How do I get a variable inside of an "if" statement to be a global variable?

Time:05-12

I'm new to Python, and I need to get the new DataFrame with the appended values (df_ap) after the condition is met, is this possible or should I try a completely new approach.

This is my current code:

df = pd.DataFrame(columns=["C1", "C2", "C3"])
Var1 = input("Input ")

if Var1 == 1:
 df_ap = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)

print(df)
print(df_ap)

Output:

Input 1
Empty DataFrame
Columns: [C1, C2, C3]
Index: []
NameError: name 'df_ap' is not defined

CodePudding user response:

Var_1 is a string not an integer so you have to cast as int or compare it with a string:

Var1 = int(input("Input "))

if Var1 == 1:

Or:

Var1 = input("Input ")

if Var1 == "1":

CodePudding user response:

Try creating the definition outside the if.

df = pd.DataFrame(columns=["C1", "C2", "C3"])
Var1 = input("Input ")

df_ap = None

if Var1 == 1:
    df_ap = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)

print(df)
print(df_ap)

CodePudding user response:

First, in order to make your condition working, you need to make sure your input has been converted into int before the if condition. Since you using df_ap outside of the if condition, you have to define it outside the if as well, which is before the condition execution.

import pandas as pd

df = pd.DataFrame(columns=["C1", "C2", "C3"])
df_ap = pd.DataFrame()

Var1 = int(input("Input "))

if Var1 == 1:
 df_ap = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)

print(df)
print(df_ap)

Another way, you can simply reuse df, since it has been defined outside if condition:

import pandas as pd

df = pd.DataFrame(columns=["C1", "C2", "C3"])

Var1 = int(input("Input "))

if Var1 == 1:
 df = df.append({"C1": 100, "C2": 200, "C3":300}, ignore_index=True)

print(df)
  • Related