如何修复错误:语法错误:无效语法

嘿,我只是在多年没有用它编程之后又重新开始使用它了。但我想把一些简单的脚本组合在一起,看看我是否记住了到目前为止的所有功能。现在我得到了这个代码:

选择 | 换行 | 行号
  1. #!/usr/bin/python
  2.  
  3. # A program developed to see if the temperature is Celcius or Farhenheit
  4. # and than convert it to the other in a more user friendly manner
  5.  
  6. import os, sys
  7. import math
  8.  
  9. def far(temp):
  10.  
  11.     Celcius = ((temp - 32) * 5) / 9
  12.     Kelvin = Celcius + 273.15
  13.  
  14. def cel(temp):
  15.  
  16.     Far = (temp * 1.8) + 32
  17.     Kelvin = temp + 273.15
  18.  
  19. def kelvin(temp):
  20.  
  21.     Celcius = temp + 273.15
  22.     Far = (Celcius * 1.8) + 32
  23.  
  24.  
  25. human = raw_input("Is your temperature in Fahrenheit (f), Celcius (c), or Kelvin (k) --> ")
  26. temp1 = int(raw_input("What is your temperature --> ")
  27.  
  28. if human=="f":
  29.     far(temp1)
  30.     print "Your temperature is %s in Celcius and %s in Kelvin" % Celcius,Kelvin
  31. if human=="c":
  32.     cel(temp1)
  33.     print "Your temperature is %s in Fahrenheit and %s in Kelvin" % Far,Kelvin
  34. if human=="k":
  35.     kelvin(temp1)
  36.     print "Your temperature is %s in Celcius and %s in Fahrenheit" % Celcius,Far
  37.  

我希望用户定义他们有哪种温度,然后程序输出其他温度。但到目前为止,我得到的只是第28行的语法错误:

选择 | 换行 | 行号
  1.   File "temp2.py", line 28
  2.     if human=="f":
  3.                  ^
  4. SyntaxError: invalid syntax
  5.  

有谁有什么想法吗?

# 回答1


您还必须始终检查前一行。例如,如果您忘记了右括号,解释器会认为此行是前一行的延续,并会错误地指向此行。还可以考虑将输入包装在try/Except中,这样,如果有人输入"F"或"98.6"而不是整数作为温度,您可以捕获它,然后请求一个整数。

选择 | 换行 | 行号
  1. ##   depending on how much input checking you want to do
  2. human = ""
  3. while human.lower() not in ["c", "f", "k"]:
  4.     human = raw_input("Is your temperature in Fahrenheit (f), Celsius (c), or Kelvin (k) --> ")
  5.  
  6. ## simplified example
  7. try:
  8.     temp1 = int(raw_input("What is your temperature --> "))
  9. except:
  10.     print "The temperature must be a whole number" 

标签: python

添加新评论