How to fix error: SyntaxError: invalid syntax

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jake Colborn
    New Member
    • Nov 2010
    • 1

    How to fix error: SyntaxError: invalid syntax

    Hey, I just picked up python again after not coding with it for many years. But I wanted to throw some simple scripts together to see if I remember all the functionality so far. Now I've got this code:

    Code:
    #!/usr/bin/python
    
    # A program developed to see if the temperature is Celcius or Farhenheit
    # and than convert it to the other in a more user friendly manner
    
    import os, sys
    import math
    
    def far(temp):
    	
    	Celcius = ((temp - 32) * 5) / 9
    	Kelvin = Celcius + 273.15
    
    def cel(temp):
    	
    	Far = (temp * 1.8) + 32
    	Kelvin = temp + 273.15
    
    def kelvin(temp):
    
    	Celcius = temp + 273.15
    	Far = (Celcius * 1.8) + 32
    
    
    human = raw_input("Is your temperature in Fahrenheit (f), Celcius (c), or Kelvin (k) --> ")
    temp1 = int(raw_input("What is your temperature --> ")
    
    if human=="f":
    	far(temp1)
    	print "Your temperature is %s in Celcius and %s in Kelvin" % Celcius,Kelvin
    if human=="c":
    	cel(temp1)
    	print "Your temperature is %s in Fahrenheit and %s in Kelvin" % Far,Kelvin
    if human=="k":
    	kelvin(temp1)
    	print "Your temperature is %s in Celcius and %s in Fahrenheit" % Celcius,Far
    I want the user to define which kind of temperature they have and than the program to output the other temperatures. But so far all I get is an error in the syntax at line 28:

    Code:
      File "temp2.py", line 28
        if human=="f":
                     ^
    SyntaxError: invalid syntax
    Anyone have any thoughts?
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    You have to always check the previous line as well. If you have forgotten a closing parenthesis for example, the interpreter will think that this line is a continuation of the previous line and point to this line with the error. Also consider wrapping the input in a try/except, so if someone enters "F" or "98.6" for the temperature instead of an integer, you can catch it and then ask for a whole number.
    Code:
    ##   depending on how much input checking you want to do
    human = ""
    while human.lower() not in ["c", "f", "k"]:
        human = raw_input("Is your temperature in Fahrenheit (f), Celsius (c), or Kelvin (k) --> ")
    
    ## simplified example
    try:
        temp1 = int(raw_input("What is your temperature --> "))
    except:
        print "The temperature must be a whole number"

    Comment

    Working...