473,667 Members | 2,670 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NOOB coding help....

Ok, this is what I have so far:

#This program will ask for a user to imput numbers. The numbers will then
be calculated
#to find the statistical mean, mode, and median. Finallly the user will be
asked
#if he would like to print out the answers.
list = [ ]
a = 1
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
while a != 0 :
a = input('Number? ')
list.append(a)
zero = list.index(0)
del list[zero]
list.sort()

variableMean = lambda x:sum(x)/len(x)
variableMedian = lambda x: x.sort() or x[len(x)//2]
variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
s = variableMean(li st)
y = variableMedian( list)
t = variableMode (list)

x = (s,y,t)
inp = open ("Wade_Stoddard SLP3-2.py", "r")
outp = open ("avg.py", "w")
f = ("avg.py")
for x in inp:
outp.write(x)
import pickle
pickle.dump(x, f)
print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
raw_input('Plea se enter Yes or No:')
if raw_input == Yes:

f = open("avg.py"," r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode

I am attempting to make it so that I can save the mean, meadian, and mode
and then if the user wants the data to give it to him. Thank you for any
assistance you can provide!

Wade

Jul 18 '05 #1
6 1678
Could you phrase this in the form of a question, like Jeopardy?
On Monday 21 February 2005 08:08 pm, Igorati wrote:
Ok, this is what I have so far:

#This program will ask for a user to imput numbers. The numbers will then
be calculated
#to find the statistical mean, mode, and median. Finallly the user will be
asked
#if he would like to print out the answers.
list = [ ]
a = 1
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
while a != 0 :
a = input('Number? ')
list.append(a)
zero = list.index(0)
del list[zero]
list.sort()

variableMean = lambda x:sum(x)/len(x)
variableMedian = lambda x: x.sort() or x[len(x)//2]
variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
s = variableMean(li st)
y = variableMedian( list)
t = variableMode (list)

x = (s,y,t)
inp = open ("Wade_Stoddard SLP3-2.py", "r")
outp = open ("avg.py", "w")
f = ("avg.py")
for x in inp:
outp.write(x)
import pickle
pickle.dump(x, f)
print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
raw_input('Plea se enter Yes or No:')
if raw_input == Yes:

f = open("avg.py"," r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode

I am attempting to make it so that I can save the mean, meadian, and mode
and then if the user wants the data to give it to him. Thank you for any
assistance you can provide!

Wade


--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
Jul 18 '05 #2
Igorati wrote:
list = [ ]
a = 1
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
while a != 0 :
a = input('Number? ')
list.append(a)
zero = list.index(0)
del list[zero]
list.sort()
A simpler approach is to use the second form of the builtin iter
function which takes a callable and a sentinel:

py> def getint():
.... return int(raw_input(' Number? '))
....
py> numbers = sorted(iter(get int, 0))
Number? 3
Number? 7
Number? 5
Number? 2
Number? 0
py> numbers
[2, 3, 5, 7]

Note that I've renamed 'list' to 'numbers' so as not to hide the builtin
type 'list'.
variableMean = lambda x:sum(x)/len(x)
variableMedian = lambda x: x.sort() or x[len(x)//2]
variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
s = variableMean(li st)
y = variableMedian( list)
t = variableMode (list)
See "Inappropri ate use of Lambda" in
http://www.python.org/moin/DubiousPython.

Lambdas aside, some alternate possibilities for these are:

def variable_median (x):
# don't modify original list
return sorted(x)[len(x)//2]
def variable_mode(x ):
# only iterate through x once (instead of len(x) times)
counts = {}
for item in x:
counts[x] = counts.get(x, 0) + 1
# in Python 2.5 you'll be able to do
# return max(counts, key=counts.__ge titem__)
return sorted(counts, key=counts.__ge titem__, reverse=True)[0]

Note also that you probably want 'from __future__ import divsion' at the
top of your file or variableMean will sometimes give you an int, not a
float.
x = (s,y,t)
inp = open ("Wade_Stoddard SLP3-2.py", "r")
outp = open ("avg.py", "w")
f = ("avg.py")
for x in inp:
outp.write(x)
import pickle
pickle.dump(x, f)
If you want to save s, y and t to a file, you probably want to do
something like:

pickle.dump((s, y, t), file('avg.pickl e', 'w'))

I don't know why you've opened Wade_StoddardSL P3-2.py, or why you write
that to avg.py, but pickle.dump takes a file object as the second
parameter, and you're passing it a string object, "avg.py".
f = open("avg.py"," r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode


mean, median, mode = pickle.load(fil e('avg.pickle') )
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode

HTH,

STeVe
Jul 18 '05 #3
Thank you, that does help quit a bit. I am working on the corrections now.
To the first poster... don't know what that meant. I thought I made my
case understandable. Thank you again. I will work on that. I was
attempting to open wade_stoddard.. . b/c that was my file I was working
with, and I was told I had to open it in order to save information to
another file so I could recall that information. Thank you again for the
help Steven.

Jul 18 '05 #4
#This program will ask for a user to imput numbers. The numbers will then
be calculated
#to find the statistical mean, mode, and median. Finallly the user will be
asked
#if he would like to print out the answers.
numbers = [ ]
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
def getint():
return int(raw_input(' Number? '))

numbers = sorted(iter(get int, 0))

numbers
[2, 3, 5, 7]
def variable_median (x):

return sorted(x)[len(x)//2]
def variable_mode(x ):

counts = {}
for item in x:
counts[x] = counts.get(x, 0) + 1

return sorted(counts, key=counts.__ge titem__, reverse=True)[0]

s = variableMean(nu mbers)
y = variableMedian( numbers)
t = variableMode (numbers)

import pickle
pickle.dump((s, y, t), file('avg.pickl e', 'w'))
print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
print 'Please enter Yes or No:'
if raw_input == yes:

f = open("avg.py"," r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode
I got the error:

Traceback (most recent call last):
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 9, in ?
numbers = sorted(iter(get int, 0))
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 7, in
getint
return int(raw_input(' Number? '))
TypeError: 'str' object is not callable

and this one for my if statement:

Traceback (most recent call last):
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 39, in ?
if raw_input == Yes:
NameError: name 'Yes' is not defined

I cannot understand how I can define yes so that when they type yes the
data is printed out. Also if they type no how do I make the program do
nothing. Or is that just infered.

Jul 18 '05 #5
Igorati said unto the world upon 2005-02-22 03:51:
#This program will ask for a user to imput numbers. The numbers will then
be calculated
#to find the statistical mean, mode, and median. Finallly the user will be
asked
#if he would like to print out the answers.
numbers = [ ]
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
def getint():
return int(raw_input(' Number? '))

numbers = sorted(iter(get int, 0))

numbers
[2, 3, 5, 7]
def variable_median (x):

return sorted(x)[len(x)//2]
def variable_mode(x ):

counts = {}
for item in x:
counts[x] = counts.get(x, 0) + 1

return sorted(counts, key=counts.__ge titem__, reverse=True)[0]

s = variableMean(nu mbers)
y = variableMedian( numbers)
t = variableMode (numbers)

import pickle
pickle.dump((s, y, t), file('avg.pickl e', 'w'))
print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
print 'Please enter Yes or No:'
if raw_input == yes:

f = open("avg.py"," r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode
I got the error:

Traceback (most recent call last):
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 9, in ?
numbers = sorted(iter(get int, 0))
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 7, in
getint
return int(raw_input(' Number? '))
TypeError: 'str' object is not callable

and this one for my if statement:

Traceback (most recent call last):
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 39, in ?
if raw_input == Yes:
NameError: name 'Yes' is not defined

I cannot understand how I can define yes so that when they type yes the
data is printed out. Also if they type no how do I make the program do
nothing. Or is that just infered.


Hi,

have you tried examining the objects you are trying to put together to
see why they might not fit?

For instance, look what happens when you run this, entering 42 at the
prompt:

ri = raw_input('Gimm e! ')
print type(ri)
print type(int(ri))
print ri == 42
print ri == '42'
name_not_define d_in_this_code

Does looking at the output of that help?

Best,

Brian vdB

Jul 18 '05 #6
Igorati wrote:
#This program will ask for a user to imput numbers. The numbers will then
be calculated
#to find the statistical mean, mode, and median. Finallly the user will be
asked
#if he would like to print out the answers.

numbers = [ ]
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
so 0 is not a valid value ?
Since you only want numbers, any alpha char could be used to exit...
def getint():
return int(raw_input(' Number? '))
What happens if the user type "foo" ?
numbers = sorted(iter(get int, 0))

numbers
[2, 3, 5, 7]
def variable_median (x):

return sorted(x)[len(x)//2]
def variable_mode(x ):

counts = {}
for item in x:
counts[x] = counts.get(x, 0) + 1

return sorted(counts, key=counts.__ge titem__, reverse=True)[0]

s = variableMean(nu mbers)
y = variableMedian( numbers)
t = variableMode (numbers)

import pickle
pickle.dump((s, y, t), file('avg.pickl e', 'w'))
Take care of removing hard-coded filenames... (this is ok for testing
but should not be released like this)

print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
print 'Please enter Yes or No:'
if raw_input == yes:
First, raw_input() is a function, you need to use the () operator to
*call* (execute) the function.

Then, raw_input() returns a string. A string is something between
quotes. Yes is a symbol (a variable name, function name or like), not a
string. And since this symbol is not defined, you have an exception.

What you want to do is to compare the string returned by the raw_input()
function to the literral string "Yes". What you're doing in fact is
comparing two symbols, one being defined, the other one being undefined...

if raw_input() == "Yes":

f = open("avg.py"," r") Same remark as above about hard-coded file names...
avg.py = f.read()
Notice that the dot is an operator. Here you trying to access the
attribute 'py' of an (actually inexistant) object named 'avg'. What you
want is to bind the data returned by f.read() to a variable.

data = f.read()

print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode
At this time, mean, meadian and mode are undefined symbols. Since you
used the pickle module to persist your data, you should use it to
unserialize'em too. The pickle module is well documented, so you may
want to read the manual.

I got the error:

Traceback (most recent call last):
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 9, in ?
numbers = sorted(iter(get int, 0))
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 7, in
getint
return int(raw_input(' Number? '))
TypeError: 'str' object is not callable
Can't tell you since I'm running python 2.3.x here (sorted() is new in 2.4)
and this one for my if statement:

Traceback (most recent call last):
File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 39, in ?
if raw_input == Yes:
NameError: name 'Yes' is not defined
See above.
I cannot understand how I can define yes so that when they type yes the
data is printed out.
Yes = 'yes' ?-)
Also if they type no how do I make the program do
nothing. Or is that just infered.


May I suggest that you :
- subscribe to the 'tutor' mailing-list (it's a ml for absolute beginners)
- do some tutorials (there's one with the doc, and many others freely
available on the net)
- use the interactive python shell to test bits of your code ?

HTH
Bruno
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2112
by: Matt Hollingsworth | last post by:
Hello, Very new to python, so a noob question. When I've written stuff in JavaScript or MEL in the past, I've always adopted the variable naming convention of using a $ as the first character (no, I don't use perl, never have). Not possible in python. What are some good options that people commonly use so that they can easily and quickly identify variable with just a glance? When I was writing stuff in SoftImage XSI/JScript, many of...
1
1801
by: davestrike | last post by:
I am a noob to sql and asp programming. I am working on a db for the gaming squad I am a member of. One of the pages I created is a roster list of all the squad members. Part of this roster is listing each member's email address. What several people have asked of me is to make it so the email addresses can be clicked on to open their email programs, just as html allows the mailto function to work. Here is a copy of the coding I am...
0
1086
by: davestrike | last post by:
I am in the process of learning SQL and ASP coding. I am making a db for my squad I belong to for an online game. I have made a page that lists all the members of the squad including their email addresses. Several people have asked that the email listed be clickable to launch their email programs, just as mailto works in html coding. Here is a copy of the line in question: <td align="center"><font face="Arial"...
4
1584
by: Mason Barge | last post by:
I'm learning how to build a website. So far I've gotten pretty good with HTML, CSS, and Paint Shop Pro, and I'm currenly learning the basics of Javascript. I'm hoping, eventually, to build and run an online publication that will change content daily and have extensive archived articles, cross-referenced by subject area(s). What other languages would it make sense for me to learn? CGI, Perl, PHP, Ajax, SQL are all Greek to me. I do...
9
3172
by: davetelling | last post by:
I am not a programmer, I'm an engineer trying to make an interface to a product I'm designing. I have used C# to make a form that interrogates the unit via the serial port and receives the data. I want to be able to draw lines in a picturebox based upon certain data points I have received. I dragged a picturebox from the toolbar onto my form, but after having gone through the help files, looking online and trying a variety of things, I...
2
2852
by: Link360 | last post by:
Im a complete noob and im proud of it. I am excited in learning everything about the C++ language. Right now im trying to make tic-tac-toe. Go ahead laugh. here is what i have so far #include<iostream> #include<stdlib.h> using namespace std; int main() {int h,h2,tmp; h=10;
5
1613
by: Milan Krejci | last post by:
the thing is that descentant branches i dont want to expand do expand. $id variable contains an array of branches i want the program to go through (alcohol's id -beer id etc) function tree_list($parent, $level,$id) { // retrieve all children of $parent $result = mysql_query('SELECT cname,cid FROM kategorie '. 'WHERE parent="'.$parent.'";'); while ($row = mysql_fetch_array($result)) {
9
3585
by: Ben | last post by:
Hello, I'll bet this has been asked a million times but I can't seem to find a thread that gives the clear example I need. This PC has MySQL and IIS configured and running. The MySQL database is "myDB" with a table "myUsers" with fields "Username" and "Password". I also have the MySQL ODBC driver loaded with a DSN "dsnMySQL" setup. First question is can someone direct me to a site or provide a sample code for a login page that...
5
2082
by: Hydrogenfussion | last post by:
Hello and thank you for reading this. I have just started to learn C++ from www.cprogramming.com,its a great site! But i do not understand some of the terms. I am using Dev-C++. Can you tell me where to go to understand C++ terms? TY When i said i was a noob i meant it. This is the ONLY thing i have written: #include <iostream> using namespace std;
0
8458
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8366
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8790
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8650
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7391
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6206
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2779
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.