Python Forum
executing a line depending on the input
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
executing a line depending on the input
#1
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
Reply
#2
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')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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
Reply
#4
Did you see my addition to previous post? I will look again at your code shortly
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Receive Input on Same Line? johnywhy 8 703 Jan-16-2024, 03:45 AM
Last Post: johnywhy
  Add a row per group and depending of values Menthix 0 505 Mar-20-2023, 11:20 AM
Last Post: Menthix
  How to input & output parameters from command line argument shantanu97 1 2,552 Apr-13-2021, 02:12 PM
Last Post: Larz60+
  How to make input come after input if certain line inserted and if not runs OtherCode Adrian_L 6 3,323 Apr-04-2021, 06:10 PM
Last Post: Adrian_L
  Multi-line console input lizze 4 2,346 Dec-26-2020, 08:10 AM
Last Post: lizze
  bad input line 3 how t fix it youssef210 2 2,689 Aug-27-2020, 04:57 PM
Last Post: nilamo
  Line charts error "'isnan' not supported for the input types," issac_n 1 2,397 Jul-22-2020, 04:34 PM
Last Post: issac_n
  Taking Multiple Command Line Argument Input bwdu 6 4,019 Mar-29-2020, 05:52 PM
Last Post: buran
  How to make input goto a different line mxl671 2 2,450 Feb-04-2020, 07:12 PM
Last Post: Marbelous
  command line input (arg parse) and data exchange Simba 7 4,321 Dec-06-2019, 11:58 PM
Last Post: Simba

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020