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


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

Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it?

Started byWilliam Bryant <gogobebe2@gmail.com>
First post2013-09-19 11:46 -0700
Last post2013-09-23 10:39 +1000
Articles 16 — 10 participants

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


Contents

  Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? William Bryant <gogobebe2@gmail.com> - 2013-09-19 11:46 -0700
    Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? John Gordon <gordon@panix.com> - 2013-09-19 18:51 +0000
      Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? patrick vrijlandt <patrick.vrijlandt@gmail.com> - 2013-09-19 19:08 +0000
    Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? Ian Kelly <ian.g.kelly@gmail.com> - 2013-09-19 13:01 -0600
    Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? Dave Angel <davea@davea.name> - 2013-09-19 20:18 +0000
    Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? Ian Kelly <ian.g.kelly@gmail.com> - 2013-09-19 17:09 -0600
      Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? William Bryant <gogobebe2@gmail.com> - 2013-09-20 00:01 -0700
        Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? William Ray Wing <wrw@mac.com> - 2013-09-20 09:04 -0400
        Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? Duncan Booth <duncan.booth@invalid.invalid> - 2013-09-20 13:39 +0000
          Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? William Bryant <gogobebe2@gmail.com> - 2013-09-20 22:59 -0700
          Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? William Bryant <gogobebe2@gmail.com> - 2013-09-20 23:07 -0700
            Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-09-21 10:25 +0000
            Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? Dave Angel <davea@davea.name> - 2013-09-21 12:53 +0000
            Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? MRAB <python@mrabarnett.plus.com> - 2013-09-21 17:18 +0100
            Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? Dave Angel <davea@davea.name> - 2013-09-21 18:09 +0000
        Re: Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it? alex23 <wuwei23@gmail.com> - 2013-09-23 10:39 +1000

#54434 — Why does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it?

FromWilliam Bryant <gogobebe2@gmail.com>
Date2013-09-19 11:46 -0700
SubjectWhy does it have red squiggly lines under it if it works perfectly fine and no errors happen when I run it?
Message-ID<22b99b0a-598f-4500-9de9-5041c2ce2c8f@googlegroups.com>
the word 'def' has  squiggily lines but the program works fine. It says: Syntax Error: expected an indented block. - why?

def restart():
    print("""

    ~~~~~~~~~~~~~~~~

    Cacluation DONE!

    ~~~~~~~~~~~~~~~~

    """)
    restart = input("\nEnter yes if you want to make a new list and no if you want to close the program (yes/no):  ")
    restart
    if restart == "yes" or restart == "y" or restart == "new list":
        print("You want make a new list...\n")
        time.sleep(1)
        NOS()
    elif restart == "no" or restart == "n" or restart == "close":
        print("Goodbye!")
        time.sleep(1)
        print("Goodbye!")
        time.sleep(1)
        print("Goodbye!")
        time.sleep(1)
        print("Goodbye!")
        time.sleep(1)
        print("Goodbye!")
        time.sleep(1)
        quit()
    else:
        print("type y or n")
        time.sleep(0.5)
        restart()

[toc] | [next] | [standalone]


#54436

FromJohn Gordon <gordon@panix.com>
Date2013-09-19 18:51 +0000
Message-ID<l1fh4f$5bv$1@reader1.panix.com>
In reply to#54434
In <22b99b0a-598f-4500-9de9-5041c2ce2c8f@googlegroups.com> William Bryant <gogobebe2@gmail.com> writes:

> the word 'def' has  squiggily lines but the program works fine. It says:
> Syntax Error: expected an indented block. - why?

> def restart():

This may be caused by the code before 'def'.  Post the whole program.

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

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


#54438

Frompatrick vrijlandt <patrick.vrijlandt@gmail.com>
Date2013-09-19 19:08 +0000
Message-ID<188912050401310416.716816patrick.vrijlandt-gmail.com@newszilla.xs4all.nl>
In reply to#54436
John Gordon <gordon@panix.com> wrote:
> In <22b99b0a-598f-4500-9de9-5041c2ce2c8f@googlegroups.com> William Bryant
> <gogobebe2@gmail.com> writes:
> 
>> the word 'def' has  squiggily lines but the program works fine. It says:
>> Syntax Error: expected an indented block. - why?
> 
>> def restart():
> 
> This may be caused by the code before 'def'.  Post the whole program.

