Program ValueError: Could not convert string to float when entering the enter key

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

    total=0

    def readAndTotal():

       global total

       num=float(input('Enter a number'))

       if num !='':
          total+=num
          return readAndTotal()


       else:
          return total


    total = readAndTotal()
    print("The total of all those values is", total)

A program that outputs the sum of input values before pressing the Enter key. When you activate this code, it says that the str value cannot be converted to the float value. Which part is the problem?

ValueError: could not convert string to float:

python enter-key

2022-09-20 16:23

1 Answers

       num=float(input('Enter a number'))

       if num !='':
          total+=num
          return readAndTotal()

Do not switch to float as soon as input is received.

       num=input('Enter a number')

       if num !='':
          total+=float(num)
          return readAndTotal()

First, you need to receive a string input, check if the input is an empty string, and replace it with float when it is not.


2022-09-20 16:23

If you have any answers or tips


© 2022 pinfo. All rights reserved.