如何解决类型错误:需要浮点数?

时间:2019-09-25 01:58:04

标签: python compiler-errors floating

它表示必须为浮点数。谁能帮我修复此代码:

from time import sleep
print("Welcome to this game of random.") ; sleep(1.0)
print("Type in your name:") ; sleep(0.5)
playerName = raw_input()
print("Welcome " + playerName + " Type how fast do you want the text to go in this format: 1.0") ; sleep(1.0)
speed = raw_input()
print("You choosed: " + speed) ; sleep(speed)

是否有需要解决的错误?

2 个答案:

答案 0 :(得分:0)

speed是一个字符串,您正在做sleep(speed)

sleep需要floatint,因此您需要执行sleep(float(speed))。假设输入为数字,因此在转换为float

时不会失败

您应该使用try/except

验证速度输入,以确保其格式正确。

答案 1 :(得分:0)

由于sleep以数字(intfloat作为参数,因此当将raw_input返回的值分配给{{1}时,需要强制转换}。我认为您正在使用Python 2,因此speed在Python 3中的等效项是raw_input,它将返回一个字符串:

input

此外,不要忘记将from time import sleep print("Welcome to this game of random.") ; sleep(1.0) print("Type in your name:") ; sleep(0.5) playerName = raw_input() print("Welcome " + playerName + " Type how fast do you want the text to go in this format: 1.0") ; sleep(1.0) ## LOOK AT THE FOLLOWING LINE speed = float(raw_input()) print("You choosed: " + str(speed)) ; sleep(speed) speed连接起来,将str转换为str