It may also have to do with having both tabs and spaces in one source file.
Python cannot recognise the indentation if you do that. Replace al tabs by
4 spaces.

-- 
patrick

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


#54439

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-09-19 13:01 -0600
Message-ID<mailman.158.1379617747.18130.python-list@python.org>
In reply to#54434
Syntactically, it looks fine.  I would guess the problem is with
whatever editor you are using.  Or as John noted, it could be caused
by the code above it.

I do see an unrelated bug in there, though.  You are using the name
"restart" both for a string entered by the user and for the name of
the function, which is called recursively.  The name for the string,
which is local, shadows the name for the function, which is global.
So if the program ever hits the third branch of the if statement you
will get an error.

Python doesn't optimize tail-recursion, so you would get a different
error if the user hit that branch enough times (around 1000)
consecutively, as the interpreter hits the stack limit.  For example,
if they just held down the Enter key for a while.  So this looping
would be better accomplished with a while True loop and break
statements than with recursion.

On Thu, Sep 19, 2013 at 12:46 PM, William Bryant <gogobebe2@gmail.com> wrote:
> the word 'def' has  squiggily lines but the program works fine. It says: Syntax Error: expected an indented block. - why?
>
> def restart():
>     print("""
>
>     ~~~~~~~~~~~~~~~~
>
>     Cacluation DONE!
>
>     ~~~~~~~~~~~~~~~~
>
>     """)
>     restart = input("\nEnter yes if you want to make a new list and no if you want to close the program (yes/no):  ")
>     restart
>     if restart == "yes" or restart == "y" or restart == "new list":
>         print("You want make a new list...\n")
>         time.sleep(1)
>         NOS()
>     elif restart == "no" or restart == "n" or restart == "close":
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         quit()
>     else:
>         print("type y or n")
>         time.sleep(0.5)
>         restart()
> --
> https://mail.python.org/mailman/listinfo/python-list

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


#54446

FromDave Angel <davea@davea.name>
Date2013-09-19 20:18 +0000
Message-ID<mailman.163.1379621946.18130.python-list@python.org>
In reply to#54434
On 19/9/2013 14:46, William Bryant wrote:

> the word 'def' has  squiggily lines but the program works fine. It says: Syntax Error: expected an indented block. - why?
>

The direct answer is that your terminal program must be broken.  it
should not use "squiggly lines" for any purposes.

But perhaps you're not seeing this in terminal, but in some text editor.
Better specify what that is.

As for the "Syntax Error..."   Better supply the entire traceback.  I
can't see how you consider that error message as "working."

> def restart():

Better give it a different name, since you're using this same name as a
local within the function.

>     print("""
>
>     ~~~~~~~~~~~~~~~~
>
>     Cacluation DONE!
>
>     ~~~~~~~~~~~~~~~~
>
>     """)
>     restart = input("\nEnter yes if you want to make a new list and no if you want to close the program (yes/no):  ")
>     restart

This line does nothing, as has been pointed out before in other
messages. of yours.  You're not printing it, assigning it to something,
calling it, or whatever.

>     if restart == "yes" or restart == "y" or restart == "new list":
>         print("You want make a new list...\n")
>         time.sleep(1)
>         NOS()

There's no such function.

>     elif restart == "no" or restart == "n" or restart == "close":
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         print("Goodbye!")
>         time.sleep(1)
>         quit()

No such function.

>     else:
>         print("type y or n")
>         time.sleep(0.5)
>         restart()

You're using recursion when a simple loop is called for.

-- 
DaveA

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


#54453

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-09-19 17:09 -0600
Message-ID<mailman.168.1379632193.18130.python-list@python.org>
In reply to#54434
On Thu, Sep 19, 2013 at 1:22 PM, William Bryant <gogobebe2@gmail.com> wrote:
> It was the other functions above it. Thanks. but I tried to do the while
> loop - I don't think I did it right, I am novice in python and I am 13 years
> old.

