Home > Net >  Percentage as user input
Percentage as user input

Time:12-22

Is there a way to add percentage as a user input ?

Google didn't help.

enter image description here


Thax in advance

Update

Here is a simple code :-

dialy_average = float(input('Average daily increase: '))
print(dialy_average)

Here is output :-

Average daily increase: 30%
Traceback (most recent call last):
  File "C:\Users\jimsrc\Desktop\repo\New folder\test2.py", line 1, in <module>
    dialy_average = float(input('Average daily increase: '))
ValueError: could not convert string to float: '30%'

CodePudding user response:

If you expect the user to add characters to the input, you can parse it with regular expression:

import re

per_raw = input()
per_str = re.findall("([0-9] )%", per_raw)[0]
per = float(per_str)

This does not check for errors. If you to support decimal dot, you need to choose a different expression.

In other languages there's a function called scanf which is a bit more simple, but in python there's no equivalent currently.

CodePudding user response:

This should achieve what you want -

daily_average=float(input(‘Daily average increase - ‘).replace(‘%’,’’))/100
  • Related