Python 3:IF输入数字然后文本代码继续;如果输入文本或没有重启代码:不起作用

时间:2015-06-04 09:13:21

标签: python

while 1:
    try:
        distance=1
        time = input("How long did it take you to reach 1 mile in seconds: ")
        f = float(time)
        speed =((distance/time)*60)*60
        print("Car",Registration_Plate,"was going at" ,speed,"Mph")
        speed_limit=60
        if speed > speed_limit:
            print("Car","'",Registration_Plate,"'"," was speeding")
        if speed ==speed_limit or speed<speed_limit:
            print("Car","'",Registration_Plate,"'"," was not speeding")
    except ValueError:
        quit

1 个答案:

答案 0 :(得分:0)

首先,这是你的工作。

while 1:
    try:
        distance=1
        Registration_Plate="whatever you want"
        time = input("How long did it take you to reach 1 mile in seconds: ")
        f = float(time)
        speed =((distance/f)*60)*60
        print("Car",Registration_Plate,"was going at" ,speed,"Mph")
        speed_limit=60
        if speed > speed_limit:
            print("Car","'",Registration_Plate,"'"," was speeding")
        if speed ==speed_limit or speed<speed_limit:
            print("Car","'",Registration_Plate,"'"," was not speeding")
    except ValueError:
        quit()

您忘记在Registration_Plate quit之后宣布except ValueError:旁边的quit(),因此您使用exitLoop=True while exitLoop: try: #do your code here except ValueError: exitLoop=False

注意: 调用quit()也会关闭python环境的当前实例。 更安全的是休息或暂时使用变量,例如:

nx <- 100
secs <- 2
x <- runif(nx)
obspersec <- nx/secs

xsub <- function(t){
   i <- trunc(t*obspersec)+1
   if (i<=0) return(0)
   if (i>nx) return(0)
   return(x[i])
}

x_njk <- function (n,i,k){
  if (i<k){
    return (0)
  } 
  sum <- 0
  for (j in 0:k){
    term <- ((-1)^j)*choose(k,j)*xsub((i-j)/n)
    sum <- sum + term 
  }
  return(sum)
}

n <- 100

for (k in 1:2){
   for (i in k:10){
     print(sprintf("n:%d i:%d k:%d  x_njk:%.5f",n,i,k,x_njk(n,i,k)))
   }
}

另一个注意: 尝试解释身体中的问题,而不是标题中的问题。 它使得理解问题变得更加容易。