It should be structured like this:

    while True:
        answer = input("Enter yes/no:")
        if answer in ('y', 'yes', 'new list'):
            do_yes_stuff()
            break
        elif answer in ('n', 'no', 'close'):
            do_no_stuff()
            break
        else:
            print("Please enter y or n.")

If they answer 'yes' or 'no', then the break statement breaks out of
the while loop.  Otherwise the while loop continues from the top and
asks them again.

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


#54460

FromWilliam Bryant <gogobebe2@gmail.com>
Date2013-09-20 00:01 -0700
Message-ID<24104d3b-ad83-4c15-bb9e-77b61a0bac78@googlegroups.com>
In reply to#54453
On Friday, September 20, 2013 11:09:03 AM UTC+12, Ian wrote:
> On Thu, Sep 19, 2013 at 1:22 PM, William Bryant <gogobebe2@gmail.com> wrote:
> 
> > It was the other functions above it. Thanks. but I tried to do the while
> 
> > loop - I don't think I did it right, I am novice in python and I am 13 years
> 
> > old.
> 
> 
> 
> It should be structured like this:
> 
> 
> 
>     while True:
> 
>         answer = input("Enter yes/no:")
> 
>         if answer in ('y', 'yes', 'new list'):
> 
>             do_yes_stuff()
> 
>             break
> 
>         elif answer in ('n', 'no', 'close'):
> 
>             do_no_stuff()
> 
>             break
> 
>         else:
> 
>             print("Please enter y or n.")
> 
> 
> 
> If they answer 'yes' or 'no', then the break statement breaks out of
> 
> the while loop.  Otherwise the while loop continues from the top and
> 
> asks them again.

Thanks a lot! I have one more question, is there any way I can make my program work on android tablets and ipads? Because I'd like to use it in school because we are learning statistics and we are allowed our devices in school.


'''**************************************************************************'''
#* Name:        Mode-Median-Mean Calculator                                   *#
#*                                                                            *#
#* Purpose:     To calculate the mode, median and mean of a list of numbers   *#
#*              and the mode of a list of strings because that is what we are *#
#*              learning in math atm in school :P                             *#
#*                                                                            *#
#* Author:      William Bryant                                                *#
#*                                                                            *#
#* Created:     11/09/2013                                                    *#
#*                                                                            *#
#* Copyright:   (c) William 2013                                              *#
#*                                                                            *#
#* Licence:     IDK :3                                                        *#
'''**************************************************************************'''



#-----#                   ~~Import things I am using~~                   #-----#

#         |
#        |
#       \/

import time
import itertools



#-----#        ~~Variables that I am using, including the list.~~        #-----#

#         |
#        |
#       \/

List = []
NumberOfXItems = []

#-----#                   ~~Functions that I am using.~~                 #-----#

#         |
#        |
#       \/

def HMNs():
    global TheStr, user_inputHMNs, List_input, List
    user_inputHMNs = input("You picked string. This program cannot calculate the mean or median, but it can calculate the mode. :D  How many strings are you using in your list? (Can not be a decimal number)  \nEnter:  ")
    if user_inputHMNs == "restart":
        NOS()
    time.sleep(1.5)
    TheStr = int(user_inputHMNs)
    for i in range(TheStr):
        List_input = input("Enter your strings. (One in each input field):  \n")
        if List_input == "restart":
            NOS()
        List.append(List_input)
        print("############################################################################\nThis is the amount of strings you are using in your list:", user_inputHMNs)
        print("and this is how much space you have left in your list for strings:", int(user_inputHMNs) - len(List), "\n################################################################################\n")
        print("Your list -> ", List)
        print("(0 is the first number in your list)\n")
        for i in range(len(List)):
            print("number " + str(i) + ": " + str(List[i]))
        print("\n*Mode*:", mode())
        print("*Median*:",  "There is no median for a list of strings - Only mode")
        print("*Mean*:",    "There is no mean for a list of strings - Only mode")
        if int(user_inputHMNs) - len(List) == 0:
            init()


