How to make this loop? - python

How would I loop this?
def start():
print('welcome to reduce that fraction')
n=int(input("please enter numerator"))
m=int(input("please enter denominator"))
r=2
while (n%r!=0):
for y in range(2,10,1):
a=n%r
r=r+1
while (m%r!=0):
for x in range(2,10):
b=m%r
r=r+1
print(n/r,"/",m/r)
print("Goodbye")
start()
I am stuck on how to loop it back to the beginning. Any ideas?

I'm assuming you want the function "start()" to re-run after completing. In that case, here's what I'd do:
while True:
start()
This is a boolean while-loop that always holds (Python implicitly parses "while True" as "while True == True"), so the function will keep looping.

Related

My break function isn't working and i dont know why its outside the loop

I am relatively new to code and have been messing around with some functions, i am currently using it for school work and have been practicing code for my course work, however when i tried to do this random code the break function was outside of the loop somehow but i dont know why, any ideas?
var=input("what name would you like to use?: ")
varf= len(var) + 1
def rep():
for i in range(0, varf):
print(var[:i])
for x in range(0, varf):
print(var[x:])
repeat=input("Would you like to go again? Y/N: ")
if repeat.upper() =="Y":
rep()
else:
break
rep()
The code you actually wanted to write goes as follows:
def rep():
for i in range(0, varf):
print(var[:i])
for x in range(0, varf):
print(var[x:])
while True:
var=input("what name would you like to use?: ")
varf= len(var) + 1
rep()
repeat=input("Would you like to go again? Y/N: ")
if repeat.upper() != "Y":
break
Now the break statement is inside the while True: loop body and works as expected.
In your code you have just forgotten to put the user input into a while True: loop to be able to go for another round of user input.

couldnt get output in python program

while True:
n = int (input ("What's n? "))
if n > 0:
break
for _ in range(n):
print("meow")
I can enter the input, but I could receive the output and I didn't have any error in my terminal window, please help where I went wrong.
Your for loop is inside your while loop and after the if statement. When your if statement evaluates to True (i.e. n > 0) then the break instruction will cause the program to exit the while loop. Thus, your for loop will never be executed.
You can learn more about the break statement from this tutorial.
The break statement in Python terminates the current loop and resumes
execution at the next statement
You can fix your code by moving the for loop outside of the while loop as follows:
while True:
n = int(input("What's n? "))
if n > 0:
break
for _ in range(n):
print('meow')

Break inside a function with for

(Python 3.10.4)
I have a for condition and inside this for a have a function that need a break and go back to the top like "continue" do, but i can't use break outside a loop, how can i go back to the top of the code? I will use this function so many times after and i don't want to have so many if in my code
import time
def function1():
if pyautogui.locateCenterOnScreen('file.png')
pyautogui.moveTo(x=612, y263)
time.sleep(1)
break
How can i break the code in this case:
for c in range (0,10):
print('begin for')
#FUNCTION
function1():
#
#
#REST OF THE CODE
It's hard to imagine what you meant by 'break the code' with your incorrect code indentations. I guess you meant to break the for loop
when the function breakes.
Use a variable out side the function to indicate when you're done with your function.
And check for the value of the variable within the for loop to break or pass
br = 0
def function1():
if pyautogui.locateCenterOnScreen('file.png')
pyautogui.moveTo(x=612, y=263)
br = 1
time.sleep(1)
return 0
for c in range (0,10):
print('begin for')
#FUNCTION
function1()
if br == 1:
break
else:
pass
#
#
#REST OF THE CODE

I can't reach a variable in a nested while loop

Here is the problem, it's just a simple program that rolls the dice, but when I write "no" in (want), the loop continues.
import random
play_continue = True
want = ""
want_play = False
while play_continue:
while not want_play:
try:
want = input("Do you want to play?: ")
except:
print("I don't understand what you said")
else:
if want == "no":
play_continue = False
elif want == "yes":
want_play = True
else:
print("I don't understand")
the reason is that you are still on the first step of the toplevel while loop, since the inner one is ongoing, even though you changed the value of play_continue the check never happens because the program never gets back around to it as the inner loop has yet to finish.
you can think of the whole inner loop as a single instruction such as
while play_continue:
do_stuff()
the play_continue condition is only checked once do_stuff() is completed, which in your case it is not

breaking out of the loop?

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!")

Categories