尝试将字符串转换为浮点时的ValueError

时间:2016-08-01 15:13:27

标签: python

我在运行此程序时遇到了麻烦 它告诉我,我有一个

  

ValueError:无法将字符串转换为float

问题是,它只是跳过我的输入命令并跳转到

print("Invalid Response")

这个程序在我的手机上工作正常但在我的Windows 10笔记本电脑上却没有。

有任何帮助吗?尝试运行它,让我知道它是否适合你。

def calc():        #The function performing calculation. 
    if chars == "+":
        result = num1 + num2
        print (result)
        return result
    elif chars == "-":
        result = num1 - num2
        print(result) 
        return result 
    elif chars == "*":
        result = num1 * num2
        print(result)
        return result 
    elif chars == "/":
        result = float(num1) / float(num2)
        print(result)
        return result 
    else:
        print("Invalid or unsupported operation")

cont = ""  
def contin():
        result = calc()
        print("Operate? y/n: ")
        cont = input()  
if cont == "y": 
        print(result)           # output is:                  ought to be:
        chars = input()                   #result                     result
        contin_num = float(input()) 
        calc(contin_num)        #result                     operate y/n
        print(result, chars, contin_num)     

elif cont == "n":
        result = 0
        print(result)
else:
        print ("Invalid response.")


num1 = float(input ()) 
chars = input () 
num2 = float(input ()) 
result = 0       

while num1 > 0 or num2 > 0: 
    calc()
    contin()
    break
if num1 == 0 and num2 == 0:
    print("Zero or undefined.")

1 个答案:

答案 0 :(得分:0)

这是所需的代码。在Contin()函数和一些逻辑的情况下,我改变了一些缩进是错误的。如果我在某些地方错了请告诉我,请参考这个。谢谢

def calc(num1,chars,num2):        #The function performing calculation. 
    if chars == "+":
        result = num1 + num2
        print (result)
        return result
    elif chars == "-":
        result = num1 - num2
        print(result) 
        return result 
    elif chars == "*":
        result = num1 * num2
        print(result)
        return result 
    elif chars == "/":
        result = float(num1) / float(num2)
        print(result)
        return result 
    else:
        print("Invalid or unsupported operation")

cont = ""  
def contin(res):
        num1 = res
        print("Operate? y/n: ")
        cont = raw_input()  
    if cont == "y": 
            print(num1)           # output is:                  ought to be:
            chars = raw_input()                   #result                     result
            num2 = float(input()) 
            num1=calc(num1,chars,num2)        #result                     operate y/n
            print num1     

    elif cont == "n":
            result = 0
            print(result)
    else:
            print ("Invalid response.")


num1 = float(input ()) 
chars = raw_input () 
num2 = float(input ()) 
result = 0       

while num1 > 0 or num2 > 0: 
    res = calc(num1,chars,num2)
    contin(res)
    break
if num1 == 0 and num2 == 0:
    print("Zero or undefined.")