breaking out of the loop? - python

I'm having some trouble with breaking out of these loops:
done = False
while not done:
while True:
print("Hello driver. You are travelling at 100km/h. Please enter the current time:")
starttime = input("")
try:
stime = int(starttime)
break
except ValueError:
print("Please enter a number!")
x = len(starttime)
while True:
if x < 4:
print("Your input time is smaller than 4-digits. Please enter a proper time.")
break
if x > 4:
print("Your input time is greater than 4-digits. Please enter a proper time.")
break
else:
break
It recognizes whether the number is < 4 or > 4 but even when the number inputted is 4-digits long it returns to the start of the program rather than continues to the next segment of code, which isn't here.

You obviously want to use the variable done as a flag. So you have to set it just before your last break (when you are done).
...
else:
done = 1
break

The reason it "returns to the beginning of the program" is because you've nested while loops inside a while loop. The break statement is very simple: it ends the (for or while) loop the program is currently executing. This has no bearing on anything outside the scope of that specific loop. Calling break inside your nested loop will inevitably end up at the same point.
If what you want is to end all execution within any particular block of code, regardless of how deeply you're nested (and what you're encountering is a symptom of the issues with deeply-nested code), you should move that code into a separate function. At that point you can use return to end the entire method.
Here's an example:
def breakNestedWhile():
while (True):
while (True):
print("This only prints once.")
return
All of this is secondary to the fact that there's no real reason for you to be doing things the way you are above - it's almost never a good idea to nest while loops, you have two while loops with the same condition, which seems pointless, and you've got a boolean flag, done, which you never bother to use. If you'd actually set done to True in your nested whiles, the parent while loop won't execute after you break.

input() can take an optional prompt string. I've tried to clean up the flow a bit here, I hope it's helpful as a reference.
x = 0
print("Hello driver. You are travelling at 100km/h.")
while x != 4:
starttime = input("Please enter the current time: ")
try:
stime = int(starttime)
x = len(starttime)
if x != 4:
print("You input ({}) digits, 4-digits are required. Please enter a proper time.".format(x))
except ValueError:
print("Please enter a number!")

Related

Does if/else statements require continue?

