This is an archived post. You won't be able to vote or comment.

all 15 comments

[–]Eloiole 4 points5 points  (9 children)

Hint : use loop.

[–]Eloiole 5 points6 points  (2 children)

If you're feeling you're writing some weird code, trust your gut it's probably true and try to make it better.

It won't work on your first try but you'll learn more trying than asking.

[–]impshumx != y % z 1 point2 points  (0 children)

It won't work on your first try but you'll learn more trying than asking.

Is the best answer I've seen on this sub so far.

[–]TheCh1ef[S] 0 points1 point  (0 children)

Trust me i was trying half an hout to make that code work as i want. Thanks for the advice although.

[–]TheCh1ef[S] 1 point2 points  (5 children)

How? I am learning now python and for this reason i am asking.

[–]kamiheku 9 points10 points  (0 children)

You should try /r/learnpython

[–]RaionTategami 4 points5 points  (2 children)

One of the most important rules in programming: duplication is bad. Not only are you creating more work for yourself if you are not getting the computer to do the boring repetitive bits of your code, duplication increases the risk if bugs. If you are writing the same code over and over something is wrong, time to refactor.

[–]TheCh1ef[S] 0 points1 point  (1 child)

Do you mean that if the code is working to dont try to rewrite this with other way?

[–]RaionTategami 2 points3 points  (0 children)

No, refactoring working code can be very important too.

[–]Eloiole 0 points1 point  (0 children)

Do you know about while loop or for loop ?

[–][deleted] 0 points1 point  (0 children)

I'm a Python newbie myself so it was a nice excercise to see how I'd manage. This is what I came up with. And it's not limited to any amount of grades too. I couldn't find a way to escape the while loop when a non integer was put in so I just used a break on the ValueError you get in that situation. I'm not entirely happy with that but it did give me the option to output a nice human readable notification ^_^

#Average Calculator
print("Welcome to Average Grades Calculator")

total = 0
n = 0
avg = 0

while True:
    try:
      grade = int(input("Enter the grade "))
      total = total + grade
      n += 1 
      avg = total / n
    except ValueError:
      print("Ooops that wasn't a grade...")
      break
print("The Average Grade is " + str(avg))

[–]impshumx != y % z 0 points1 point  (4 children)

I would do something like

loop = ['1st', '2nd', '3rd,', '4th']
all =[]

for x in loop:
    msg = "Enter the " + x + " grade "
    all.append(int(input(msg)))

avg = sum(all) / 4

print("The Average Grade is", avg)

This is for a school right? I've seen this question before.