Else statement executing when it shouldnt


E

eli m

an else statement is running when it shouldnt be. It is on the last line. Whenever i am in the math or game function, when i type in main, it goes back to the start of the program, but it also says not a valid function. I am stumped!
Here is my code:
#Cmd
#Created By Eli M.
#import modules
import random
import math
gtn = 0
print ("Type in help for a list of cmd functions")
#initiate main loop
cmd = 0
while cmd == 0:
#ask for input on function
function = raw_input("Type in a function:")
#start math loop
if function == "math":
run = 0
while run == 0:
#ask for math operation
type = raw_input("What math operation do you want to use?")
if type == "multiplication":
x = raw_input("Type in your first number:")
y = raw_input("Multiply your first number by:")
try:
ans = int(x) * int(y)
print (ans)
try:
ans = float(x) * float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#division math function
if type == "division":
x = raw_input("Type in your first number:")
y = raw_input("Divide your first number by:")
try:
ans = float(x) / float(y)
print (ans)
except ZeroDivisionError, err:
print ("Can't divide by zero")
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#subtraction math function
if type == "subtraction":
x = raw_input("Type in your first number:")
y = raw_input("Subtract your first number by:")
try:
ans = float(x) - float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
#addition math function
if type == "addition":
x = raw_input("Type in your first number:")
y = raw_input("Add your first number by:")
try:
ans = float(x) + float(y)
print (ans)
except ValueError, err:
try:
ans = int(x) + int(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#square root math function
if type == "square root":
x = raw_input("Type in your number:")
try:
y = float(x)
z = math.sqrt(y)
print (z)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")

#to the power of... math function
if type == "power":
x = raw_input("Type in your number:")
y = raw_input("Multiply your first number by the power of:")
try:
ans = float(x) ** float(y)
print (ans)
except OverflowError, err:
print ("Number too large")
except ValueError, err:
print ("Not a valid number")
#break the math loop
if type == "main":
run = 1
#absolute value math function
if type == "absolute value":
try:
x = float(raw_input("Type in your number:"))
y = math.fabs(x)
print (y)
except ValueError, err:
print ("Not a valid number")
if function == "random number":
try:
x = int(raw_input("Minimum number:"))
y = int(raw_input("Maximum number:"))
num = random.randint(x, y)
print (num)
except ValueError, err:
print ("Not a valid number")
if function == "games":
games = 0
while games == 0:
gamechoice = raw_input("What game do you want to play:")
if gamechoice == "guess the number":
run = 0
while run == 0:
print ("I am thinking of a number between 1 and 20")
num = random.randint(1, 20)
num = int(num)
guesses = 0
guessestaken = 0
while guesses == 0:
try:
guess = raw_input("Your guess:")
guess = int(guess)
guessestaken = (guessestaken) + 1
guessestaken = int(guessestaken)
if guess == (num):
print 'Correct! It took you', int(guessestaken), 'guesses!'
playagain = raw_input("Do you want to play again?")
if playagain == "yes":
guesses = 1
if playagain == "no":
run = 1
guesses = 1
if guess > num:
print ("My number is lower")
if guess < num:
print ("My number is higher")
except TypeError, err:
print ("Not a valid number")
if gamechoice == "main":
games = 1

#help function
if function == "help":
helpfunc = 0
while helpfunc == 0:
#show functions
print ("Functions:")
print ("Math: multiplication, division, subtraction, addition, square root, power, absolute value")
print ("Random Number")
print ("Games: Guess the number")
helpmain = raw_input("Type in main to go back")
if helpmain == "main":
#end helpfunction loop
helpfunc = 1
cmd = 0
else:
print ("Not a valid function")
 
Ad

Advertisements

R

Roy Smith

eli m said:
an else statement is running when it shouldnt be. It is on the last line.
Whenever i am in the math or game function, when i type in main, it goes back
to the start of the program, but it also says not a valid function. I am
stumped!
Here is my code:

[many lines of code elided]

TL;DNR :)

