I am wondering if there is an alternative, more elegant, syntax for code to achieve the same result as the below code (which works):
import pandas as pd
path = 'C:/Users/Path/'
name1 = 'David'
name2 = 'Thomas'
switch = 'On'
if switch == 'On':
df = pd.read_csv(path + name1 + '.csv')
elif switch == 'Off':
df = pd.read_csv(path + name2 + '.csv')
The kind of thing I am thinking about is this (but this results in a syntax error):
import pandas as pd
path = 'C:/Users/Path/'
name1 = 'David'
name2 = 'Thomas'
switch = 'On'
df = pd.read_csv(path + (if switch == 'On':
name1
elif switch == 'Off':
name2) + '.csv')
The goal is to avoid having to write out multiple lines of very similar code as per the first example!
I would appreciate alternatives and am interested as to why the second approach does lead to a syntax error!
Thanks!...
Aucun commentaire:
Enregistrer un commentaire