Home > Blockchain >  How do I have a value that can be both a floating decimal point or a string in python?
How do I have a value that can be both a floating decimal point or a string in python?

Time:11-09

so, I need one of my variables to be A possibility. like, it is a user input var & it can be both a floating decimal point or a string. And, so I want to do stuff with it, like >/</= but if the user says "done" I exit. So, let me show you:

largest = None
smallest = None
while True:
    try:
        num = input("Enter a number: ")
        float(num)
    except:
        "invalid input"
    if num == "done":
        break
    if num > largest:
        largest = num
        
    if smallest == None:
        smallest= num
        
    if smallest > num:
        smallest = num
    print(num)

print("Maximum is", largest)
print("Minimum is", smallest)

CodePudding user response:

I don't really understand what you're trying to do, but you can always perform the float conversion after you compare the user input against a string:

largest = float('inf')
smallest = None

while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    try:
        num = float(num)
    except:
        print("invalid input")
    if num > largest:
        largest = num

    if smallest == None:
        smallest = num

    if smallest > num:
        smallest = num
    print(num)

print("Maximum is", largest)
print("Minimum is", smallest)

Here's a sample play through:

Enter a number: 1.2
1.2
Enter a number: 3.4
3.4
Enter a number: 0
0.0
Enter a number: done
Maximum is inf
Minimum is 0.0

One suggestion for a code simplification I had, assuming you're on Python 3.8 , is to use the walrus := operator, which should allow you to omit the break condition:

while (num := input("Enter a number: ")) != 'done':
    try:  # same as before
       ...

CodePudding user response:

First, read the number as a string, check if it's "done" and only after convert to a float:

while True:
    num = input()
    if num == "done":
        break
    num = float(num)
    # ... do something with num ...

CodePudding user response:

You don't need to have it for this example. The value you read from user input can be always a string and if this string is not "done", then it should be a float number, otherwise it is invalid. More specifically you don't need your input to be any float or string. You need it to be any float or "done". See the following snippet:

largest = None
smallest = None
while True:
  text = input("Enter a number: ")
  if text == "done":
    break
  else:
    try:
      num = float(text)
      if smallest is None or num < smallest:
        smallest = num
      if largest is None or num > largest:
        largest = nunm
    except:
      print("Invalid input")

print("Maximum is", largest)
print("Minimum is", smallest)
  • Related