def HMNn():
    global TheNum, user_inputHMNn, List_input, List
    user_inputHMNn = input("You picked number. :D How many numbers are you using in your list? (Can not be a decimal number) \nEnter:  ")
    if user_inputHMNn == "restart":
        NOS()
    time.sleep(1.5)
    TheNum = int(user_inputHMNn)
    for i in range(TheNum):
        List_input = input("Enter your numbers. (One in each input field):  \n")
        List_input = int(List_input)
        if List_input == "restart":
            NOS()
        List.append(List_input)
        print("############################################################################\nThis is the amount of numbers you are using in your list:", user_inputHMNn)
        print("and this is how much space you have left in your list for numbers:", int(user_inputHMNn) - len(List), "\n################################################################################\n")
        print("Your list -> ", List)
        print("(0 is the first number in your list)\n")
        for i in range(len(List)):
            print("number " + str(i) + ": " + str(List[i]))
        print("\n*Mode*:", mode())
        print("*Median*:",  "<Coming soon!>")
        print("*Mean*:",    mean(), "\n")
        if int(user_inputHMNn) - len(List) == 0:
            init()

def NOS():
    print("Loading...\n")
    time.sleep(2.5)
    while True: # Loops forever (until the break)
        answer = input("Does your list contain a number or a string?  \nEnter: ")
        answer = answer.lower()
        if answer in ("string", "str", "s"):
            HMNs()
            break
        elif answer in ("number", "num", "n", "int"):
            HMNn()
            break
        elif answer in ("quit", "q"):
            break  # Exits the while loop
        else:
            print("You did not enter a valid field, :P Sorry.  \nEnter: ")
    time.sleep(1.5)
    if answer == "restart":
        NOS()
def mean():
    thesum = sum(List)
    amount = len(List)
    themean = thesum / amount
    return themean

def mode():
    max_occurrences = 0
    themode = None
    for i in List:
        thecount = List.count(i)
        if thecount > max_occurrences:
            max_occurrences = thecount
            themode = i
    return themode

def median():
    pass

def init():
    print("""

    ~~~~~~~~~~~~~~~~

    Cacluation DONE!

    ~~~~~~~~~~~~~~~~

    """)
    while "lol" == "lol":
        restart = input("\nEnter yes if you want to make a new list and no if you want to close the program (yes/no):  ")
        if restart in ('y', 'yes', 'new list'):
            print("You want make a new list...\n")
            time.sleep(1)
            NOS()
            break
        elif restart in ('n', 'no', 'close'):
            for i in range(6):
                print("""Goodbye! Thanks you for using my program!
                         - William Bryant (AKA gogobebe2)""")
                time.sleep(1)
            quit()
        else:
            print("type y or n")
            time.sleep(0.5)
            init()
#-----#               ~~The functions which need calling~~               #-----#

#         |
#        |
#       \/

NOS()



Thanks again - Will 

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


#54470

FromWilliam Ray Wing <wrw@mac.com>
Date2013-09-20 09:04 -0400
Message-ID<mailman.179.1379682321.18130.python-list@python.org>
In reply to#54460
On Sep 20, 2013, at 3:01 AM, William Bryant <gogobebe2@gmail.com> wrote:

[byte]

> 
> Thanks a lot! I have one more question, is there any way I can make my program work on android tablets and ipads? Because I'd like to use it in school because we are learning statistics and we are allowed our devices in school.
> 
> 

[byte]

> 
> Thanks again - Will 
> 

Python doesn't come pre-installed on tablets the way it does on most computers.  However, there are low-cost commercial python apps for tablets.  The one I'm most familiar with is Pythonista, available for the iPad in the Apple App store.  Last time I looked it was $6.95.

Bill

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


#54473

FromDuncan Booth <duncan.booth@invalid.invalid>
Date2013-09-20 13:39 +0000
Message-ID<XnsA241951725F1Cduncanbooth@127.0.0.1>
In reply to#54460
William Bryant <gogobebe2@gmail.com> wrote:

> Thanks a lot! I have one more question, is there any way I can make my
> program work on android tablets and ipads? Because I'd like to use it
> in school because we are learning statistics and we are allowed our
> devices in school. 
> 

