Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #37138 > unrolled thread

Else statement executing when it shouldnt

Started byeli m <techgeek201@gmail.com>
First post2013-01-20 20:40 -0800
Last post2013-01-22 05:44 +1100
Articles 15 on this page of 35 — 13 participants

Back to article view | Back to comp.lang.python


Contents

  Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:40 -0800
    Re: Else statement executing when it shouldnt Roy Smith <roy@panix.com> - 2013-01-20 23:47 -0500
    Re: Else statement executing when it shouldnt Chris Angelico <rosuav@gmail.com> - 2013-01-21 15:52 +1100
      Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:55 -0800
      Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:55 -0800
    Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:54 -0800
      Re: Else statement executing when it shouldnt alex23 <wuwei23@gmail.com> - 2013-01-20 22:00 -0800
        Re: Else statement executing when it shouldnt Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-21 08:04 +0000
    Re: Else statement executing when it shouldnt René Klačan <rene.klacan@gmail.com> - 2013-01-21 05:54 +0100
      Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:57 -0800
        Re: Else statement executing when it shouldnt René Klačan <rene.klacan@gmail.com> - 2013-01-21 06:06 +0100
        Re: Else statement executing when it shouldnt René Klačan <rene.klacan@gmail.com> - 2013-01-21 06:07 +0100
          Re: Else statement executing when it shouldnt Thomas Boell <tboell@domain.invalid> - 2013-01-22 16:39 +0100
            Re: Else statement executing when it shouldnt Chris Angelico <rosuav@gmail.com> - 2013-01-23 02:42 +1100
              Re: Else statement executing when it shouldnt Thomas Boell <tboell@domain.invalid> - 2013-01-22 16:48 +0100
                Re: Else statement executing when it shouldnt Chris Angelico <rosuav@gmail.com> - 2013-01-23 03:07 +1100
                Re: Else statement executing when it shouldnt Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-22 23:22 +0000
                  Re: Else statement executing when it shouldnt René Klačan <rene.klacan@gmail.com> - 2013-01-23 01:34 +0100
                  Re: Else statement executing when it shouldnt Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-01-22 22:11 -0500
                Re: Else statement executing when it shouldnt alex23 <wuwei23@gmail.com> - 2013-01-22 17:28 -0800
                  Re: Else statement executing when it shouldnt Thomas Boell <tboell@domain.invalid> - 2013-01-23 12:22 +0100
                    Re: Else statement executing when it shouldnt Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2013-01-23 15:35 +0200
                      Re: Else statement executing when it shouldnt Jerry Hill <malaclypse2@gmail.com> - 2013-01-23 09:53 -0500
                      Re: Else statement executing when it shouldnt Frank Millman <frank@chagford.com> - 2013-01-25 10:15 +0200
            Re: Else statement executing when it shouldnt Duncan Booth <duncan.booth@invalid.invalid> - 2013-01-22 15:48 +0000
              Re: Else statement executing when it shouldnt Duncan Booth <duncan.booth@invalid.invalid> - 2013-01-22 15:52 +0000
      Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:57 -0800
    Re: Else statement executing when it shouldnt Mitya Sirenef <msirenef@lightbird.net> - 2013-01-20 23:57 -0500
      Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:59 -0800
        Re: Else statement executing when it shouldnt Mitya Sirenef <msirenef@lightbird.net> - 2013-01-21 01:09 -0500
      Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-20 20:59 -0800
        Re: Else statement executing when it shouldnt alex23 <wuwei23@gmail.com> - 2013-01-20 21:46 -0800
    Re: Else statement executing when it shouldnt alex23 <wuwei23@gmail.com> - 2013-01-20 21:56 -0800
      Re: Else statement executing when it shouldnt eli m <techgeek201@gmail.com> - 2013-01-21 07:37 -0800
        Re: Else statement executing when it shouldnt Chris Angelico <rosuav@gmail.com> - 2013-01-22 05:44 +1100

Page 2 of 2 — ← Prev page 1 [2]


#37451

FromThomas Boell <tboell@domain.invalid>
Date2013-01-23 12:22 +0100
Message-ID<20130123122247.43031d2e@sampi>
In reply to#37392
On Tue, 22 Jan 2013 17:28:35 -0800 (PST)
alex23 <wuwei23@gmail.com> wrote:

> On Jan 23, 1:48 am, Thomas Boell <tbo...@domain.invalid> wrote:
> > I must say, that's bound to be confusing for anyone who knows any
> > language other than Python (or none, even).  Syntax like that is "an
> > accident waiting to happen"...
> 
> No, ignorantly expecting every language to conform to every other is
> the pending accident.

Using a keyword that has a well-understood meaning in just about every
other programming language on the planet *and even in English*,
redefining it to mean something completely different, and then making
the syntax look like the original, well-understood meaning -- that's
setting a trap out for users.

The feature isn't bad, it's just very, very badly named.

[toc] | [prev] | [next] | [standalone]


#37462

FromJussi Piitulainen <jpiitula@ling.helsinki.fi>
Date2013-01-23 15:35 +0200
Message-ID<qotbocg58f2.fsf@ruuvi.it.helsinki.fi>
In reply to#37451
Thomas Boell writes:

> Using a keyword that has a well-understood meaning in just about
> every other programming language on the planet *and even in
> English*, redefining it to mean something completely different, and
> then making the syntax look like the original, well-understood
> meaning -- that's setting a trap out for users.
> 
> The feature isn't bad, it's just very, very badly named.

I believe it would read better - much better - if it was "for/then"
and "while/then" instead of "for/else" and "while/else".

I believe someone didn't want to introduce a new keyword for this,
hence "else".

[toc] | [prev] | [next] | [standalone]


#37476

FromJerry Hill <malaclypse2@gmail.com>
Date2013-01-23 09:53 -0500
Message-ID<mailman.899.1358952792.2939.python-list@python.org>
In reply to#37462
On Wed, Jan 23, 2013 at 8:35 AM, Jussi Piitulainen
<jpiitula@ling.helsinki.fi> wrote:
>> The feature isn't bad, it's just very, very badly named.
>
> I believe it would read better - much better - if it was "for/then"
> and "while/then" instead of "for/else" and "while/else".

That's always been my opinion too.  I'd remember how the construct
worked if it was for/then (and while/then).  Since seeing for/else
always makes my brain lock up for a few seconds when I'm reading code,
I don't bother using it.

Jerry

[toc] | [prev] | [next] | [standalone]


#37653

FromFrank Millman <frank@chagford.com>
Date2013-01-25 10:15 +0200
Message-ID<mailman.1030.1359101769.2939.python-list@python.org>
In reply to#37462
On 23/01/2013 15:35, Jussi Piitulainen wrote:
> Thomas Boell writes:
>
>> Using a keyword that has a well-understood meaning in just about
>> every other programming language on the planet *and even in
>> English*, redefining it to mean something completely different, and
>> then making the syntax look like the original, well-understood
>> meaning -- that's setting a trap out for users.
>>
>> The feature isn't bad, it's just very, very badly named.
>
> I believe it would read better - much better - if it was "for/then"
> and "while/then" instead of "for/else" and "while/else".
>
> I believe someone didn't want to introduce a new keyword for this,
> hence "else".
>

There is a scenario, which I use from time to time, where 'else' makes 
perfect sense.

You want to loop through an iterable, looking for 'something'. If you 
find it, you want to do something and break. If you do not find it, you 
want to do something else.

for item in iterable:
     if item == 'something':
         do_something()
         break
else:  # item was not found
     do_something_else()

Not arguing for or against, just saying it is difficult to find one word 
which covers all requirements.

Frank Millman

[toc] | [prev] | [next] | [standalone]


#37290

FromDuncan Booth <duncan.booth@invalid.invalid>
Date2013-01-22 15:48 +0000
Message-ID<XnsA150A0BDECFCEduncanbooth@127.0.0.1>
In reply to#37287
Thomas Boell <tboell@domain.invalid> wrote:

> Huh?! I would have expected all your examples to raise a SyntaxError or
> IndentationError. Why don't they? Is 'else' not required to have a
> matching 'if'?
> 

Matching 'if' or 'for' or 'while'.
See http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

-- 
Duncan Booth http://kupuguy.blogspot.com

[toc] | [prev] | [next] | [standalone]


#37292

FromDuncan Booth <duncan.booth@invalid.invalid>
Date2013-01-22 15:52 +0000
Message-ID<XnsA150A169BB586duncanbooth@127.0.0.1>
In reply to#37290
Duncan Booth <duncan.booth@invalid.invalid> wrote:
> Matching 'if' or 'for' or 'while'.
> 
or of course 'try'.

-- 
Duncan Booth http://kupuguy.blogspot.com

[toc] | [prev] | [next] | [standalone]


