Why does it have red squiggly lines under it if it works perfectlyfine and no errors happen when I r

W

William Bryant

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()
 
I

Ian Kelly

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.
 
P

patrick vrijlandt

John Gordon said:
In <[email protected]> William Bryant



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.
 
D

Dave Angel

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.
 
I

Ian Kelly

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.
 
W

William Bryant

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))
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))
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
 
W

William Bryant

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.

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
 
W

William Bryant

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.

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 statmentto 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. :)
 
S

Steven D'Aprano

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,
 
D

Dave Angel

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
 
M

MRAB

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
 
D

Dave Angel

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.
 
A

alex23

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/
 

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

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,185
Members
46,722
Latest member
NelsonHeil

Latest Threads

Top