Python Forum
executing a line depending on the input - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: executing a line depending on the input (/thread-11598.html)



executing a line depending on the input - PierreSoulier - Jul-17-2018

Hello!

I wanted to know if it is possible to create a command on Python based on the input.

In the program I ask the user to choose a number between 1 and 871 and if he chooses the number N then i will launch the command

c_N.writerow(result)
I could do something like that:

x=input("Entrer le numéro correspondant")
if x=1:
    c_1.writerow(result)
elif x=2:
    c_2.writerow(result)
....
....
....
elif x=871:
    c_871.writerow(result)
else:
    print("You wrote the wrong number")
But it would take way to much time. I was thinking of a function that could "launch" a line depending of the string in input. Like that:

Quote:x=input("Entrer le numéro correspondant")
x="c_"+x
execute(x,".writerow(result))


Do you have any idea?

Thank you


RE: executing a line depending on the input - buran - Jul-17-2018

it looks like your design is wrong. don't create 871 different variables/commands.
use a container - list, dict...
give us more information what c_N is so we can show the correct way

something within these lines
def foo():
    print('foo')
    
def bar():
    print('bar')
    
def error():
    print('not a valid input')
    
# using dict   
commands = {'1':foo, '2':bar}
user_input = input('Select command (1 or 2): ')
commands.get(user_input, error)()

if c_N are files
my_files = ['file1.txt', 'file2.txt']
user_input = input('Select output file (1 - {}): '.format(len(my_files)))
try:
    with open(my_files[user_input-1], 'a') as f:
        f.writerow(result)
except IndexError:
    print('Incorrect input')



RE: executing a line depending on the input - PierreSoulier - Jul-17-2018

The idea is that i have a database on mysql of over 100 000 events (with description and title) and i want to sort them with keywords. I have then 871 csv files on which i put the events depending of the sort.
No problem for that part.

If there is no keyword found i display the title and the description to the user and he puts the number corresponding to csv he wants the data to be stored in.
For example: 1 is concert, 2 is orchestra etc...(not really like that but you get the idea)

so I've done something like that:

Starting by creating the csv
c_1 = csv.writer(open('CSV/Communales_départementales_nationales.csv', 'w'))
c_2 = csv.writer(open('CSV/Autoroutes.csv', 'w'))
c_3 =  csv.writer(open('CSV/Eclairage public.csv', 'w'))
c_4 =  csv.writer(open('CSV/Parkings couverts.csv', 'w'))
c_5 =  csv.writer(open('CSV/Parkings non couverts.csv', 'w'))
c_6 =  csv.writer(open('CSV/Stationnement public.csv', 'w'))
c_7 =  csv.writer(open('CSV/Habitat_Logement.csv', 'w'))
c_8 =  csv.writer(open('CSV/Transports en commun.csv', 'w'))
c_9 =  csv.writer(open('CSV/Transports ferroviaires et aériens.csv', 'w'))
c_10 =  csv.writer(open('CSV/Pistes Cyclables.csv', 'w'))
c_11 =  csv.writer(open('CSV/Aire de jeux pour enfants.csv', 'w'))
c_12 =  csv.writer(open('CSV/Crèches avec accueil régulier et occasionel.csv', 'w'))
c_13 =  csv.writer(open('CSV/Crèches parentales.csv', 'w'))
c_14 =  csv.writer(open('CSV/Micro-crèches.csv', 'w'))
c_15 =  csv.writer(open('CSV/Crèches familiales.csv', 'w'))
c_16 =  csv.writer(open('CSV/Haltes-garderies.csv', 'w'))
....
.....
......
On the following AT is a list of id for which we didn't find any match with keyword
nom is the title
details is the description
for i in AT:
    cur.execute("""SELECT nom,details FROM Tri WHERE id = %s""", i)
    result=cur.fetchall()
    print("\ntitre|description:")
    print(result)
    nombre = False
    while nombre is False:        
        x=int(input("Entrer le numéro correspondant: "))
        if x > 0 and x < 872 :
            nombre = True
        else:
            print("Veuillez rentrer un nombre adéquat")
    y="c_"+str(x)
    cur.execute("""SELECT * FROM Tri WHERE id = %s""", i)
    result=cur.fetchone()
    eval(y+".writerow(result)")          
    print("Déplacé dans le numéro",x) 
And it look like it work but is there a better way to do it?

Thank you and sorry for the English


RE: executing a line depending on the input - buran - Jul-17-2018

Did you see my addition to previous post? I will look again at your code shortly


RE: executing a line depending on the input - PierreSoulier - Jul-17-2018

Oh yes the addition seems to be a great idea, more condense!