#37147

Fromeli m <techgeek201@gmail.com>
Date2013-01-20 20:57 -0800
Message-ID<mailman.721.1358744274.2939.python-list@python.org>
In reply to#37143
On Sunday, January 20, 2013 8:54:13 PM UTC-8, René Klačan wrote:
> You have to break while loop not to execute else branch
> 
> 
> Rene
> 
> 
> 
Can you explain in more detail please.

[toc] | [prev] | [next] | [standalone]


#37145

FromMitya Sirenef <msirenef@lightbird.net>
Date2013-01-20 23:57 -0500
Message-ID<mailman.720.1358744227.2939.python-list@python.org>
In reply to#37138
On 01/20/2013 11:40 PM, eli m wrote:
> 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


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

When a friend succeeds, I die a little.  Gore Vidal

[toc] | [prev] | [next] | [standalone]


#37148

Fromeli m <techgeek201@gmail.com>
Date2013-01-20 20:59 -0800
Message-ID<11a77bd2-c537-4d0b-8af4-99d1f8c252d0@googlegroups.com>
In reply to#37145
> 
> 
> 
> Your else is lined up with while, not with if.
> 
> 
> 
>   -m
> 
> 
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/
> 
> 
> 
> When a friend succeeds, I die a little.  Gore Vidal
Its lined up. It got messed up when i copied the code into the post.

[toc] | [prev] | [next] | [standalone]


#37157

FromMitya Sirenef <msirenef@lightbird.net>
Date2013-01-21 01:09 -0500
Message-ID<mailman.726.1358748565.2939.python-list@python.org>
In reply to#37148
On 01/20/2013 11:59 PM, eli m wrote:
>
 >>
 >>
 >>
 >> Your else is lined up with while, not with if.
 >>
 >>
 >>
 >> -m
 >>
 >>
 >>
 >>
 >>
 >> --
 >>
 >> Lark's Tongue Guide to Python: http://lightbird.net/larks/
 >>
 >>
 >>
 >> When a friend succeeds, I die a little. Gore Vidal
 > 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

[toc] | [prev] | [next] | [standalone]


#37149

Fromeli m <techgeek201@gmail.com>
Date2013-01-20 20:59 -0800
Message-ID<mailman.722.1358744367.2939.python-list@python.org>
In reply to#37145
> 
> 
> 
> Your else is lined up with while, not with if.
> 
> 
> 
>   -m
> 
> 
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/
> 
> 
> 
> When a friend succeeds, I die a little.  Gore Vidal
Its lined up. It got messed up when i copied the code into the post.

[toc] | [prev] | [next] | [standalone]


#37154

Fromalex23 <wuwei23@gmail.com>
Date2013-01-20 21:46 -0800
Message-ID<49b9c29e-362a-4483-8f4f-ea95d27f31df@jl13g2000pbb.googlegroups.com>
In reply to#37149
On Jan 21, 2:59 pm, eli m <techgeek...@gmail.com> wrote:
> 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.

[toc] | [prev] | [next] | [standalone]


#37155

Fromalex23 <wuwei23@gmail.com>
Date2013-01-20 21:56 -0800
Message-ID<d31709f3-a76c-4f49-85ba-16d0e3bde2d6@pd8g2000pbc.googlegroups.com>
In reply to#37138
On Jan 21, 2:40 pm, eli m <techgeek...@gmail.com> wrote:
> 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`.

[toc] | [prev] | [next] | [standalone]


#37205

Fromeli m <techgeek201@gmail.com>
Date2013-01-21 07:37 -0800
Message-ID<1796075c-5b40-4034-ac44-ec33f5c54e67@googlegroups.com>
In reply to#37155
On Sunday, January 20, 2013 9:56:59 PM UTC-8, alex23 wrote:
> On Jan 21, 2:40 pm, eli m <techgeek...@gmail.com> wrote:
> 
> > 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 this is my first time posting on here.

[toc] | [prev] | [next] | [standalone]


#37218

FromChris Angelico <rosuav@gmail.com>
Date2013-01-22 05:44 +1100
Message-ID<mailman.759.1358793859.2939.python-list@python.org>
In reply to#37205
On Tue, Jan 22, 2013 at 2:37 AM, eli m <techgeek201@gmail.com> wrote:
> 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

[toc] | [prev] | [standalone]


Page 2 of 2 — ← Prev page 1 [2]

Back to top | Article view | comp.lang.python


csiph-web