The standard library's itertools provide an iterator counting up:
import itertools
for i in itertools.count():
print(i)
You can set the start and step:
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) --> 2.5 3.0 3.5 ...
Answer from rassi on Stack OverflowThe standard library's itertools provide an iterator counting up:
import itertools
for i in itertools.count():
print(i)
You can set the start and step:
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) --> 2.5 3.0 3.5 ...
The Pythonic way is
max_guesses = 5
solution = ... # Some solution
guessed = False
for wrong_guesses in range(1, max_guesses + 1):
guess = ... # Get Guess
if guess == round(solution, 2):
print("correct")
guessed = True
break
...
else:
print(f"You have exceeded the maximum of {max_guesses} guesses")
This way the loop is executed at most max_guesses times. The else block is only executed if the loop did not end because of a break statement i.e. when there was no correct guess.
Note the max_guesses + 1 because range is an iterator over the interval [low, high) (excluding the upper limit). So to run from 1 to max_guesses we have to +1.
How to exit while loops (using counters)
Help Understanding While loops
Can you count the number of times a loop occurs?
python - While loop counter - Stack Overflow
Technically this might be a 'learning to code' question but my language of choice happens to be Python so here goes!
I've come across this problem a few times while working through Daniel Zingaro's 'Learning to code' book (n00b here). Basically, I've got a while loop that is set to end if my counter reaches X number.
However, when I nest a for loop in that, with a list of say 3 elements (index 0,1,2) and add the counter at the end of each loop, my while loop statement is only being checked every three for loop iterations.
What follows is that my counter will over shoot by a few numbers because even though I've satisfied the while loop, the for loop operation needs to run until the end.
Is there a good way to force the while loop to end at the desired counter number without invoking the 'break' operation? The book warns that using 'break' can sometimes be bad practice, as it won't always clear why it's in the code. I get it's probably necessary sometimes but if I can avoid it, I'd like to learn how it can be done.
I've typed out an example snippet in case my description is unclear. In this case, the for loop runs through a list of 3 letters.
lst = ['A','B','C']
count = 0
while count <= 100:
for i in range(len(lst)):
...some operation...
...some operation...
if Y criteria met:
count += 1
'count' exits when it equals '102'.The problem I'm working on is here.
I'm new to python, sorry if my wording is terrible.
I'm building a very basic number guessing game. I don't want to copy and paste the whole code into here unless someone wants it in the comments.
I have it so that you guess a number between 1-100. After each guess it will tell you if it's too low or too high. Once you guess it correct it will say "Correct!". I want it to also tell you how many attempts it took you to find the correct answer and print that out with the "Correct!". How do you do that?
counter resets to its original value because it is a global variable. Global variables in Python behave differently than in other languages. Try this snippet :
counter = 3
def f():
counter = 2 # Shadows global 'counter' by a newly defined one
f()
print (counter) # Prints 3 !
You could expect the printed value to be 2, but is 3 instead. Global variables are immutable by default, and attempt to modify it in a local scope without global keyword will shadow by local definition instead. See this discussion to use global variable although it would be preferable to rework your program to use local variables.
EDIT: There is also a mistake, counter is initialized to 3 and only incremented, so the condition >= 0 will always be satisfied (thus creating an infinite loop). You can try:
[...]
def rps_game(user_obj, ai_obj, counter):
if counter <= 0:
return
print('Player selected %s ' % user_obj)
print('Computer selected %s ' % ai_obj)
while user_obj in rps and ai_obj in rps :
[...]
else:
print('Invalid input, please select Rock, Paper or Sissors')
rps_game(user_obj, ai_obj, counter-1)
rps_game(user_obj, ai_obj, 3)
The else containing the counter update is indented so that it hangs off of the while. That means that it executes only when the while loop terminates because the condition is false (not when you break out). In this case, the condition is false when either the user or ai input is not in the list of valid inputs or the counter is negative. The counter can never be negative because it starts at 3 and is only ever incremented. If the user input is invalid, the error message is printed, the counter is incremented, and then you use recursion to call the function with the same arguments. Since the arguments haven't changed, the function should do the same thing it just did, unless it depends on global data (counter). However, if counter is local (initialized inside the function), each invocation of the function gets a fresh copy. If counter is global (initialized outside the function, but declared global inside the function), it still won't work because you need to decrement it. And even then, because none of the other inputs have changed, it will just print the error message over and over.
Your loop bound appears to expect counter to count down from 3 since it keeps going as long as counter is positive. Incidentally, using >= as the conditional will make the loop execute 4 times (3, 2, 1, and 0). You might want to change the conditional to strictly greater than, and change the counter increment to a counter decrement.
Next, you are using recursion (the function calls itself), but this should be unnecessary since the loop gets you back to where you need to be.
Next, the lose cases break out of the loop, but the win cases do not. If you win, the code will loop, not modifying the counter or any of the other inputs, so it will not terminate.
Finally, the user input is read from outside the function, so it never changes inside the loop. If the user enters an illegal value, the loop will just keep testing the same value. You probably want to read the user input inside the loop.