How do I consider just what number a user enters in an input? (python)

Asked

Viewed 39 times

-1

rabanada = int(input("Quantos quilos você pesa? "))

if rabanada > 100000:
   print("Você é gordo")

else:
   print("Você tá magro, rlx")

If the user type: "100 kilos", as I do for the program consider only the number (100) and not the string (kilos) ?

1 answer

2


You will use regular expressions for this. Something like:

import re

texto = '100 quilogramas'
peso = int(re.sub('\D', '', texto))
print(peso) # 100

What the above example does is to take the string and remove everything that is not number, for this it uses the regular expression \D. In your example you would do something like:

import re

rabanada = int( re.sub('\D', '', input("Quantos quilos você pesa? ")) )

if rabanada > 100000:
   print("Você é gordo")

else:
   print("Você tá magro, rlx")

You just have to be aware that if you don’t type a number into data entry one, ValueError will be released because it will take away everything that is not number, so in the end will be something as being int('').

And it will throw this error. You can already validate before, replace and see if it has characters or make a try/except.

  • 1

    Remember that if you type something like a1 b2 c3, shall be considered to have a weight of 123. Of course a format was not specified (apparently it can be "anything"), but however, it is the tip :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.