首页 > 解决方案 > 我不明白为什么我的缩进是错误的,当我输入答案时,除了错误之外什么都不输出

问题描述

我正在使用带有 Python 2.7.6 的 PyScripter 运行它。我不明白为什么我的代码是错误的。有人可以给我一个解释吗?

def mainMenu():
answer = input("""Main Menu:
Pythagoras
Repeat Program
Quit""")
if answer == "Pythagoras":
    pythagoras()
elif answer == "Repeat Program":
    mainMenu()
elif answer == "Quit":
    print("Program ended")
else:
    mainMenu()

def pythagoras():
if answer == "Pythagoras":
    aNotSquared = input("Input the value of A")
bNotSquared = input("Input the value of B")

aSquared = aNotSquared ** 2
bSquared = bNotSquared ** 2

valueC = aSquared + bSquared

print(valueC)


mainMenu()

标签: pythonpython-2.7

解决方案


不确定粘贴时是否出现缩进错误,但在外部也有一些问题需要修复

  • if answer == 'Pythagoras'在进入函数之前已经测试过,在函数内部pythagoras()检查不起作用也没有意义answer
  • 无法根据strings需要执行数学运算将您的输入转换为int
  • 在输入和打印结果时,为清晰起见的通用格式
  • PEP-8snake_caseCamelCase

略微改进的版本:

from math import sqrt

def main_menu():
    answer = input("""Main Menu:
    Pythagoras
    Repeat Program
    Quit\nChoose option from above: """)
    if answer == "Pythagoras":
        pythagoras()
    elif answer == "Repeat Program":
        main_menu()
    elif answer == "Quit":
        print("Program ended")
    else:
        main_menu()

def pythagoras():
    a_not_sqr = int(input("Input the value of A: "))
    b_not_sqr = int(input("Input the value of B: "))

    a_sqr = a_not_sqr ** 2
    b_sqr = b_not_sqr ** 2

    c_sqr = a_sqr + b_sqr
    c_not_sqr = sqrt(c_sqr)

    print(f'C Squared  = {c_sqr}')
    print(f'C = {round(c_not_sqr, 2)}')

main_menu()
Main Menu:
    Pythagoras
    Repeat Program
    Quit
Choose option from above: Pythagoras
Input the value of A: 10
Input the value of B: 10
C Squared  = 200
C = 14.14

推荐阅读