Основной вопрос по Python: недопустимая синтаксическая ошибка elif - PullRequest
0 голосов
/ 01 марта 2019

Я новичок в Python и пытаюсь выяснить, как работает отступ, а не скобки.У меня проблема с elif:

"""This program calculates the area of a circle or triangle."""
print "Area Calculator is on."
option = raw_input("Enter C for Circle or T for Triangle: ")
if option == 'C': radius = float(raw_input("Enter the radius: ")) 
  area = 3.14159*radius**2
  print "The area of circle with radius %s is %s." % (radius, area)
elif option == 'T':
    base = float(rawinput("Enter the base: "))
    height = float(rawinput("Enter the height: "))
    area2 = .5*base*height
    print "The area of triangle with base %s and height %s is %s." % (base, height, area2)

else: print "ERROR"

Всякий раз, когда я пытаюсь отправить это, это дает мне недопустимую синтаксическую ошибку в elif.Я пытался посмотреть на разные темы по этому поводу, но те, у которых elif-отступ был слишком далеко, или забыли поставить двоеточие в конце elif.Что я должен сделать, чтобы это исправить?

Ответы [ 2 ]

0 голосов
/ 01 марта 2019

Используете ли вы Python 2 или 3 ..

Я нахожусь в Python 3 и запускаю ваш код после нескольких изменений, и он работает нормально.Пожалуйста, попробуйте:

print ("Area Calculator is on.")
option = input("Enter C for Circle or T for Triangle: ")
if option == 'C':
    radius = float(input("Enter the radius: "))
    area = 3.14159*radius**2
    print ("The area of circle with radius %s is %s." % (radius, area))
elif option == 'T':
    base = float(input("Enter the base: "))
    height = float(input("Enter the height: "))
    area2 = .5*base*height
    print ("The area of triangle with base %s and height %s is %s." % (base, height, area2))
else: 
    print ("ERROR")
0 голосов
/ 01 марта 2019

Python - очень неумолимый язык, когда дело доходит до отступа.Руководство PEP-8 в стиле пойдет вам на пользу, но проблемы с вашим кодом были несовместимыми отступами после if, а затем после elif (2 против 4 пробелов) и запускапри объявлении переменной после двоеточия в if.

Вот пересмотренная версия вашего скрипта Python 2:

#!/usr/bin/env python2

"""This program calculates the area of a circle or triangle."""
print "Area Calculator is on."
option = raw_input("Enter C for Circle or T for Triangle: ")
if option == 'C':
    radius = float(raw_input("Enter the radius: ")) 
    area = 3.14159*radius**2
    print "The area of circle with radius %s is %s." % (radius, area)
elif option == 'T':
    base = float(raw_input("Enter the base: "))
    height = float(raw_input("Enter the height: "))
    area2 = .5*base*height
    print "The area of triangle with base %s and height %s is %s." % (base, height, area2)
else:
    print "ERROR"
...