Home > OS >  how to print a string in a variable based on what the user inputs?
how to print a string in a variable based on what the user inputs?

Time:10-17

x = '123'
#asks for input, user inputs x
#prints 123

how can I print a variable based on user input?

CodePudding user response:

input() can be used to fetch input from the command line.

name = input("Your Name: ")
print("Hello there, "   name   "!")

CodePudding user response:

Dynamic variable name is not recommended, especially in this situation because you are directly taking the user input. But if you really want to implement it, globals() is one option:

x = '123'
y = '456'

which = input('What do you want to see?: ') # x
print(globals()[which]) # 123

A better and more secure approach would be to use a dict:

user_vars = {'x': '123', 'y': '456'}

which = input('What do you want to see?: ') # x
print(user_vars[which]) # 123

CodePudding user response:

You can make use of the dictionary in python as follows:

user_options = {'x': '123', 'y': '456', 'z': '789'}

entered_value = input('Please enter an input?: ') # could be x, y or z depending upon the dictionary
print(user_options[entered_value])

This should give you the number depending on if x,y, or z is entered

CodePudding user response:

You can also use eval(),

The eval() method parses the expression passed to this method and runs python expression (code) within the program.

x = '123'
try:
    print(eval(input()))
except NameError:
    print("Invalid variable name")
  • Related