You can install SL4A on Android and that should let you run your script on 
an Android tablet. You may want to modify the script to work with the 
android UI, or it might be enough just to run it in a terminal window.

I don't believe there is an ipad equivalent, but so long as you have a 
network connection, another option to consider (that would work on both 
android and ipad) would be to run the script on a server somewhere and 
connect to it through a web browser. Have a look at https://c9.io as that 
gives you a full development environment that can be accessed through a web 
browser: I don't know how well it works on a tablet but it would be worth 
trying.


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

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


#54532

FromWilliam Bryant <gogobebe2@gmail.com>
Date2013-09-20 22:59 -0700
Message-ID<017a5d0b-1e76-4a0f-94ad-03c6e7a00d57@googlegroups.com>
In reply to#54473
On Saturday, September 21, 2013 1:39:41 AM UTC+12, Duncan Booth wrote:
> William Bryant <gogobebe2@gmail.com> wrote:
> 
> 
> 
> > Thanks a lot! I have one more question, is there any way I can make my
> 
> > program work on android tablets and ipads? Because I'd like to use it
> 
> > in school because we are learning statistics and we are allowed our
> 
> > devices in school. 
> 
> > 
> 
> 
> 
> You can install SL4A on Android and that should let you run your script on 
> 
> an Android tablet. You may want to modify the script to work with the 
> 
> android UI, or it might be enough just to run it in a terminal window.
> 
> 
> 
> I don't believe there is an ipad equivalent, but so long as you have a 
> 
> network connection, another option to consider (that would work on both 
> 
> android and ipad) would be to run the script on a server somewhere and 
> 
> connect to it through a web browser. Have a look at https://c9.io as that 
> 
> gives you a full development environment that can be accessed through a web 
> 
> browser: I don't know how well it works on a tablet but it would be worth 
> 
> trying.
> 
> 
> 
> 
> 
> -- 
> 
> Duncan Booth http://kupuguy.blogspot.com

Ok thanks for that, I know I said 1 more question but I just made the median function, could u tell me how I could finish it? I can't think of a way:

def median():
    medlist = List
    medlist.sort()
    if len(List) % 2:
        while len(list) > 2:
            medlist.popleft()
            medlist.popright()
        if medlist[0] == medlist[1]:
            themedian = medlist
        elif medlist[0] != medlist[1]:
            #make an if statment to figure out the median if the last 2 left are not the same. Eg [1, 2] the middle value is 1.5
            pass
    else:
        while len(medlist) > 1:
            medlist.popleft()
            medlist.popright()
        themedian = medlist
    return themedian

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


#54533

FromWilliam Bryant <gogobebe2@gmail.com>
Date2013-09-20 23:07 -0700
Message-ID<5398c4af-1692-4b7f-9f39-ea392d24199b@googlegroups.com>
In reply to#54473
On Saturday, September 21, 2013 1:39:41 AM UTC+12, Duncan Booth wrote:
> William Bryant <gogobebe2@gmail.com> wrote:
> 
> 
> 
> > Thanks a lot! I have one more question, is there any way I can make my
> 
> > program work on android tablets and ipads? Because I'd like to use it
> 
> > in school because we are learning statistics and we are allowed our
> 
> > devices in school. 
> 
> > 
> 
> 
> 
> You can install SL4A on Android and that should let you run your script on 
> 
> an Android tablet. You may want to modify the script to work with the 
> 
> android UI, or it might be enough just to run it in a terminal window.
> 
> 
> 
> I don't believe there is an ipad equivalent, but so long as you have a 
> 
> network connection, another option to consider (that would work on both 
> 
> android and ipad) would be to run the script on a server somewhere and 
> 
> connect to it through a web browser. Have a look at https://c9.io as that 
> 
> gives you a full development environment that can be accessed through a web 
> 
> browser: I don't know how well it works on a tablet but it would be worth 
> 
> trying.
> 
> 
> 
> 
> 
> -- 
> 
> Duncan Booth http://kupuguy.blogspot.com

Ok thanks for that, I know I said one more question, but could you pleasse help me here:

