![]() |
for loops and if - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: for loops and if (/thread-18107.html) |
for loops and if - johneven - May-06-2019 I feel like my code is correct, but keep getting wrong output for this homework question. The problem is: Below are a set of scores that students have received in the past semester. Write code to determine how many are 90 or above and assign that result to the value a_scores. scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" #my attempt below accum = 0 for sc in scores: if sc >= 90: accum = accum + 1 a_scores = accum print(a_scores)
RE: for loops and if - scidam - May-06-2019 I got: Do something like this prior your loop: scores = map(int, scores.split())or a_score = len(list(filter(lambda x: x >= 90, scores)))
RE: for loops and if - perfringo - May-06-2019 Another possibility: >>> scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" >>> sum(1 for x in scores.split() if 90 <= int(x)) 10Of course there is also Counter in collections module: Quote:A Counter is a dict subclass for counting hashable objects. RE: for loops and if - MvGulik - May-06-2019 (May-06-2019, 05:39 AM)scidam Wrote: I got: That's the difference between Python-2* and Python-3 when unequal types are compared. (*tried to read up on this for Py2 ... but gave up on that idea very very quickly*) *) or when Trinket(default free version) is used without #!/bin/python3 as first line. Right, even with #!/bin/python3 Trinket happily processed that str() >= int() part. (back to the drawing board ... right, effects only syntax evaluation)))
RE: for loops and if - johneven - May-06-2019 An answer to problem: scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" scoressplit = scores.split() #print(scoressplit) accum = 0 for sc in scoressplit: if int(sc) >= 90: accum = accum + 1 a_scores = accum print(a_scores)
RE: for loops and if - perfringo - May-07-2019 Some observations and suggestions. - there is no reason to assign names to objects like scoressplit and accum if you don't need them- use descriptive names i.e. sc -> score - use += - use comparison operators in ascending flow i.e 90 <= int(score), it makes easier for human to mentally parse comparison scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" a_scores = 0 for score in scores.split(): if 90 <= int(score): a_scores += 1 print(a_scores) |