Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics Functions and Looping While Loops

devin blair
devin blair
4,075 Points

Restarting program rather than exiting when entering an invalid number

I'm trying to make it to where rather than just printing a message and exiting the program it just loops back to the beginning so you don't have to manually restart it but I can't figure it out. I've tried using while loops and using another function but none of it has worked so far.

import math
def split_check(total, number_of_people):
    if (number_of_people <= 0) or (total <=0):
        raise ValueError("Value cannot be 0 or negative")
    return math.ceil(total / number_of_people)

try:
    total_due = float(input("What is the total? "))
    number_of_people = int(input("How many people "))
    amount_due = split_check(total_due, number_of_people)
except ValueError:
    print("value cannot be 0 or negative")
else:
     print("each person owes ${}".format(amount_due))

1 Answer

Mark Sebeck
MOD
Mark Sebeck
Treehouse Moderator 30,296 Points

Good question Devin. There are many ways to do loops so think of my solution as one of many. I simply made an infinite loop and then break out of the loop when there is a non zero value entered for number of persons.

import math
def split_check(total, number_of_people):
    if (number_of_people <= 0) or (total <=0):
        raise ValueError("Value cannot be 0 or negative")
    return math.ceil(total / number_of_people)

while 1:
    try:
        total_due = float(input("What is the total? "))
        number_of_people = int(input("How many people "))
        amount_due = split_check(total_due, number_of_people)
    except ValueError:
        print("value cannot be 0 or negative")
    else:
        print("each person owes ${}".format(amount_due))
        break

I challenge you to find another way to implement a loop here. Keep at it Devin!

devin blair
devin blair
4,075 Points

I was so close! I was actually putting the break statement in the wrong place, now I'm trying to change it to where it prompts the user "Value cannot be 0 or negative press r to restart or x to exit" so far I've tried this with nested functions, I'll post it if I figure it out thank you for the help.