K.Vit
K.Vit

Reputation: 53

How do I let the user input enter a decimal number as well as just an integer?

How do I let the user input any type of number that they want? Here is what I tried:

a=0
def main():
    x = int(input("Input a number in Celsius to convert it to Fahrenheit"))
    f = (x*1.8)+(32)
    print(f, "degrees Fahrenheit")

a=a+1
while a > 0:
    main()

main()

Upvotes: 5

Views: 25164

Answers (3)

Sash Sinha
Sash Sinha

Reputation: 22360

To handle numeric input with greater precision and validation, consider using the decimal_input function from the typed-input1 library. This approach avoids floating-point precision issues by working with Decimal values and includes built-in input validation, making your program more robust without extra code. (Note the library also provides a float_input function if you absolutely require to use floats).

Installation

Install the typed-input library via pip:

pip install typed-input

Here’s an improved version of your code, also using int_input to determine how many values to convert:

from decimal import Decimal
from typed_input import decimal_input, int_input

def celsius_to_fahrenheit(celsius: Decimal) -> Decimal:
    return (celsius * Decimal('1.8')) + Decimal('32')

def fahrenheit_to_celsius(fahrenheit: Decimal) -> Decimal:
    return (fahrenheit - Decimal('32')) / Decimal('1.8')

def main():
    num_inputs = int_input('How many temperatures would you like to convert? ')
    for _ in range(num_inputs):
        celsius = decimal_input('Enter temperature in Celsius: ')
        fahrenheit = celsius_to_fahrenheit(celsius)
        print(f'{celsius:.2f}°C is {fahrenheit:.2f}°F')

if __name__ == '__main__':
    main()

Example Usage:

How many temperatures would you like to convert? a
Error: You must enter a valid integer.
How many temperatures would you like to convert? 3
Enter temperature in Celsius: a
Error: You must enter a valid Decimal.
Enter temperature in Celsius: 20
20.00°C is 68.00°F
Enter temperature in Celsius: 14.34
14.34°C is 57.81°F
Enter temperature in Celsius: -12.5
-12.50°C is 9.50°F

Why use typed-input?

  1. High Precision: Decimal avoids the inaccuracies of floating-point arithmetic, perfect for calculations like temperature conversions.
  2. Built-In Validation: The library ensures user input is valid, reducing error-prone custom validation code.
  3. Customizable Prompts: You can set input bounds, default values, or custom error messages for enhanced user guidance.

1 Disclosure: I am the author of typed-input.

Upvotes: 0

Transformer
Transformer

Reputation: 3760

Depending on the type of number you want you just have to try and catch

UPDATE since raw_input stores it data as str, because isinstance(x, str) will give you True.

x = raw_input("Input a number in celcius to convert it to fahrenheit")

try:
    val = int(x) # you can also covert to float before doing your calculation
    #carry out your calculations
except ValueError:
    print("That's not an int!")

Upvotes: 4

Sнаđошƒаӽ
Sнаđошƒаӽ

Reputation: 17562

Just use this:

x = float(input('Input a number in celcius to convert it to fahrenheit'))

Then carry out the required calculations with x.

Read about basic types in python here.

Any way, your indentation as given in the question is totally wrong. Your code should not even run. And your logic for running main() is also absurd. It could have been something like this:

a=0

def main():
    x = float(input("Input a number in celcius to convert it to fahrenheit"))
    f = (x*1.8)+(32)
    print(f, "degrees fahrenheit")

while a < 10: # for taking 10 inputs and converting
    main()
    a += 1

Upvotes: 7

Related Questions