I am a beginner in Python and from what I understand, the continue statement in Python returns the control to the beginning of the while loop.
guesses = [0]
while True:
# we can copy the code from above to take an input
guess = int(input("I'm thinking of a number between 1 and 100.\n What is your guess? "))
if guess < 1 or guess > 100:
print('OUT OF BOUNDS! Please try again: ')
continue
# here we compare the player's guess to our number
if guess == num:
print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
break
# if guess is incorrect, add guess to the list
guesses.append(guess)
# when testing the first guess, guesses[-2]==0, which evaluates to False
# and brings us down to the second section
if guesses[-2]:
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
else:
print('COLDER!')
else:
if abs(num-guess) <= 10:
print('WARM!')
else:
print('COLD!')
Above is the code for the game called 'guess the number from 1 - 100'.
The first if statement where guess < 1 or guess > 100, it will print "Out of bounds!" and then continue which loops to the top of the code and asks for the user's input again.
But for the 3rd if statement where if guesses[-2]:, it does not require continue for neither if nor else.
Sorry if you do not understand what I am asking. But essentially, I want to know why 'continue' statement is not required after print('WARMER!), print('COLDER!'), print('WARM!') and print('COLD!').
guesses = [0]
while True:
# we can copy the code from above to take an input
guess = int(input("I'm thinking of a number between 1 and 100.\n What is your guess? "))
if guess < 1 or guess > 100:
print('OUT OF BOUNDS! Please try again: ')
continue
# here we compare the player's guess to our number
if guess == num:
print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
break
# if guess is incorrect, add guess to the list
guesses.append(guess)
# when testing the first guess, guesses[-2]==0, which evaluates to False
# and brings us down to the second section
if guesses[-2]:
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
**continue**
else:
print('COLDER!')
**continue**
else:
if abs(num-guess) <= 10:
print('WARM!')
**continue**
else:
print('COLD!')
**continue**
Note that all four of these print statements are the last of their execution branch.
Meaning, if guesses[-2] evaluates as true, than the else part won't be executed at all. Then, if abs(num-guess) < abs(num-guesses[-2]) evaluates to true, again - its else won't be executed. It means that for this execution branch the print('WARMER!') is the last statement of the loop and hence continue is not needed.
Same logic applies to all other 3 print statements.
In the case "guess < 1 or guess > 100" you want to skip the rest of the loop since you dont want to append the guess to the guesses list. Therefore you use continue.
The 'continue' statement is not required after print('WARMER!) etc because you dont need to skip any code afterwards. In this case because there wont be any lines executed after the print statement anyway.
First of all, if/else doesn't require continue. It's optional.
From what I understand you want to know why you used continue in the first if/else and not in the last if/else.
In the first one, after executing if statement it will transfer the control to while True: but for the last if/else statement it is not needed as the control will automatically go to while True: as it is the end of the loop and even if you had used continue it wouldn't have made a difference.
For further references
If you want to know why the continue is not always in if or else, this is due to the fact that when the operation arrives (true), the loop is exited and the code continues to run.

How can i make this code loop in Python

This code is supposed to turn decimals into binary, i figured out that part but now i need the code to go back to the previous question of asking to type in a integer instead of closing the program when calculations are done.
Here is what i have so far
def binary(n):
if n > 1:
binary(n//2)
print(n % 2,end = '')
dec = int(input("Enter an integer: "))
binary(dec)
input("\n\nPress the enter key to exit.")
Both a for loop and a while loop would help you to achieve the required outcome, depending on how many times you want the statement to loop. If you know the amount of times, use a for loop, however if you are comparing it do a condition, a while loop would probably be best. Find the syntax for for loops in python here
All you need is a simple while loop. It checks to see if the condition is true, and then executes the nested code. Therefore, putting True as the condition will make it an infinite loop.
def binary(n):
if n > 1:
binary(n//2)
string print(n % 2,end = '')
while True:
dec = int(input("Enter an integer: "))
binary(dec)
input("\n\nPress the enter key to exit.")

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)

Can someone tell me why this wont loop?

I'm making a number guessing game and can someone tell me why it wont work properly?
import random
import time
time.time()
count=0
a = random.randint(0,100)
b = int(input("What number will you guess?"))
while b != a:
if b > a:
print("TOO BIG")
count = count + 1
elif b < a:
print("TOO SMALL")
count = count + 1
else b == a:
print("YOU WIN")
count = count + 1
time=time.time()
print("You took",count,"tries")
print("It took you",time,"second")
The reason this isn't working properly is because you're calling b = input outside of your while loop. As it stands, the user will be asked a single time what their guess is, then the loop will just move infinitely, because b is never being modified.
This loop will accomplish more what you want:
a = random.randint(0,100)
b = -1
while b != a:
b = int(input("What number will you guess?"))
A few notes, though:
Firstly, as Lee Daniel Crocker points out, the user will actually never see "YOU WIN", because you've structured your if-elif-else statement incorrectly. else by definition cannot have a condition - it exists purely in exclusion to all other conditionals in the same block. Additionally, your else statement is the opposite of your while condition. When that else becomes true, the loop exits. You'll need to handle printing "YOU WIN" somewhere else.
Second, you're not validating the user's input in any way - if they enter 'a', the program will crash, because you can't cast 'a' to an int. Either add an exception handler (for ValueError) or using isdigit() on the string, then casting it.
Third, you're not using time.time() correctly - you need to subtract the time at which the user wins from the time at which they started, then represent that value, which is in seconds, in some meaningful way. As it stands you're telling each player that they took the number of seconds since the beginning of the UNIX epoch to complete the game.
Also, for usability reasons, you should probably provide the user some way to break out - a string like "QUIT" - because as it stands, the only way to restart/quit is to either close the application or KeyboardInterrupt.
You need to accept input in the loop. Move the line b = int(input("What number will you guess?")) within the loop.

Python: How do I repeat a false while loop?

I can't get it to actually repeat the while loop.
I've tried having it register a true value, or make it continue or break out of the loop. But nothing works.
xvalue = int(input("Enter a test value to test if it works: "))
while xvalue >= Limit:
print("\a\a\a")
else:
continue
xvalue = int(input("Updating Value: "))
Can someone suggest something?
I've also written it so that it says:
else:
return True
But that doesn't work. (I get an error)I just need it to keep repeating the while loop until it becomes true on the first condition. And then rings.
I don't entirely follow the intent of your code. I think you want something along the following lines:
while True:
xvalue = int(input("Enter a value: "))
if xvalue < Limit:
break
print("\a\a\a")
There are a bunch of problems with your code, but there are a few big problems here.
First, the else in while...else doesn't mean what you think it does. It's not like in if...else. In while...else, the else block is executed if your while statement becomes False--note that that does not include if you break out of the loop or there's an error. In your code, the else block would be executed when xvalue < Limit, since that's the opposite of your Boolean expression for the while.
Second, because the else block is executed after the loop, putting continue in there doesn't make any sense, since there's no longer any loop to iterate over. Not only that, even if there were a loop continuing, the fact that you stuck continue before xvalue = int(input... means that the loop will be restarted before the user gets a chance to put in an updated value. You would need to put continue after the reassignment, and at that point, there's no point to putting in the continue at all.
So basically, what you're looking for is:
xvalue = int(input("Enter a test value to see if it works: "))
while xvalue >= Limit:
print ("\a\a\a")
xvalue = int(input("Please try another value: "))
Updated after OP comments:
xvalue = int(input("Enter a test value to see if it works: "))
while xvalue < Limit: # Repeats until user gives a value above limit
xvalue = int(input("Please try another value: "))
else:
while True: # Causes bell to ring infinitely
print ("\a\a\a")
Can someone suggest something I've written it so that it says:
else: return True but that doesn't work. I just need it to keep repeating the while loop until it becomes true on the first condition. And then rings.
You could do the following:
Value = False
while Value == False:
#code to do while looping
#code to do after looping
or:
Value = False
While 1:
#code for inside the loop
if Value == True
break
Furthermore, your question was not really describing enough, so don't blame me if i didn't understand

Categories