Break out of Loop but Still make Loop Useable - python

I'm a beginner to Python, so this might sound pretty easy.
Anyway, I'm a little confused on when to use break, pass, or continue. I want to have a loop where it breaks out of it, but then after all the code runs again, then the loop will run again. This is some example code:
score = 100
while True:
score + 1
# break, continue, or pass
score - 30
Basically, what I want to happen is have score go up by 1, then have it go down by 30, and then keep going up by 1.
How can I achieve this? Thanks in advance!

score = 100
first = True
while True:
while True:
score += 1
if first:
first = False
break
score -= 30

Related

while loop wont stop running in python

I am working on a crash game in python and im trying to make it crash when a value hits 1,50, or 100 but it keeps going. Does anyone know why?
import random
import time
game = 1
num = 1.00
while game == 1:
num += .01
print(round(num, 2))
time.sleep(.1)
if game != 1:
print("Crash!")
break
while game == 1:
crash = random.randint(1, 100)
time.sleep(.1)
if crash == 1 or crash == 50 or crash == 100:
game -= 1
else:
break
In first while loop game's value never changes from 1 therefore never exits the first while loop
BTW you do not have to break the loop because once game != 1 it will won't enter the loop again.
I think you mean to use only the second while loop you have written - so you can delete the first one and remove the else from the second - no need for it for the same reason you do not need the break in the first loop.
so if I understand your intention correctly than the code should be:
import time
game = 1
while game == 1:
crash = random.randint(1, 100)
time.sleep(.1)
if crash == 1 or crash == 50 or crash == 100:
game -= 1
If you're new to computer science, it can sometimes be useful to "play computer" when looking at code. Look at each step of the code and try to imagine what would happen. In a language like python, you can even test these statements one at a time to make sure they do what you think they do.
Let's skip to the important part.
The state of the memory is game and num both equal 1.
while game == 1: # loop until game is not 1
num += .01 # add 0.01 to num
print(round(num, 2)) #print round(num, 2); 1.01 the first time
time.sleep(.1) # sleep for 1 10th of a second
if game != 1: #game was not changed before this point, so game=1
print("Crash!") # this will never execute, ignore it.
break
# End of the loop: execution flow return to the start again, with num=1.01
You see the problem? This will never exit because game is never altered in the loop, this will continue to loop forever. The second loop won't ever even be reached because it's going to be stuck in the first one.

python: Trying to add another "timered" print function inside a loop, with not great success :D

First part was cut.. Sorry to ask this but I'm new to python and programming in general. My knowledge and experience is lacking and I'm not always able to find (or understand) what I need to do to achieve something.
Right now I'm performing print('2') every 2 secs, and print('30') every 30secs.
So right now I would like to implement another function print('10') to perform every 10 secs, within the loop.
Can you help me understand how to achieve this?
SHORT_DELAY = 2
LONG_DELAY = 30
accum_time = LONG_DELAY
while True:
print('2')
if accum_time > LONG_DELAY:
print('30')
accum_time -= LONG_DELAY
time.sleep(SHORT_DELAY)
accum_time += SHORT_DELAY
Wo, what to do now??
To achieve my goal I would say I need to set another var, for example MID_DELAY = 10, but then how can I implement this new parameter in the loop?
I can't solve this simple task because if I'm resetting the mid_delay I will never get the long_delay value to be bigger than 30, and if I reset the long_delay the mid_delay would actually works ONLY after the long_delay has been resetted, so it would print "10" only after the 30 seconds have been resetted.
Also with the code like this I get a "30" print results after few seconds. (I think that's because the loop starts with accum_time already with a value of "30", and so as soon as it get bigger it prints)
Hope my question is clear.
Sorry if there is confusion, I was trying to "debug" as writing this, still with no success..
Forgive me I'm noob.
It's not necessary to use "for" loop in your problem. Start thinking "How to resolve my problem?" What do you want to do?
You want to print something at appropriate intervals. And you want to set this intervals in your variables.
So start timing and check that the values ​​have been reached with function IF
import time
SHORT_DELAY = 2
MID_DELAY = 10
LONG_DELAY = 30
accum_time = 0
while True:
if accum_time == 0:
pass
elif accum_time % LONG_DELAY == 0:
print('30')
elif accum_time % MID_DELAY == 0:
print('10')
else accum_time % SHORT_DELAY == 0:
print('2')
time.sleep(SHORT_DELAY)
accum_time += SHORT_DELAY
Of course while accum_time is increasing by SHORT_DELAY you don't have to check statement in "else".
else:
print('2')
I can help you,
I changed the code a bit so its easier to read for me.
import time
SHORT_DELAY = 2
while True:
print('2')
SHORT_DELAY += 1
time.sleep(2)
#when 30 seconds is full it prints 30
if SHORT_DELAY==31:
SHORT_DELAY=0
print('30')
when 10 seconds is full it prints 10
if SHORT_DELAY==11 or 21 or 31:
print('10')
I hope I helped. Message me if something is wrong or hard to understand.

My "while loop" not working as expected

I am a new coder, sorry if my question is bad or I am not following proper etiquette!
I am designing a basic program that rolls dice. It is supposed to roll dice until the total points of either the computer or the user equals 100. However, even though my point totaler is working, the loop won't end. Anyone know why this is? Thank you!
def main():
GAME_END_POINTS = 100
COMPUTER_HOLD = 10
is_user_turn = True
user_pt = 0
computer_pt = 0
welcome()
while computer_pt < GAME_END_POINTS or user_pt < GAME_END_POINTS:
print_current_player(is_user_turn)
if is_user_turn is True:
user_pt = user_pt + take_turn(is_user_turn, COMPUTER_HOLD)
elif is_user_turn is False:
computer_pt = computer_pt + take_turn(is_user_turn, COMPUTER_HOLD)
report_points(user_pt, computer_pt)
is_user_turn = get_next_player(is_user_turn)
The condition is always True because either the computer or the user will have a points total less than 100.
Instead of or use and:
while computer_pt < GAME_END_POINTS and user_pt < GAME_END_POINTS:
Now the loop will continue only when both the user and the computer have a points total less than 100. As soon as one of them has more than 100 the condition will be be False and the loop will terminate.
You while loop will only end if both computer_pt >= GAME_END_POINTS and user_pt >= GAME_END_POINTS. Are you sure that those two variables satisfy those two conditions?
you can print computer_pt and user_pt in the loop to see what happened in this two variable, then you will find the answer by your self.
Print variable in loop is a common way to debug your code.

if statement handling-manipulation

well, ive been wondering if such thing is possible in python
while True:
if True:
x = -5
x = 5
now i mean, whenever if statement is true,(in this example) the first time x to equal -5 and the second time is true, x to equal 5 ,and again the same
i know it sounds absurd but im trying to make a game which the ball has to go rightward and when returns leftward,and this thing over and over again
sorry for my bad english but it's really difficult for me to explain this
thanks in advance
Simply negate x each time the condition is true
x = 5
while True:
if True:
x = -x
You will need to count the iterations of the while loop so like this. This will let you switch between each iteration of the loop. If you just want to make it switch positive negative do x=-x.
x=0
while True:
if x%2==0: #if x is even do
y=5
else:
y=-5
print y
x+=1 #add 1 to x
if x==10: #quit at 10
break

Loop and validation in number guessing game

I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)

Categories