如果语句不会执行最后一行

时间:2019-09-23 00:49:39

标签: python

我是编码的初学者,我的elif语句出了点问题,我无法弄清楚什么

由于某种原因,该代码被卡在or中,它将永远不会执行'4'选项。我们正在尝试使用较少重复的代码,但没有什么太先进的,因为我们只是开始学习python。

# defines menu
menu = '1- Sum of integers\n2- Sum of squares\n3- sum of cubes\n4- Geometric series'

# asks user for menu choice
print(menu)

menuChoice = 0
while menuChoice >= 0:
menuChoice = int(input(
    'Please enter a choice from our menu. (enter a negative number to quit)\n'))
sum = 0
calcSum = 0
if menuChoice == 0:
    print(menu)
elif menuChoice == 1 or 2 or 3:
    n = int(input('Enter n: '))
    for i in range(n + 1):
        if menuChoice == 1:
            sum += i
            calcSum = n * (n + 1)/2
        elif menuChoice == 2:
            sum += i ** 2
            calcSum = n * (n + 1) * (2 * n + 1)/6
        elif menuChoice == 3:
            sum += i ** 3
            calcSum = (n + (n + 1) / 2) ** 2

elif menuChoice == 4:
    x = int(input("Please Enter the Common Ratio: "))
    n = int(input("Please Enter the Total Numbers in this Geometric Series:  "))
    for i in range(n + 1):
        sum += x ** i

2 个答案:

答案 0 :(得分:1)

<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="site.css"> </head> <body> <div> <ul class="navigation"> <li class="nav" id="logo">Company logo goes here</li> <div class="bottom-border"> <li class="nav">Home</li> </div> <li class="nav">FAQ</li> <li class="nav">Sign-up</li> </ul> </div> <div class="lander"> <h1 id="let-credit">This is<br>a test site.</h1> <h4 id="how-it-works">How it works.</h4> </div> <ol id="how-it-works"> <li>lorem</li> <li>Ipsum.</li> <li>Lorem.</li> </ol> </body> </html>被解析为menuChoice == 1 or 2 or 3,并且由于(menuChoice == 1) or 2 or 3(和2)是真实的,因此总是逃避为真实值。改用3menuChoice == 1 or menuChoice == 2 or menuChoice == 3

答案 1 :(得分:0)

更改您的if陈述:

or 2 or 3

您的代码不起作用,因为在python or True or True中条件被转换为# defines menu menu = '1- Sum of integers\n2- Sum of squares\n3- sum of cubes\n4- Geometric series' # asks user for menu choice print(menu) menuChoice = 0 while menuChoice >= 0: menuChoice = int(input('Please enter a choice from our menu. (enter a negative number to quit)\n')) sum = 0 calcSum = 0 if menuChoice == 0: print(menu) elif menuChoice == 1 or menuChoice == 2 or menuChoice == 3: n = int(input('Enter n: ')) for i in range(n + 1): if menuChoice == 1: sum += i calcSum = n * (n + 1)/2 elif menuChoice == 2: sum += i ** 2 calcSum = n * (n + 1) * (2 * n + 1)/6 elif menuChoice == 3: sum += i ** 3 calcSum = (n + (n + 1) / 2) ** 2 elif menuChoice == 4: x = int(input("Please Enter the Common Ratio: ")) n = int(input("Please Enter the Total Numbers in this Geometric Series: ")) for i in range(n + 1): sum += x ** i ,因为在条件中值(非零)始终被认为是``真实的''。

此代码运行:

{{1}}