Input Variables in Python 3

Is it possible for user input to be equal to a variable for tasks related to chemical elements.

For example, carbon has a molecular weight of 12, but I do not want to use input 12, they must enter "C". but as the input turns this into a string, it is impossible to match this with the variable C = 12.

Is there a way to input the variable istead string?

If not, can I set the 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 cannot multiply by a string.

+3
source share
4 answers

You can change your code as follows:

>>> 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
+8
source

input Python 3.x raw_input Python 2.x, .. .

, Python 2.x input, eval, doc 2.x 3.0.

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

eval Python, ( ). eval, . , globals() , int.

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

, ?

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)
+3

. . input cast, int python.

:

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

element = eval ( ( " :" ))

will be the easiest, but not necessarily the safest. In addition, your character must be in the local area

you might want to have a dictionary object

0
source

Source: https://habr.com/ru/post/1772712/


All Articles