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 Comparison Challenge

Any way to make cleaner code?

It works for the most part, I was having a hard time with displaying an error message if someone entered a name into the number question. i used .isdigit() at first, but i couldn't find a way to have 2 else statements next to each other so I just completely removed it. I started to get a feeling that this wasn't important for where we're at right now in the course. I'm not sure if I followed the directions properly, but it works. Any way to make this code a little cleaner and more concise?

name = input("Please enter your name: ")
number = input("Please enter a number: ")
true_number = int(number) 
print(name)
print(number)
if true_number % 3 == 0 and true_number % 5 == 0:
    is_fizzbuzz = True
    print("is a FizzBuzz Number")
elif true_number % 3 == 0 and true_number % 5 != 0:
    is_fizz = True  
    print("is a Fizz Number")
elif true_number % 3 != 0 and true_number % 5 == 0:
    is_buzz = True   
    print("is a Buzz Number")
else: 
    print("This is neither a Fizzy or a Buzzy Number")

Any Help is appreciated

1 Answer

Steven Parker
Steven Parker
210,425 Points

You can directly assign the results of a comparison to a variable, and avoid re-testing conditions previously eliminated by other tests:

is_fizz = true_number % 3 == 0
is_buzz = true_number % 5 == 0
if is_fizz and is_buzz:
    print("is a FizzBuzz Number")
elif is_fizz:
    print("is a Fizz Number")
elif is_buzz:
    print("is a Buzz Number")
else: 
    print("This is neither a Fizzy or a Buzzy Number")

Thanks, it really helped me clean up my code