if-else statement and code exit

旧城冷巷雨未停 提交于 2020-04-30 04:26:53

问题


basically I'm quite new to python so I decided to make a simple calculator, I have done the coding for the calculator and that all works and I am happy, however I would like an if-else statement to see if they would like to continue with another calculation. So this is the top part of my code and the bottom part of my code, I would like to know how to get it so that after the 'else' part of the code, it just runs the rest of the code.

import os
done = ("")
if done == True:
    os._exit(0)
else:
    print ("---CALCULATOR---")

...

done = str(input("Would you like to do another calculation? (Y/N) "))
if done == "N" or "n":
    done = True
if done == "Y" or "y":
    done = False

Any help would be appreciated.


回答1:


if done == "N" or "n":

The above condition checks whether done == "N" or "n". This will always evaluate to True because in Python, a non-empty string evaluates to boolean True.

As suggested in the comments you should use a while loop to have the program continue to execute until the user types in "N" or "n".

import os
finished = False

while not finished:
    print ("---CALCULATOR---")
    ...

    done = str(input("Would you like to do another calculation? (Y/N) "))
    if done == "N" or done == "n":
        finished = True



回答2:


You'll want something like this...

import os
done = False

while not done:
    print ("---CALCULATOR---")
    ...

    # be careful with the following lines, they won't actually do what you expect
    done = str(input("Would you like to do another calculation? (Y/N) "))
    if done == "N" or "n":
        done = True
    if done == "Y" or "y":
        done = False


来源:https://stackoverflow.com/questions/19961400/if-else-statement-and-code-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!