Python Callback to variable on input [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
if(input == "Karma Score"):
print("Your Karma score is {}.format(charKarma) + ".")
This may be an odd question, and I am new to python so I'm stumped.
I set myself a goal of finishing a text-based adventure game that features a 'Karma" system. It's basically a watered-down version of the Fallout series' Karma system.
I need help figuring out how to callback to a variable value when requested from the console.
A simplified version of my spaghetti code is:
if(Input == "Print Variable")
print("variable")
Thanks a bunch for your time.

Notwithstanding that it might be bad design as #juanpa.arrivillaga noted in the comments, it can be done quite easily in Python.
Python conceptually holds variables and their values in dictionaries, which you can retrieve using the built-in functions globals() or locals(). In your case globals() is probably what you want. So, you could print out the value of a variable karma like this:
print( globals()["karma"] )
Or, if I understand your intentions correctly, here is how it might look in context:
user_input = input("command$ ")
words = user_input.split()
if words[0] == "print":
var_name = words[1]
value = globals()[var_name]
print(value)
Just to be complete here: if the variable is defined in another module, either use getattr(module, var_name) or module.__dict__[var_name]. So, the following works, too:
import math
print( getattr(math, "pi") )
pritn( math.__dict__["pi"] )
The __dict__ here is basically what globals() returns for the current module.

Related

Printing key from dictionary that previous function returns [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I came across this problem. Not sure how to continue.
My dictionary:
DICT = {
"inside": "It's obviously inside",
"outside": "It went outside"
}
I have a function that returns a dictionary key. Then I have a printing function that should print the value connected to that function.
If my previous function's return line is return "inside", I tried this:
def print_location(key):
print(DICT[key])
This seems not to be working. Somehow I might need to connect the variable 'key' to the returned key but this is where I get stuck. How could I do this?
Your code seems fine; the following works as expected:
DICT = {
"inside": "It's obviously inside",
"outside": "It went outside"
}
def get_key():
return 'inside'
def print_location(key):
print(DICT[key])
# run the code
the_key = get_key()
print_location(the_key) # prints "It's obviously inside"

Python type convertion based on string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How can I write this code so it works for every type given?
def set_val_type(val, val_type):
if val_type == 'bool':
return bool(val)
elif val_type == 'int':
return int(val)
You can do something like:
def set_val_type(val, val_type):
return eval(val_type + '({})'.format(val))
As much as this seems to be what you are looking for, using eval is not recommended. It seems like an XY problem as commented before by #pault
You can create a dictionary of all the types you need to process.
def set_val_type(val, val_type):
funcs = {'int': int, 'bool': bool}
return funcs[val_type](val)
To avoid using eval, and presuming you are only using builtin types, you can use a getattr() on the builtins module (if you want to make sure you don't call any functions, you can perform an isinstance(user_provided_type_here, type) before.
To allow any type in global scope, use globals()[user_provided_type_name]
Complete example:
import builtins
def set_val_type(val, val_type);
user_type = getattr(builtins, val_type) # possibly replace with globals()[val_type]
if not isinstance(user_type, type):
raise TypeError(f'{user_type} is no a type.')
return user_type(val)
Why not to use eval() (with untrusted user input):
def set_val_type(val, val_type):
return eval(val_type + '({})'.format(val))
evil_val_type = 'bool'
evil_val = 'exec("import os\\nos.chdir(os.path.sep)\\nprint(os.getcwd())")'
print(set_val_type(evil_val, evil_val_name))
'False' # yes, this actually works error-free
With this level of access, one is just a subprocess.Popen / os.system from very bad news.
That said, if your user input is trusted, using eval() is not less problematic.

Why is this Python loop running one too many times [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
i wanna create a Reverse word function, and i tried:
def reversa(str):
j=len(str)
for i in str:
j -=1
print(str[j], end="")
print(reversa("Apple"))
But it did not work.
Well there are existing functions for this already:
print("Apple"[::-1])
And:
print(''.join(reversed("Apple")))
Your code doesn't work because:
since there's no return and only print, just call like: reversa("Apple")
Also, would be nice to print() at the end, like (fixed up some stuff):
def reversa(s):
j=len(s)
for i in s:
j-=1
print(str[j], end="")
print()
print(reversa("Apple"))
Also if i where you, i would make a function like:
def reversa(s):
return ''.join([s[-i] for i in range(1,len(s)+1)])
Which could be called like:
print(reversa('Apple'))
You may want to use range to increment backwards from the largest index position
def reversal(str):
for i in range(len(str) - 1, -1, -1):
print(str[i], end="")
reversal("Apple")
The loop is not running one more time.
The thing is you are printing the function reversa (i.e. the return value of the function). Since you don't make the function return anything, None will be returned and printed after your function has ended.
You just need to call the function without print: reversa("Apple")

Counting and Grouping function with Python (2.7) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have tried the following function:
def item_order(order):
salads = order.count("salad")
hamburgers = order.count("hamburger")
waters = order.count("water")
return "salad:{} hamburger:{} water:{}".format(salads, hamburgers, waters)
taken from ( https://stackoverflow.com/questions/34906570/counting-and-grouping-with-python ),
with these two orders:
1st order = "salad water hamburger salad hamburger"
- then the function should returns "salad:2 hamburger:2 water:1"
2nd order = "hamburger water hamburger"
then the function should returns "salad:0 hamburger:2 water:1",
in http://www.pythontutor.com/visualize.html#mode=edit
But it seems it doesn't work.
Maintaining this structure, what am I doing wrong?
Many thanks for any help!!
You have a function definition, and then in your script you define the order:
def item_order(order):
# your function here
order = 'salad water hamburger salad hamburger'
When you call the function, you need to either assign the result to a variable or otherwise display the return from the function. So:
print item_order(order)
or:
x = item_order(order)
print x
Your code works as intended.
Variable order needs to be assigned some value and then function item_order can be called with variable order as the argument.

Calculator Program in Ruby/Python without using any built in operators [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was recently asked this in an interview for junior dev position. I was asked to create a calculator program that can add,subtract, multiply and divide without using the built in +,-,*,/ operators. Essentially to build it from the ground up.
I had no idea how to solve this. Does anyone have any guidance on how to implement at least one of the operations? I can figure out the rest from there but really need some guidance.
I code in both python and ruby.
This is an example of addition.
class Integer
def add(int) # int is 5 in the demo
res = self # 7 in the demo
int.times{res = res.succ} # succ just adds 1
return res
end
end
# demo
p 7.add(5) # => 12
Apart from succ, the Integer class has a pred method, which subtracts 1. Really useful for building a subtract method. Multiplying is just adding multiple times, and integer division is just subtracting multiple times.
Study how Ruby's "operators" are implemented; They're methods and send can be used as an alternate way of calling them.
From the documentation:
Invokes the method identified by symbol, passing it any arguments specified....
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
From that:
1.send(:+, 1) # => 2
Learning more about that is left as an exercise for the reader.
If you really want to dive in, you could create base methods like:
class Fixnum
def add(value)
val = self
value.times do
val = val.succ
end
val
end
end
1.add(1) # => 2

Categories

Resources