Vibha
Vibha

Reputation: 94

Variables in print statement

I'm trying to print the variable and their value both in the below code

New_veh = "C:\new_buy\Jan"
Used_veh = "C:\usedBuy\Jan"
if(Type=='N'):
    Model = New_veh
elif(Type=='U'):
    Model = Used_veh

....

print(Model, "Analysis File is used for Model building :", Model)

Output :

C:\new_buy\Jan Analysis File is used for Model building :C:\new_buy\Jan

In the above code Model variable resolved to the path variable New_veh or Used_veh based on the condition at both places in print statement.

Is there any way it will resolve at one place only. I'm trying to achieve results like this

New_veh Analysis File is used for Model building :C:\new_buy\Jan

Here it resolved to path at end but in start it print as it is.

Any help on this ?

Upvotes: 0

Views: 102

Answers (3)

buran
buran

Reputation: 14233

Use a data structure like dict

models = {'N':('New_veh', r"C:\new_buy\Jan"), 'U':('Used_veh', r'C:\usedBuy\Jan')}
name, model = models[model_type] # model_type=='N' or model_type='U'
print(f'{name}, Analysis File is used for Model building : {model}')

Also check Ned Batchelder's Keep data out of your variable names

If you like you can go fancy with namedtuple.

Upvotes: 3

Miguel Méndez
Miguel Méndez

Reputation: 1

I am not if this will help you, but based on your expected results this can help you:

Type = 'N'
New_veh = 'C:\\new_buy\\Jan'
Used_veh = 'C:\\usedBuy\\Jan'
Model = None
if Type == 'N':
    Model = {
        'model': New_veh,
        'variable': f'{New_veh=}'.split('=')[0]
    }
elif Type == 'U':
    Model = {
        'model': Used_veh,
        'variable': f'{Used_veh=}'.split('=')[0]
    }

print(Model.get('variable'), "Analysis File is used for Model building :", Model.get('model'))

This is for version 3.9

Upvotes: 0

bruno
bruno

Reputation: 32586

Warning use == rather than = to compare

in Python before 3 :

First way :

New_veh = "C:\new_buy\Jan"
Used_veh = "C:\usedBuy\Jan"
Model = None
V=None

if(Type=='N'):
    Model = New_veh
    V = "New_veh"
elif(Type=='U'):
    Model = Used_veh
    V = "Used_veh"

print(V, "Analysis File is used for Model building :", Model)

Second way :

New_veh = "C:\new_buy\Jan"
Used_veh = "C:\usedBuy\Jan"
Model = None

if(Type=='N'):
    Model = "New_veh"
elif(Type=='U'):
    Model = "Used_veh"

print(Model, "Analysis File is used for Model building :", eval(Model))

In python 3 (\\ rather than \)

First way

New_veh = "C:\\new_buy\\Jan"
Used_veh = "C:\\usedBuy\\Jan"
Model = None
V=None

if(Type=='N'):
    Model = New_veh
    V = "New_veh"
elif(Type=='U'):
    Model = Used_veh
    V = "Used_veh"

print(V, "Analysis File is used for Model building :", Model)

Second way :

New_veh = "C:\\new_buy\\Jan"
Used_veh = "C:\\usedBuy\\Jan"
Model = None

if(Type=='N'):
    Model = "New_veh"
elif(Type=='U'):
    Model = "Used_veh"

print(Model, "Analysis File is used for Model building :", eval(Model))

Upvotes: 1

Related Questions