A basic debugging technique is to try to find the minimum amount of code
that can reproduce the problem.

Find some hunk of lines that you're pretty sure can't be at fault, and
delete them. See if you can still reproduce the problem. Assuming you
can, delete another hunk of code. Keep going until you're down to the
smallest possible amount of code which demonstrates the problem.

There's a couple of good things that come out of this. One is that it's
likely that in the course of doing this, you'll figure out what's wrong.
The other is that if you can't figure it out, at least now you'll have
something that's easy to show somebody else when you ask for help.
 
C

Chris Angelico

an else statement is running when it shouldnt be. It is on the last line. Whenever i am in the math or game function, when i type in main, it goes back to the start of the program, but it also says not a valid function. I am stumped!

Check your indentation levels. I see a few things here that look odd:
if function == "help":
while helpfunc == 0:
if helpmain == "main":
else:

What is the else meant to bind to? The innermost if? The 'if function
== "help"'? It's currently binding to the while.

Recommendation: Break this up! Your main loop is huge! It's way too
easy to get lost in it. And while you're at it, consider unifying some
of the similar blocks of code. The solution to both issues is simple:
Use functions. Have you been taught about them yet?

Also, side tip: Be honest about homework. I'm fairly sure that's what
this is. :)

ChrisA
 
E

eli m

Check your indentation levels. I see a few things here that look odd:









What is the else meant to bind to? The innermost if? The 'if function

== "help"'? It's currently binding to the while.



Recommendation: Break this up! Your main loop is huge! It's way too

easy to get lost in it. And while you're at it, consider unifying some

of the similar blocks of code. The solution to both issues is simple:

Use functions. Have you been taught about them yet?



Also, side tip: Be honest about homework. I'm fairly sure that's what

this is. :)



ChrisA

Its not homework. It is a personal project.
 
E

eli m

Check your indentation levels. I see a few things here that look odd:









What is the else meant to bind to? The innermost if? The 'if function

== "help"'? It's currently binding to the while.



Recommendation: Break this up! Your main loop is huge! It's way too

easy to get lost in it. And while you're at it, consider unifying some

of the similar blocks of code. The solution to both issues is simple:

Use functions. Have you been taught about them yet?



Also, side tip: Be honest about homework. I'm fairly sure that's what

this is. :)



ChrisA

Its not homework. It is a personal project.
 
Ad

Advertisements

M

Mitya Sirenef

