0

I have been trying to make a logarithm calculator on Python. I am just one step away from finishing it. Here is the code:

import math
print("Welcome to logarithm calculator")

while True:
    try:
        inlog = int(input("Enter any value greater than zero to lookup its logarithm to    the base 10\n"))
        outlog = math.log(inlog, 10)
        print(outlog)

        # Here, the program will ask the user to quit or to continue
        print("Want to check another one?")
        response = input("Hit y for yes or n for no\n")

        if response == ("y" or "Y"):
            pass
        elif response == ("n" or "N"):
            break
        else:
            #I don't know what to do here so that the program asks the user to quit or continue if the response is invalid?

    except ValueError:
        print("Invalid Input: Make sure your number is greater than zero and no alphabets. Try Again.")

After the else statement, I want the program to ask the user to respond again and again until it is a valid response as "y" or "Y" and "n" or "N". If I add another while loop here, it would work good to with pass statement if user enters "y". But it won't break the program when the user responds as "n" since it would land us in the outer loop. So how to sort this out?

1
  • 1
    response == ("y" or "Y") doesn't look right. You want response in 'Yy'. Commented Feb 10, 2013 at 11:06

6 Answers 6

4

You can move that test to a different function:

def read_more():
    while True:
        print("Want to check another one?")
        response = input("Hit y for yes or n for no\n")

        if response == ("y" or "Y"):
            return True
        elif response == ("n" or "N"):
            return False
        else:
            continue

And then in your function, just test the return type of this method:

while True:
    try:
        inlog = int(input("Enter any value greater than zero to lookup its logarithm to    the base 10\n"))
        outlog = math.log(inlog, 10)
        print(outlog)

        if read_more():
            continue
        else:
            break

Note that, you can go into infinite loop, if the user keeps on entering wrong input. You can restrict him to upto some maximum attempts.

Sign up to request clarification or add additional context in comments.

5 Comments

In case the in operator is too advanced, there's always writing out the boolean logic: if response == "y" or response == "Y"
Wait, isn't ("y" or "Y") always True, so if response == ("y" or "Y"): is actually if response == True:, which is always False?
@Volatility. Ah! Wait. You did have brackets there. I didn't see. Sorry will update the answer. But still, although that might work, but is confusing, so it's better to use in operator.
@RohitJain lol, did I sound like the OP there? I was just trying to point it out. ;)
@Volatility. Gurrr. Yup I got confused. Thanks for pointing anyways. :)
1

You can do something like this:

stop=False
while True:
    try:
        inlog = int(input("Enter any value greater than zero to lookup its logarithm to    the base 10\n"))
        outlog = math.log(inlog, 10)
        print(outlog)

        # Here, the program will ask the user to quit or to continue
        print("Want to check another one?")

        while True:
            response = input("Hit y for yes or n for no\n")
            if response == ("y" or "Y"):
                stop = False
                break
            elif response == ("n" or "N"):
                stop = True
                break
            else:
                continue
        if stop:
            break
except ValueError:
        print("Invalid Input: Make sure your number

2 Comments

Thanks, although there's no need of stop = False in the first line. Thank you. This is the most efficient solution, anyways.
@PreetikaSharma, yeah, that looks like that now. But I had started with something else in mind, so it was initialized there.
0

you can define a boolean parameter outside the value with an initial value of 'false'. at the beginning of each run of the outer loop, you can check for this boolean value, if it is true, then also break the outer loop. after that, when you want to end outer loop inside the inner loop, just make the value true before breaking inner loop. this way outer loop will also break.

Comments

0

Try this:

import math
class quitit(Exception):
    pass
print("Welcome to logarithm calculator")

while True:
    try:
        inlog = int(input("Enter any value greater than zero to lookup its logarithm to    the base 10\n"))
        outlog = math.log(inlog, 10)
        print(outlog)

        # Here, the program will ask the user to quit or to continue
        print("Want to check another one?")
        while True: 
            response = input("Hit y for yes or n for no\n")
            if response == ("y" or "Y"):
                break
            elif response == ("n" or "N"):
                raise quitit
except quitit:
        print "Terminated!"        
except ValueError:
        print("Invalid Input: Make sure your number is greater than zero and no alphabets. Try Again.")

Comments

0

If the user inputs a number less than or equal to zero, this will produce an exception that you have not accounted for.

As far as breaking out of the loop, it isn't too nested that you cannot already break out. If you had a deeper nesting then I would suggest using the following template for breaking out of nested loops.

def loopbreak():
  while True:
    while True:
      print('Breaking out of function')
      return
  print('This statement will not print, the function has already returned')

3 Comments

loopbreak will simply return from itself.
It was meant as a template. Did you even read ' If you had a deeper nesting then I would suggest the following.' In this light, your comment does not make sense to me. I wouldn't use a double while loop for this code but also wanted to answer the general question.
if you're in a nested loop and want to break from that, return would still terminate the entire function, not just the loops. This might be what you want, but it might not be. To be fair, you do say you're breaking out of the function...
0
stop=False
while not stop:
    try:
        inlog = int(input("Enter any value greater than zero to lookup its logarithm to the base 10\n"))
        outlog = math.log(inlog, 10)
        print(outlog)

        # Here, the program will ask the user to quit or to continue
        print("Want to check another one?")

        while True:
            response = raw_input("Hit y for yes or n for no\n")
            if response == ("y" or "Y"):
                break
            elif response == ("n" or "N"):
                stop = True
                break
    except ValueError:
        print("Invalid Input: Make sure your number")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.