Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

python - How do I restrict an input to be to the second decimal?

I'm taking an intro to Python and I'm asked to request an input of dimes and quarters and then add the values, I'm trying to restrict either the input to a second decimal for the dimes.

dimes = input('How many dimes do you have?: ')
dimes = round(dimes, 2)

It's supposed to take an input and put it to the second decimal:

input = 5
output = 0.05

What it's doing:

   dimes = round(dimes, 2)
TypeError: type str doesn't define __round__ method
question from:https://stackoverflow.com/questions/65864331/how-do-i-restrict-an-input-to-be-to-the-second-decimal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You simply need to convert the input to an integer and divide it by 100.

dimes = int(input('How many dimes do you have?: ')) / 100

This will fail if the user enters something that is not an integer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...