calling a function and argument in an 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: calling a function and argument in an input (/thread-30512.html) |
calling a function and argument in an input - phillup7 - Oct-24-2020 hi I was wondering if anyone could help me with this for a personal prject I am working on what I want to do is to call a function and an argument in a single input. could you help I cant find anything online it would look something like this: input: >rotate(6) output: >you rotated 6° to the right RE: calling a function and argument in an input - DPaul - Oct-24-2020 Your description is very limited, but i assume you mean this: somewhere in your app you have: Quote:def rotate(angle):rotate is a function and angle the argument. Elsewhere you have an input() statement for the user, and you want him/her to be able to type ">rotate(6)". The simplest way would be to have two inputs: a = input("What angle do you need ? ") -> convert that to int() c = input("What command should I execute? ") For the variable c you will have to construct some logic that says: if it's "r" do rotate, if its "x" do something else. My 2 cts, Paul RE: calling a function and argument in an input - DPaul - Oct-25-2020 Some extra thoughts on this: If you are considering to use the split() function, you might be better off reformatting the input string to "rotate,5" It's less work, and you will need some extra logic, assuming that there are more commands than just rotate. There is however another possibility, that does what you want, but it will probably require some rethinking of the function. Consider this: def add(x): print(x + x) z = input('??? ') eval(z)So, if you input 'add(10) ', it will print "20". This is a potentially dangerous thing, as you allow the user to execute all kinds of commands that may not be desirable Paul RE: calling a function and argument in an input - jefsummers - Oct-25-2020 The extremely dangerous way to do it is the exec() function. You are opening up your machine to the user, but here's an example cmd = input('What do you want to do?') print(f'You want to {cmd}') exec(cmd)
|