Loop in Tip Calculator (Python)

TheSuds13

So I'm making a tip calculator at the moment. The thing that I am stuck on is where they can input the total amount of the cost. If they input an integer I want it to break out of the loop but if they input something else than an integer, I want it to stay in the loop and tell them to enter an integer. Here is the code that I made for this portion. (Not all the code)

Integer = range(1,10000)




while True:
    while True:
        Cost = raw_input("What was the cost? ")
        Cost = int(Cost)
        if Cost in Integer:
            break
        else:
            pass

The spacing may not look correct but it is in the actual script. I still don't know how to paste the code on here without having to add 4 spaces to every line. Anyway, please let me know what you would do to complete the task I need.

Jules G.M.

Cost = int(Cost) will raise a ValueError if Cost is not a string for an Integer.

as such,

    while True:
        Cost = raw_input("What was the cost? ")
        try:
             Cost = int(Cost)
             break
        except ValueError:
             print("Please enter an Integer for the cost")

as you can see, break will only be executed if the ValueError is not raised.

You should not do this though. What you should do is test for isdigit before casting:

    while True:
        Cost = raw_input("What was the cost? ")
        if Cost.isdigit():
             Cost = int(Cost)
             break
        else:
             print("Please enter an Integer for the cost")

exceptions make control flow be unobvious and should be avoided if possible.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사