.get not working in Python - python

import os
name = input("Please enter your username ") or "name"
server = input("Please enter a name you wish to call this server ") or "server"
prompt = name + "#" + server
def error(choice):
print(choice + ": command not found")
commands()
def clear():
os.system("cls")
commands()
def commands():
while 1 > 0:
choice = input(prompt)
{'clear': clear}.get(choice, error(choice))()
commands()
When running this code, no matter what I enter the dictionaries .get function always returns an error. When I enter 'clear' the script should go to that function. Does anyone have an idea why this does not work correctly? Thanks.

You'll always see the error, because all arguments to a function must be evaluated before the function is called. So error(choice) will be called to get its result before it is passed as the default value to get().
Instead, leave out the default, and check it explicitly:
result = {'clear': clear}.get(choice)
if result:
result()
else:
error(choice)

You don't want to actually call error(choice).
You can partially apply parameters to a function but leave it to be called later:
>>> def error(choice):
... print(choice + ': command not found')
>>> from functools import partial
>>> func = partial(error, choice='asdf')
>>> func()
asdf: command not found
So you want:
{'clear': clear}.get(choice, partial(error, choice))()

Related

call a 'def' with an 'input' in Python

I'm working on a project, and I got a bit stuck. I want the user the of the program to be able to call a function. But it must be easy for the user to call it. For example
def definition():
print("This is a function")
command = input("> ")
if command == definition:
definition()
else:
print("")
in this function I want the user not to write the () in the input. But I want the user just to be able to write 'definition' to call the function. Does anyone have any clue how to do this?
You are missing the quotes from around definition, therefore trying to compare an undeclared variable with an inputted string which will always equate to false.
Try:
def definition():
print("This is a function")
command = input("> ")
if command == 'definition':
definition()
else:
print("")
You are mixing up the function name (callable object in you code) and the name from your input.
For your problem I would use a dictionary of function names for the keys and function references for the value
def function1():
print ('calling function1')
def function2():
print ('calling function2')
def function3():
print ('calling function3')
functions = {}
functions['function1'] = function1
functions['function2'] = function2
functions['function3'] = function3
name = input('Enter the function name:\n')
if name in functions:
functions[name]()
else:
print ('Invalid function name. Use one of: ')
for key in functions.keys():
print (' - ' + key)
Just one command "definition"
def definition():
print("This is a function")
command = input("> ")
if command == "definition":
definition()
else:
print("Wrong command !")
More commands and functions
def definition():
print("This is definition function")
def modify():
print("This is modify function")
func = {"definition":definition, "modify":modify}
command = input("> ").strip().lower()
if command in func:
func[command]()
else:
print("Wrong command !")
You will have to implicitly define the conditions with if statement..
For ease of user you can do like this:
def definition():
#your function here
if __name__=='__main__':
print ("Choose your option:\n1. Definition")
choice = int(input("Enter choice: "))
if choice == 1:
definition ()
Try this
whitelist_funcs = ['definition', 'something else']
command = input("> ")
if command in whitelist_funcs:
exec(f"{command}()")
else:
print("")

How to fix my program so that it returns my actual defined function when called, instead of <function name at 0x3424243>?

Why does my program return "function name at 0x3424243" whenever I call my defined function?
To let you know that 3424243 isn't the actual number, but either way it shows a very random number, whenever I call my defined function.
My code:
print("WELCOME!")
name = input("\nWhat is your name? ")
print("\nHello " + name + "!")
def name():
print(name)
print("\nGoodbye", name)
How can I fix this so that it says goodbye to the name I typed in. The code above generates "Goodbye, function name at 0x3424243>"
Don't use the same name for the input variable and the function.
First:
name = input("\nWhat is your name? ")
Will run and name will point to the input string.
When:
def name():
Is evaluated name will start pointing to the function instead of the input string.
Modify your code like this:
print("WELCOME!")
name = input("\nWhat is your name? ")
print("\nHello " + name + "!")
def fn(): # Changed the name of the function to avoid the clash.
return name # Return the name.
print("\nGoodbye", fn())
Output:
WELCOME!
What is your name?
Hello Dipen!
Goodbye Dipen
After reading your comments to Dipens's answer, I think what you are looking for is something like this:
print("\nGoodbye %s" % fn())
But in that case you don't want fn to actually print anything, only to return a string. In your original example the code would execute along the lines of the following:
print("text", print("name"))
... which would result in the same/similar behavior as you're experiencing.

Program won't run

I have this exercise and the first part of the program was running fine but I must've done something because now when I try to run it will just show None and and nothing seems to be 'wrong'. I don't know enough to even figure out what's wrong.
def main():
"""Gets the job done"""
#this program returns the value according to the colour
def re_start():
#do the work
return read_colour
def read_names():
"""prompt user for their name and returns in a space-separaded line"""
PROMPT_NAMES = input("Enter names: ")
users_names = '{}'.format(PROMPT_NAMES)
print (users_names)
return users_names
def read_colour():
"""prompt user for a colour letter if invalid colour enter retry"""
ALLOWED_COLOURS = ["whero",
"kowhai",
"kikorangi",
"parauri",
"kiwikiwi",
"karaka",
"waiporoporo",
"pango"]
PROMPT_COLOUR = input("Enter letter colour: ").casefold()
if PROMPT_COLOUR in ALLOWED_COLOURS:
return read_names()
else:
print("Invalid colour...")
print(*ALLOWED_COLOURS,sep='\n')
re_start()
main()
The only function you call is main(), but that has no statements in it, so your code will do nothing. To fix this, put some statements in your main() and rerun your code.

Continuous results from a single function call

I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...

Python Application does nothing

This code stopped doing anything at all after I changed something that I no longer remember
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv()
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
edit: Lol sorry guys forgot to say its supposed to run the input
You should better describe your problem. Does it print the input prompt? Does it output anything? Does it exit or just sit there? I noticed a few issues while reading over this code that might help. You should be using raw_input(), not input(). Also, you don't actually do anything with userinput unless it == 'exit'. Which is won't, because you are just using input(), not raw_input(), so the person would have to enter 'exit' (including quotes) or else the loop will never exit. (Assuming it's not Python 3 Code)
It's doing nothing because there's no code to make it do anything. Try inserting a line like
print("You entered:", userinput)
at an appropriate place in your loop.
os.getenv() must have at least one param. Try os.getenv("HOST") or something.

Categories

Resources