Matt
Matt

Reputation: 1521

Input variables in Python 3

Is it possible to have a user input equal to a variable for tasks that involve chemical elements.

For example, Carbon has the molecular mass 12, but i do not want the use to input 12, They should input 'C'. but as the input turns this into a string, it is not possible to lik this to the variable C = 12.

Is there any way to input a variable istead of a string?

If not, could i set a string as a variable.

example:

C = 12

element = input('element symbol:')
multiplier = input('how many?')

print(element*multiplier)

This just returns an error stating that you can't multiply by a string.

Upvotes: 4

Views: 14100

Answers (4)

Ashutosh Makharia
Ashutosh Makharia

Reputation: 11

Since input always return string type. Multiplication to the string is not allowed. So after taking the input, you need to type cast if using int type in python .

Try this:

multiply_string = input("how many? ")
multiplier = int(multiplier_string) #type cast here as int

Upvotes: 1

kennytm
kennytm

Reputation: 523214

input in Python 3.x is equivalent to raw_input in Python 2.x, i.e. it returns a string.

To evaluate that expression like Python 2.x's input, use eval, as shown in the doc for changes from 2.x to 3.0.

element = eval(input("element symbol: "))
....

However, eval allows execution of any Python code, so this could be very dangerous (and slow). Most of the time you don't need the power of eval, including this. Since you are just getting a global symbol, you could use the globals() dictionary, and to convert a string into an integer, use the int function.

element = globals()[input("element symbol: ")]
multiplier = int(input("how many? "))

but when a dictionary is needed anyway, why not restructure the program and store everything in a dictionary?

ELEMENTS = {'C': 12.0107, 'H': 1.00794, 'He': 4.002602, ...}

try:
  element_symbol = input("element symbol: ")
  element_mass = ELEMENTS[element_symbol]

  multiplier_string = input("how many? ")
  multiplier = int(multiplier_string)

  print(element_mass * multiplier)

# optional error handling
except KeyError:
  print("Unrecognized element: ", element_symbol)
except ValueError:
  print("Not a number: ", multiplier_string)

Upvotes: 3

jon_darkstar
jon_darkstar

Reputation: 16768

element = eval(input("element symbol: "))

would be the simplest, but not necessarily the safest. Plus, your symbol needs to be in the local scope

you might prefer to have a dictionary object

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319551

You could change your code like this:

>>> masses = {'C': 12}
>>> element = input('element symbol:')
element symbol:C
>>> masses[element]
12
>>> multiplier = input('how many?')
how many?5
>>> multiplier
'5'                                          # string
>>> masses[element] * int(multiplier)
60

Upvotes: 9

Related Questions