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
Related
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.
I wasn't too sure what to call this post.
Anyways, what I'm trying to do is assign 'diff' to a user input, and if 'diff' is not average or advanced, recall the function so that the user can (hopefully) enter average or advanced.
However, no matter what I input, it will always recall the function, even if the input is 'average' or 'advanced'.
Code -
def choices():
global diff
diff = input("Choose a difficulty: Average/Advanced ")
diff = diff.lower()
x = 0
while x > 1:
if diff == 'average':
print('Difficulty set to average.')
x = x + 1
elif diff == 'advanced':
print('Difficulty set to advanced.')
x = x + 1
if diff != 'average' or 'advanced':
print('Your input is invalid. Please try again.')
choices()
choices()
The same thing is also happening for another decision I have that is similar to this, but I figured that there's no point in putting it down if it follows the same logic.
Sorry if this is a stupid question. I'm only a beginner.
You can also wrap it all into the while loop, I'm new to python but spawning recursive instances of a function seems dangerous to me.
def choices():
global diff
while true:
diff = input("Choose a difficulty: Average/Advanced ")
diff = diff.lower()
if diff == 'average':
print('Difficulty set to average.')
return
if diff == 'advanced':
print('Difficulty set to advanced.')
return
print('Your input is invalid. Please try again.')
Your first bug lies in this statement:
while x > 1:
You'll never execute the code within that loop because you set x = 0 at the top of the function. When it hits the while loop, x = 0 and so the while loop will be completely skipped.
There are a number of other problems, but this one is what's stopping the "if" logic from running.
I'm so confused about this function that I can't determine exactly what you're trying to do so I can't supply a complete working solution to your problem, only the first rather large bug in it.
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.")
First, in my code i'm asked to enter a value from user and the program should place it in the correct orderly position without using the built-in python sort().
My completed code can do this without repetitively inserting the same element, only with the break command. Now i once i remove the break command the number i enter outputs in the list 3 times instead of 1.
Note: we aren't allowed to use the break statement in this Python course
Currently my code looks like this:
#List of numbers
myList = [1,9,16,24]
#Enter a number to be placed in the list
num = int(input("Enter a number: "))
#For loop to check the placement of entered number
#to compare it and see if it is less than or
#equal to the each and every element in myList
for x in range(0, len(myList)-1):
if num < myList[x]:
myList.insert(x,num)
#break
elif num > myList[x]:
myList.append(num)
#break
print(myList)
ex. output:
[-1,-1,-1,1,9,16,24]
Simple. Have an external condition that you can test at each insertion attempt. If you insert the item, set the condition to false. Then, outside of the loop, if the condition is still true you know the item goes at the end. No breaks involved.
myList = [1,9,16,24]
num = int(input("Enter a number: "))
condition = True
for index, x in enumerate(myList):
if condition and num < x:
myList.insert(index, num)
condition = False
if condition:
myList.append(num)
print(myList)
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!")