user5737301
user5737301

Reputation:

Error when input contains letters in Python

I have encountered a problem with eval(input(...)), it gives me an error when I input letters.

When I use instead this:

first_input = km

It works perfectly fine. But I want to make user to input letters.

I found similar answers to my question, but they all relate to Python 2 and tell to use raw_input, but it doesn't work for me, however. Most likely because my Python version is 3.5.1.

Here is some part of my code:

    ...        

first_unit = eval(input("Enter the units for the first value (cm, m or km): "))

# convert units into m
if first_unit is 'cm':
   first_input = first_input / 100
elif first_unit is 'km':
   first_input = first_input * 1000
else:
   first_input = first_input

   ...

Upvotes: 0

Views: 59

Answers (1)

Bakuriu
Bakuriu

Reputation: 101989

DO NOT USE eval!!!

In order to obtain an input from the user you simply call input. It returns a string already.

Secondly: do not compare objects using is! Use ==:

first_unit = input("Enter the units for the first value (cm, m or km): ")

# convert units into m
if first_unit == 'cm':
   first_input = first_input / 100
elif first_unit == 'km':
   first_input = first_input * 1000
else:
   first_input = first_input

The is operator compares identities not values.

Note: to obtain a number from the user you should use either int(input(..)) or float(input(..)) depending on whether it is an integer or decimal.

Upvotes: 4

Related Questions