I'm brand new to coding and python. Could someone tell me what is wrong with my code?

def getlist():
     lst=[]
     answer1 = raw_input ("Would you like to add a number to create your mean value? y/n")
     if (answer1 == "y"):
          x = input ("Your number:")
          lst = lst + [x]
     return lst

def mean(l):
   return float(sum(l))/len(l)

a=mean(getList())
print a

Dani AI

Generated

A few things to check beyond the NameError that @neo and already pointed out (Python is case sensitive):

  • If you run the script under Python 2, avoid using input() for raw user text: it evaluates the input. Use raw_input() (or write code that works in both 2 and 3) and convert to float or int with a try/except to catch bad input.
  • Guard against an empty list before dividing — calling sum(...) / len(...) on an empty list raises a ZeroDivisionError.
  • In Python 2, integer division can silently truncate results. Either convert one operand to float or use from __future__ import division to get true division semantics.

A compact, robust pattern that avoids repeated prompts and validates input is to accept a single line of space-separated numbers, parse them with float() inside a try/except, and then compute the mean only if there are numbers:

from __future__ import division

def read_numbers_line(prompt="Enter numbers separated by spaces: "):
    try:
        s = raw_input(prompt)   # Python 2
    except NameError:
        s = input(prompt)       # Python 3
    if not s.strip():
        return []
    parts = s.split()
    nums = []
    for p in parts:
        try:
            nums.append(float(p))
        except ValueError:
            raise ValueError("invalid token: %r" % p)
    return nums

def average(nums):
    if not nums:
        raise ValueError("no numbers supplied")
    return sum(nums) / len(nums)

For interactive one-by-one entry, 's approach works well; the single-line alternative above is often nicer for quick testing. Test with integers and decimals, and try an empty input to confirm your error handling behaves as expected.

Recommended Answers

All 7 Replies

What is your python version?
When you run it do you get any errors?

I use python 3.0 and your modifying code works fine:

def getList():
     lst=[]
     answer1 = input ("Would you like to add a number to create your mean value? y/n")
     if (answer1 == "y"):
         while True:
            x = input ("Your number:")
            if not x: break
            lst = lst + [x]
     return lst

def mean(l):
    s = sum([ int(x) for x in l])
    return float(s/len(l))

a=mean(getList())
print (a)

I'm using python 2.6

my code says I haven't defined getlist

you defined getlist() with lowercase letter 'l' and below used it with uppercase letter 'L'. Python is case-sensitive language. :)

I would do like this for your example, it shows the 'mean' when you just press enter with no input.

def getlist():
    lst = []
    x = None
    while x != '':
        x = raw_input('Your number:')
        if x:
            lst.append(int(x))
    return lst

def mean(l):
   return float(sum(l))/len(l)

a = mean(getlist())
print a

Cheers and Happy coding

You have defined getlist. You have not defined getList.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.