an else statement is running when it shouldnt be. It is on the last line. Whenever i am in the math
or game function, when i type in main, it goes back to the start of the
program, but it also says not a valid function. I am stumped!
Here is my code:
#Cmd
#Created By Eli M.
#import modules
import random
import math
gtn = 0
print ("Type in help for a list of cmd functions")
#initiate main loop
cmd = 0
while cmd == 0:
#ask for input on function
function = raw_input("Type in a function:")
#start math loop
if function == "math":
run = 0
while run == 0:
#ask for math operation
type = raw_input("What math operation do you want to use?")
if type == "multiplication":
x = raw_input("Type in your first number:")
y = raw_input("Multiply your first number by:")
try:
ans = int(x) * int(y)
print (ans)
try:
ans = float(x) * float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#division math function
if type == "division":
x = raw_input("Type in your first number:")
y = raw_input("Divide your first number by:")
try:
ans = float(x) / float(y)
print (ans)
except ZeroDivisionError, err:
print ("Can't divide by zero")
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#subtraction math function
if type == "subtraction":
x = raw_input("Type in your first number:")
y = raw_input("Subtract your first number by:")
try:
ans = float(x) - float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
#addition math function
if type == "addition":
x = raw_input("Type in your first number:")
y = raw_input("Add your first number by:")
try:
ans = float(x) + float(y)
print (ans)
except ValueError, err:
try:
ans = int(x) + int(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#square root math function
if type == "square root":
x = raw_input("Type in your number:")
try:
y = float(x)
z = math.sqrt(y)
print (z)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")

#to the power of... math function
if type == "power":
x = raw_input("Type in your number:")
y = raw_input("Multiply your first number by the power of:")
try:
ans = float(x) ** float(y)
print (ans)
except OverflowError, err:
print ("Number too large")
except ValueError, err:
print ("Not a valid number")
#break the math loop
if type == "main":
run = 1
#absolute value math function
if type == "absolute value":
try:
x = float(raw_input("Type in your number:"))
y = math.fabs(x)
print (y)
except ValueError, err:
print ("Not a valid number")
if function == "random number":
try:
x = int(raw_input("Minimum number:"))
y = int(raw_input("Maximum number:"))
num = random.randint(x, y)
print (num)
except ValueError, err:
print ("Not a valid number")
if function == "games":
games = 0
while games == 0:
gamechoice = raw_input("What game do you want to play:")
if gamechoice == "guess the number":
run = 0
while run == 0:
print ("I am thinking of a number between 1 and 20")
num = random.randint(1, 20)
num = int(num)
guesses = 0
guessestaken = 0
while guesses == 0:
try:
guess = raw_input("Your guess:")
guess = int(guess)
guessestaken = (guessestaken) + 1
guessestaken = int(guessestaken)
if guess == (num):
print 'Correct! It took you', int(guessestaken), 'guesses!'
playagain = raw_input("Do you want to play again?")
if playagain == "yes":
guesses = 1
if playagain == "no":
run = 1
guesses = 1
if guess > num:
print ("My number is lower")
if guess < num:
print ("My number is higher")
except TypeError, err:
print ("Not a valid number")
if gamechoice == "main":
games = 1

#help function
if function == "help":
helpfunc = 0
while helpfunc == 0:
#show functions
print ("Functions:")
print ("Math: multiplication, division, subtraction, addition, square root, power, absolute value")
print ("Random Number")
print ("Games: Guess the number")
helpmain = raw_input("Type in main to go back")
if helpmain == "main":
#end helpfunction loop
helpfunc = 1
cmd = 0
else:
print ("Not a valid function")


Your else is lined up with while, not with if.

-m
 
Ad

Advertisements

R

René KlaÄan

Examples:

# else branch will be executed
i = 0
while i < 5:
i += 1
else:
print('loop is over')


# else branch will be executed
i = 0
while i < 5:
i += 1
if i == 7:
print('i == 7')
break
else:
print('loop is over')


# else branch wont be executed
i = 0
while i < 5:
i += 1
if i == 3:
print('i == 3')
break
else:
print('loop is over')
 
R

René KlaÄan

Examples:

# else branch will be executed
i = 0
while i < 5:
i += 1
else:
print('loop is over')


# else branch will be executed
i = 0
while i < 5:
i += 1
if i == 7:
print('i == 7')
break
else:
print('loop is over')


# else branch wont be executed
i = 0
while i < 5:
i += 1
if i == 3:
print('i == 3')
break
else:
print('loop is over')
 
A

alex23

Its lined up. It got messed up when i copied the code into the post.

Sorry, we're not going to take your word for it. Reduce it to the
minimal amount of code that reproduces your error and post that.
 
A

alex23

an else statement is running when it shouldnt be. It is
on the last line. Whenever i am in the math or game
function, when i type in main, it goes back to the start
of the program, but it also says not a valid function.
I am stumped!

Here is your code with the irrelevancy stripped away:

function = raw_input("Type in a function:")
#start math loop
if function == "math":
#math code
if function == "random number":
#random code
if function == "games":
#games code
if function == "help":
#help code
else:
print ("Not a valid function")

Say you enter 'math'. It passes the first condition, so runs the math
code.
It then fails on the next 3 conditions, the last of which has an else,
so if you type _anything_ other than 'help', you'll see "Not a valid
function".

Easy answer, use `elif` ("else if") instead of else for the subsequent
tests:

if function == "math":
#math code
elif function == "random number":
#random code
elif function == "games":
#games code
elif function == "help":
#help code
else:
print ("Not a valid function")

Better answer: read up on real functions, and look into dictionary
dispatch:

def f_math():
#math code

def f_random_number():
#random code

<etc>

function_dispatcher = {
'math': f_math,
'random number': f_random_number,
<etc>
}

while cmd == 0:
function_name = raw_input("Type in a function:")
if function_name in function_dispatcher:
function_dispatcher[function_name]()
else:
print("Not a valid function")

To have your functions break out of the loop, use a `global` variable
or pass a context object into each function to allow them to set
`cmd`.
 
A

alex23

hint: Use the comments in the code to find out where my error is.

Pro-tip: when people you're asking for help tell you how you can make
it easier for them to help you, a snide response isn't the correct
approach.
 
Ad

Advertisements

M

Mitya Sirenef

Its lined up. It got messed up when i copied the code into the post.

I would recommend using while True: and break vs. while var: as you
have. In most cases while True: works better, especially in case of long
and/or nested 'while' loops, as you have.

'while True' blocks have two advantages: 1. you can break the loop at
any location and 2. when looking at the code, you can tell on which
condition it breaks by looking at the break line.

Even more importantly, break it up into a few functions. The code as you
have it is too hard to work with and to debug.

It's hard to tell what your 'else' is lined up to, or whether some other
lines are mis-aligned, as well.

Generally, try to avoid making a loop if it's 20+ lines; if there are
nested loops, it makes things even worse. Compare:

if something:
while True:
if not process(): break

def process():
[... 20 lines that loop ...]
[ return None to break the loop ]

Now this is really clear, because just by looking at the first three
lines, I know what the loop is supposed to do (process something), that
it continues looping until it returns a false value; when looking at
the function body I don't need to care which block it aligns to, I
already know the entire function body is in the while loop.

HTH, -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The irrational in the human has something about it altogether repulsive and
terrible, as we see in the maniac, the miser, the drunkard or the ape.
George Santayana
 
S

Steven D'Aprano

Pro-tip: when people you're asking for help tell you how you can make it
easier for them to help you, a snide response isn't the correct
approach.

Alex, thank you for saying this. I can now delete my *much* less polite
version saying the same thing.
 
E

eli m

an else statement is running when it shouldnt be. It is
on the last line. Whenever i am in the math or game
function, when i type in main, it goes back to the start
of the program, but it also says not a valid function.
I am stumped!



Here is your code with the irrelevancy stripped away:



function = raw_input("Type in a function:")

#start math loop

if function == "math":

#math code

if function == "random number":

#random code

if function == "games":

#games code

if function == "help":

#help code

else:

print ("Not a valid function")



Say you enter 'math'. It passes the first condition, so runs the math

code.

It then fails on the next 3 conditions, the last of which has an else,

so if you type _anything_ other than 'help', you'll see "Not a valid

function".



Easy answer, use `elif` ("else if") instead of else for the subsequent

tests:



if function == "math":

#math code

elif function == "random number":

#random code

elif function == "games":

#games code

elif function == "help":

#help code

else:

print ("Not a valid function")



Better answer: read up on real functions, and look into dictionary

dispatch:



def f_math():

#math code



def f_random_number():

#random code



<etc>



function_dispatcher = {

'math': f_math,

'random number': f_random_number,

<etc>

}



while cmd == 0:

function_name = raw_input("Type in a function:")

if function_name in function_dispatcher:

function_dispatcher[function_name]()

else:

print("Not a valid function")



To have your functions break out of the loop, use a `global` variable

or pass a context object into each function to allow them to set

`cmd`.

Thank you, that solved my problem. Sorry for my posts, i am a noob and thisis my first time posting on here.
 
Ad

Advertisements

C

Chris Angelico

Thank you, that solved my problem. Sorry for my posts, i am a noob and this is my first time posting on here.

There's nothing wrong with being a noob, we all start out that way.
Want to be one of the people we love to help? Here are some tips:

http://www.catb.org/esr/faqs/smart-questions.html

It's longish, but you'll find it helpful. The principles laid out in
that document govern pretty much every geeky forum, and a good number
of others besides.

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top