-1

Here is my code:

def retest2():
    print "Type in another chapter title! Or type \"Next\" to move on."
def primenumbers1():
    print "--------------------------------------------------\nChapters in books are usually given the cardinal numbers 1, 2, 3, 4, 5, 6 and so on.\n\nBut I have decided to give my chapters prime numbers 2, 3, 5, 7, 11, 13 and so on because I like prime numbers.\n\nType in the chapter title of my book (a prime number) and I will tell you what cardinal number the chapter is."
def primenumbers2():
    chapter = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233)
    while True:
        prime = raw_input("\n")
        if "next"  == prime.lower() or "Next" == prime.lower():
            print "--------------------------------------------------\nOnto the next thing."
            break
        try:
            p = int(prime)
            if p in chapter:
                print "Chapter ",chapter.index(p) + 1
                retest2()
        except ValueError:  #invalid input
            print "That is not one of my chapter numbers because {0} is not a prime number found in my book. Try again.".format(prime)

        if p not in chapter:    #input is integer, but not a prime number within my range of primes
            print "That is not one of my chapter numbers because {0} is not a prime number found in my book. Try again.".format(prime)
primenumbers1()
primenumbers2()

I asked a similar question with this program in mind (Python – Have a variable be both an int and a str) but now I have encountered a couple of different problems. When I type in a random string such as okay as my first input in this while loop, I get an error message:

That is not one of my chapter numbers because okay is not a prime number found in my book. Try again.
Traceback (most recent call last):
  File "trial.py", line 83, in <module>
    primenumbers2()
  File "trial.py", line 80, in primenumbers2
    if p not in chapter:    #input is integer, but not a prime number within my range of primes
UnboundLocalError: local variable 'p' referenced before assignment

Yet when I type in okay in a later input, it works.

One other error is that in this loop, if I haven't yet typed in a prime number, and then I type in okay, the output is two lines of That is not one of my chapter numbers because okay is not a prime number found in my book. Try again.

Community
  • 1
  • 1
theo1010
  • 127
  • 10

3 Answers3

3

For the second error you mentioned in the above comment: (I can't comment yet, I don't know how else to respond)
"I did what you suggested and initialized p with p=None and that worked well to get rid of my first problem. However, if I enter okay I get 2 lines of That is..., and that's probably because this argument satisfies both the except and the if p not in chapter... How can I avoid this?"

You are getting this error for invalid inputs because it prints out the first time for invalid inputs but then the code continues to check if p is not in chapter, and it is not so it will print again.

What you want to do is find some way to skip the next if-block should the except occur. Once you know it's an invalid input you don't want to continue looking through your chapters.

In python you can do this by adding a continue statement. Add this in your error handling for ValueError and it will prevent you from continuing to check if p not in chapter for invalid inputs.

except ValueError:  #invalid input
    print "That is ...'
    continue

You can read more about the continue statement here, I recommend reading up before using it! https://docs.python.org/2/reference/simple_stmts.html#continue

I would also like to mention that in python, convention is to keep lines under 80 chars. It makes it a lot easier for other coders to read and follow your code.

Burkely91
  • 902
  • 9
  • 28
2

You're initializing p in your try block but trying to use it after the code in except runs. If you get a ValueError you get p was referenced before assignment. How to solve: initialize p before the try block

p=None
try:
    # do smth
except:
    # do smth
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Okay but how do I solve this? If I define `p` somewhere outside of the `except`, I get this error message: `ValueError: invalid literal for int() with base 10: 'okay'` – theo1010 May 16 '15 at 20:12
  • @theo1010, this error is because you entered `okay` in your `raw_input` and then tried to convert it to integer. Certainly, you got an error. Enter an integer and everything'll work – ForceBru May 16 '15 at 20:21
  • I did what you suggested and initialized `p` with `p=None` and that worked well to get rid of my first problem. However, if I enter `okay` I get 2 lines of `That is...`, and that's probably because this argument satisfies both the `except` and the `if p not in chapter`... How can I avoid this? – theo1010 May 16 '15 at 20:36
  • @theo1010 I've added an answer below that hopefully helps with this, let me know if it makes sense! – Burkely91 Jun 14 '15 at 05:02
0

When you handle your exception with except ValueError: #invalid input in the first loop, you don't define p.

Adding continue seems to make more sense:

 except ValueError:  #invalid input
     print "That is ...'
     continue
Mike Müller
  • 82,630
  • 20
  • 166
  • 161