Some Python Questions

Started by
11 comments, last by mmoWoWmkr 17 years ago
cmd = ""sumlist = []total = 0while 1:    cmd = raw_input("Number or stop: ")    if cmd == "stop":        break    else:        sumlist.append(int(cmd))for item in sumlist:    total += itemprint sumlistprint total/len(sumlist)


I wrote this about 6 hours ago when I first saw your post.
Quote:Michael TanczosCut that shit out. You shouldn't be spying on other people.. especially your parents. If your dad wanted to look at horses having sex with transexual eskimo midgets, that's his business and not yours.
Advertisement
That code looks reasonable. I have a few thoughts, though...

1) You don't need to declare variables before usage assignment in Python, so the first line in the posted code (cmd = "") isn't necessary.

2) You can use the sum() function to calculate the sum of a sequence (i.e. a list, tuple, set, etc.).

3) The user input should be processed inside a try..except block. Exception handling is very useful.

Since you've let the cat out of the bag and posted some code, I'll post a version with the above changes:

sumlist = []while 1:    try:        cmd = raw_input("Number or stop: ")        sumlist.append(int(cmd))    except:        break  # stop if the user entered a non-numberif len(sumlist) > 0:	print sumlist	print sum(sumlist)/len(sumlist)
Ahh. I see where you are going. I tried that in a different way but i got some errors for putting breaks and whiles in the wrong places. I was getting pretty mad, but these two helped alot. Thanks.

This topic is closed to new replies.

Advertisement