2

Yesterday I posted a question where I was searching for a way to do an infinite for loop, without using while at all (because my teacher wants so, and also, we can't use any commands we haven't seen in class). It was difficult as apparently there wasn't a very viable option that didn't use while, or other functions like itertools or .append, etc.

You can see that question here
Also, thanks a lot for the feedback you guys brought me! :)


But I managed to talk with my teacher and we got permission to use itertools or just a range big enough (instead of actually infinite).


I solved a few exercises already, but now I have the following instructions:

(Think about grades)
• Ask the user a number (through inputs), and keep asking until the user tells to stop.
• Then, calculate the average from all the numbers entered.

(It's actually a little more complex, but I shortened it and I believe I can deal with the rest)

As I said, I must use a for loop, and I can't use whiles at all.

If I could use while, I'd do something like this:

def grades():
    totalg = 0
    countg = 0
    keepAdding = "y"
    while(keepAdding == "y"):
        qualif = int(input("Insert grades obtained, in scale from 0 to 100 "))
        totalg = totalg + qualif
        countg = countg + 1
        keepAdding = str(input("Do you wish to keep adding data? (y/n) "))
    print("The average of your grades is", totalg/countg)

How can I do something like that, but with for loops? I have no idea on how to store the data for later calculation.


Also, I'm interested into knowing a more "proper" way to be able to end the loop, but I can't use a break neither.

Thanks in advance! Any advice is appreciated and welcome! :)

James
  • 32,991
  • 4
  • 47
  • 70
oScarDiAnno
  • 184
  • 1
  • 1
  • 10
  • In yesterday's answer I used `return` to get over the no-`break` restriction. Or aren't you allowed to use `return` either? – PM 2Ring Oct 17 '17 at 03:42
  • 1
    Maybe you should list the stuff you are allowed to use. It's hard to answer this type of question when we don't know what the rules are. – PM 2Ring Oct 17 '17 at 03:54
  • Yes. (sorry for the late btw) I can use return and it's more or less what I've done, but in this case, for this code for example, how would I put the return command in order to end it while keeping the variables value? Sorry for my ignorance, I guess it's something I could deduce from your code, but I'm afraid I haven't been able to understand it fully. And yes, let me do a list of the stuff we've seen to make it easier. But I think we're getting closer though, thank you :) – oScarDiAnno Oct 17 '17 at 04:43

3 Answers3

4

One way to do this is, without outside modules, is to use two-arg iter; when passed two arguments, the first is a no-argument function to call over and over, and the second is a sentinel value than indicates you should stop.

So for example, you could make an infinite loop with something as simple as:

 for _ in iter(bool, True):

Since the bool constructor returns False, a sentinel value of True will never occur, so that's an infinite loop.

Similarly, to make a loop that prompts until the user responds with a given sentinel string, like 'q' for quit (or just the empty string), you could do:

for inp in iter(lambda: input("Insert grades obtained, in scale from 0 to 100 (type 'q' to quit)"), 'q'):
    val = int(inp)
    ... rest of loop ...

Obviously, this is a little obscure (two-arg iter is rarely seen), so usually you'd use while True: with the loop containing a test-and-break or test-and-return (the latter doesn't violate the letter of the teacher's requirements). Similarly, exception handling can be used to exit the loop, though it's ugly:

 try:
     for ...:
         if test_for_end:
             raise StopIteration
 except StopIteration:
     pass
 # You're outside the loop

Note: Literally everything I've mentioned is terrible style, aside from an actual while True: loop with a test-and-break/return case. But you've got one hand tied behind your back, so I'm suggesting some terrible mutant hands to substitute.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • @PM2Ring: Possible. One-arg `iter` isn't totally unheard of though, so they might have seen it, even if they weren't introduced to the two-arg form. If they went over the built-in functions, it's there; similarly, if they covered how a for loop works, `iter` is an implicit part of all `for` loops, so who knows? – ShadowRanger Oct 17 '17 at 03:54
  • I believe I'd be able to use iter know, well, actually, at first I believed it was included in iter.tools and my teacher allowed that. We haven't seen it in class, that's sure, but know I think I could use it. However, I seen some other things we wouldn't been able to use, like `lambda`. I think I'm making you guys struggle a little too much, really, thanks a lot for this. But I think it'd be easier if as @PM2Ring says, I did a list with stuff we have seen. Give me a second, it'd be useful for me too – oScarDiAnno Oct 17 '17 at 04:48
4

Even though 'no-break' rule and a request for a "proper" way to end a loop are somewhat contradictory, I'd say that is possible, even without return :

grades = [0]
for j in grades:
    t = int(raw_input('grade:'))
    ans = raw_input('more? [y/n]:').lower()
    if(ans == 'y'):
        grades.append(t)
    else:
        grades[0] = t

print(sum(grades)*1.0/len(grades))  

here we just iterate over ever-growing list of values, and when we need to stop - we simply stop adding values to it, and the loop ends.

HOWEVER This is NOT a proper way of handling that issue, read ShadowRanger for more details - this is bad coding style and should not be used.

E P
  • 116
  • 8
-1

Maybe saving all the data obtained in an array? I think arrays on python work as Linked Lists, so you won't have any overflow problems, at least that would be a starting point

Solrak
  • 11
  • 2
  • 1
    One: No, Python isn't using linked lists for the `list` type (`array` is a module for C specific types, and probably not what you mean). Two: This isn't really an answer; it sort of responds to the title of the question, but the body of the question isn't about storing the original values at all; even if it was, this is too vague/broad to serve as an answer. – ShadowRanger Oct 17 '17 at 04:15