可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm learning Python (using 3.6.2) and on my last class, they asked me to do something where I need to make an infinite for loop. For some reason, the teacher doesn't want us to use while for the entire practice. This is where it gets complicated...
So, I've been looking for a way to do it. But, it's also difficult because the teacher doesn't want us to use any commands we haven't seen in class. So I can't use .append, sys functions, well, I can't even use a break. I must find a way to do with "simple" commands.
I thought I could do it this way;
x=1 for i in range(x): do_something() x += 1
However, it didn't seemed to work. I think that's because Python doesn't read the value for the range again?
I couldn't find a way, but after hours of thinking I found myself a small workaround I could use:
def ex(): print("Welcome") for i in range(1): math = int(input("Please insert grades obtained at Math, or insert 666 to exit" )) if(math > 0 and math < 60): print("Sorry. You failed the test") return ex(): elif(math >= 60 and math <= 100): print("Congratulations. You passed the test") return ex(): elif(math == 666): return exit() else: print("ERROR: Please insert a valid number") return ex(): def exit(): pass
As you can see, what makes it "infinite" is that it returns to the function once and once again, until you tell the program to "exit", by entering "666". I'd also like to have a more proper way to exit the function.
I'm still wondering if there's a better way to make my for loop infinite until the user calls it to stop. However, one way or another I got this exercise working. The problem came when I started with the second one, which is more or less like this:
Imagine the same past program, but this time, it will not just show you if you passed the test or not. It wants to collect as many grades you enter through the input, and then calculate the average of all the grades. I'm not able to save those values (the grades) because I kind of "restart" my own function every time.
And according to my teacher's instructions, I can't ask the user how many grades he wants me to calculate. It must be infinite and keep asking for inputs until the user choses not to.
I'm really stuck and lost on it. It's very hard and frustrating because it'd be way easier if we could just use while's :( And also harder because we can't use any options we haven't seen...
So, I have 3 questions:
- How do I make an appropiate "infinite" for loop?
- How do I make a proper way to "finish" it?
- How do I make it able to save values?
A lot of thanks in advance for anyone willing to help, and sorry for my ignorance.
I'm new to the community, so any advice about my problems, the question formatting or anything is well received :)
EDIT: I talked to my teacher and he allowed me to use either itertools or just a range big enough to not be reached. Now i'm wondering, how can I save those values inside the for for later manipulation?
回答1:
If you are not allowed to use itertools and you are limited to basic language constructs, and not allowed to use while then I have some sad news for you;
This might not be possible. At least not with a python for loop.
I suggest you get in contact with whoever is leading your class and get them to clarify the requirements. There is no real-world application for this knowledge, so I would be very interested to know what the goal of this assignment is.
Note; This is possible in other languages that support actual for loops (ie, rather than foreach loops) so maybe the assigner of this task ported this question from a different language class?
EDIT; Now that you're allowed to use itertools, I would suggest using the answer I gave in the comments originally;
from itertools import count for i in count(): pass # this will loop for longer than you will live.
With this, plus a list created before the loop, you should have no difficulty keeping track of grades and calculating their average.
回答2:
I hate "trick" questions like this that have very little to do with how you'd use Python in the real world. But anyway...
The trick here is to iterate over a list that you modify inside the for loop. This is generally regarded as a bad practice, but we can exploit it here for this contrived assignment.
We ask for user input inside a function so we can escape from the loop by using return, since you aren't permitted to use break.
def get_data(prompt): lst = [None] for i in lst: s = input(prompt) if not s: return lst[1:] lst += [int(s)] print(lst) print('Enter data, one number at a time. Enter an empty line at the end of the data') lst = get_data('Number: ') print('Data:', lst)
demo
Enter data, one number at a time. Enter an empty line at the end of the data Number: 3 [None, 3] Number: 1 [None, 3, 1] Number: 4 [None, 3, 1, 4] Number: 1 [None, 3, 1, 4, 1] Number: 5 [None, 3, 1, 4, 1, 5] Number: 9 [None, 3, 1, 4, 1, 5, 9] Number: Data: [3, 1, 4, 1, 5, 9]
回答3:
Can you try something like this:
for i in iter(int, 1): print("Infinite for loop executing")
Refer to this question regarding infinte iterator without while for more info.
回答4:
Python 3.x infinite loop bassed on class:
class loop_iter(object): def __iter__(self): return self def __next__(self): # for python2.x rename this method to `next` # Return the next item from the container. # If there are no further items, raise the StopIteration exception. # Because this is infinite loop - StopIteration is not raised return None class infinite_loop(object): def __iter__(self): # This method is called when an iterator is required for a container. # This method should return a new iterator object that can iterate over all the objects in the container. # For mappings, it should iterate over the keys of the container, and should also be made available as the method keys(). # Iterator objects also need to implement this method; # they are required to return themselves. # For more information on iterator objects, see Iterator Types. return loop_iter() x = [] # thx PM 2Ring for text print('Enter data, one number at a time. Enter an empty line at the end of the data') for _ in infinite_loop(): line = input('Number: ') if line: x += [int(line)] continue print('Average:', sum(x)/len(x)) # average exit()