def median():
    medlist = List
    medlist.sort()
    if len(medlist) % 2:
        while len(medlist) > 2:
            medlist.popleft()
            medlist.popright()
        if medlist[0] == medlist[1]:
            themedian = medlist
        elif medlist[0] != medlist[1]:
            #make an if statment to figure out the median if the last 2 left are not the same. Eg [1, 2] the middle value is 1.5
            pass
    else:
        while len(medlist) > 1:
            medlist.popleft()
            medlist.popright()
        themedian = medlist
    return themedian

It says out of range and i don't know how I am going to make an if statment to figure out the median if the last 2 left are not the same. Eg [1, 2] the middle value is 1.5. Thanks - I am 13 year old beginner in python and i am trying to finish the tutorial on code academy and read the docs. :)

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


#54546

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-09-21 10:25 +0000
Message-ID<523d7419$0$29988$c3e8da3$5496439d@news.astraweb.com>
In reply to#54533
On Fri, 20 Sep 2013 23:07:57 -0700, William Bryant wrote:

> I am 13 year old beginner in
> python and i am trying to finish the tutorial on code academy and read
> the docs. :)

Hi William, 

I think this is about the fifth or sixth time you've told us this. I'm 
really pleased that a youngster like you is learning to program, but you 
don't have to apologise for your youth in every second email, you're 
starting to make us oldies jealous :-) 

Perhaps when you start a new question, it's okay to remind us. But if 
you're a regular here, we'll soon learn your level of experience.


> def median():
>     medlist = List
>     medlist.sort()
>     if len(medlist) % 2:
>         while len(medlist) > 2:
>             medlist.popleft()
>             medlist.popright()
>         if medlist[0] == medlist[1]:
>             themedian = medlist
>         elif medlist[0] != medlist[1]:
>             #make an if statment to figure out the median if the last 2
>             left are not the same. Eg [1, 2] the middle value is 1.5
>             pass
>     else:
>         while len(medlist) > 1:
>             medlist.popleft()
>             medlist.popright()
>         themedian = medlist
>     return themedian
> 
> It says out of range

If you're going to be a coder, for fun or profit, there are some skills 
you need to learn. One of those skills is to copy and paste the whole 
traceback, not just paraphrase the error message at the end. In this 
case, I can guess what is going wrong without seeing the whole traceback, 
but in general it is best to copy everything from the line

Traceback (most recent call last)

to the end of the error message.

In this case, there is a better approach to calculating the median. Start 
by thinking about how you would calculate it by hand:

* sort the numbers;
* if there is an odd number of items, pick the middle one;
* otherwise pick the two middle ones and take the average.

Python can do the same thing. There's no need to delete items one by one 
from the ends of the list until there are only one, or two left. If you 
have a million items, that would be terribly slow...

So, here we go:

def median():
    # Relies on the global variable called List.
    List.sort()
    n = len(List)
    if n % 2 == 1:
        # Odd number of items.
        return List[n//2]
    else:
        a = List[n//2 - 1]
        b = List[n//2]
        return (a + b)/2.0


There's a couple of useful things to learn from this:

1) In a couple of places, you'll see n//2, which looks like division but 
with the / doubled. This is not a typo! It performs integer division, 
throwing away any remainder instead of giving you a fraction. So:

21//7 => 3

22//7 => 3


2) You'll also see a few places where I say List[...] with something 
inside the square brackets. This is looking into the list to grab 
whatever element is in the position. For example:

>>> L = [100, 110, 120, 130]
>>> L[0]  # List indexes start from zero, not one
100
>>> L[1]
110
>>> L[2]
120
>>> L[3]
130


So you can look up the element at any position inside a list in a single 
operation, without needing to throw elements away first. Just remember to 
start counting at zero, not one!


3) Last but not least, the last line divides by 2.0 instead of 2. Why 
2.0? Unfortunately, older versions of Python treat single-slash 
division / differently depending on whether the values have a decimal 
point or not. This was a bad design, and Python 3 has fixed that, but I 
don't know whether you have Python 2 or Python 3. So to be safe, I divide 
by 2.0 to ensure that it calculates the right answer no matter what 
version you are using.



Regards,



