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.