-- 
Steven

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


#54553

FromDave Angel <davea@davea.name>
Date2013-09-21 12:53 +0000
Message-ID<mailman.225.1379768042.18130.python-list@python.org>
In reply to#54533
On 21/9/2013 02:07, William Bryant wrote:

In addition to Steven's comments:

>
> def median():
>     medlist = List
>     medlist.sort()

You have just altered the original list.  Perhaps sorting it is
harmless, but below you actually remove elements from it.  One way to
avoid that is to use the sorted() method, which creates a new list.

>     if len(medlist) % 2:

This then is the "odd" size branch of code.  I think you intended to do
the reverse if-test.  A comment would be in order.

>         while len(medlist) > 2:
>             medlist.popleft()
>             medlist.popright()

At this point, there is exactly one item left in the list.  So the code
below is going to get into trouble.

>         if medlist[0] == medlist[1]:
>             themedian = medlist

Is the return value of this function supposed to be a list, or a float? 
If a float, then you should be doing something like:
               themedian = medlist[0]

>         elif medlist[0] != medlist[1]:
>             #make an if statment to figure out the median if the last 2 left are not the same. Eg [1, 2] the middle value is 1.5
>             pass
>     else:
>         while len(medlist) > 1:
>             medlist.popleft()
>             medlist.popright()
>         themedian = medlist
>     return themedian
>
> It says out of range and i don't know how I am going to make an if statment to figure out the median if the last 2 left are not the same. Eg [1, 2] the middle value is 1.5. Thanks - I am 13 year old beginner in python and i am trying to finish the tutorial on code academy and read the docs. :)

Taking Steven's suggested code, and changing it so it uses a COPY of the
global list;

def median():
    # Relies on the global variable called List.
    # assumes there is at least one number in that list
    numbers = List.sorted()
    n = len(numbers)
    if n % 2 == 1:
        # Odd number of items.
        return numbers[n//2]
    else:
        a = numbers[n//2 - 1]
        b = numbers[n//2]
        return (a + b)/2.0

-- 
DaveA

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


#54559

FromMRAB <python@mrabarnett.plus.com>
Date2013-09-21 17:18 +0100
Message-ID<mailman.229.1379780313.18130.python-list@python.org>
In reply to#54533
On 21/09/2013 13:53, Dave Angel wrote:
[snip]
> Taking Steven's suggested code, and changing it so it uses a COPY of the
> global list;
>
> def median():
>      # Relies on the global variable called List.
>      # assumes there is at least one number in that list
>      numbers = List.sorted()

That should be:

      numbers = sorted(List)

>      n = len(numbers)
>      if n % 2 == 1:
>          # Odd number of items.
>          return numbers[n//2]
>      else:
>          a = numbers[n//2 - 1]
>          b = numbers[n//2]
>          return (a + b)/2.0
>

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


#54561

FromDave Angel <davea@davea.name>
Date2013-09-21 18:09 +0000
Message-ID<mailman.230.1379786985.18130.python-list@python.org>
In reply to#54533
On 21/9/2013 12:18, MRAB wrote:

> On 21/09/2013 13:53, Dave Angel wrote:
> [snip]
>> Taking Steven's suggested code, and changing it so it uses a COPY of the
>> global list;
>>
>> def median():
>>      # Relies on the global variable called List.
>>      # assumes there is at least one number in that list
>>      numbers = List.sorted()
>
> That should be:
>
>       numbers = sorted(List)

OOPS.  Thanks, you're so right.

-- 
DaveA

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


#54601

Fromalex23 <wuwei23@gmail.com>
Date2013-09-23 10:39 +1000
Message-ID<l1o2jh$sjn$1@dont-email.me>
In reply to#54460
On 20/09/2013 5:01 PM, William Bryant wrote:
> I have one more question, is there any way I can make my program work on android tablets and ipads? Because I'd like to use it in school because we are learning statistics and we are allowed our devices in school.

I'd recommend taking a look at kivy, it supports both Android & iOS (as 
well as Windows, Mac, Linux):

http://kivy.org/

[toc] | [prev] | [standalone]


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


csiph-web