Python Restarting a loop - python

How can I restart the loop in the following code after it hits 1 since in 3N+1 it goes 1>4>2>1?
Code:
import math
import random
num = 1
NumTF = False
play = True
while play:
if num % 2 == 0:
num = num / 2
else:
num = 3 * num + 1
print(num)
if num == 1:
play = False
if play == False:
num += 1 and play == True

I'm assuming that you want to end the loop, because ...Collatz Conjecture.
All you have to do is add this simple if statement to the end:
elif num == 1:
play = False
after the if num%2 == 0 statement, so the while loop ends. Currently, your doing this after your doing num = 3*num+1, which makes it 4, so that case never happens. as rv.kvetch mentioned, the play==True does unexpected things, so just delete everything after print(num), as those are unnecessary.

Related

why does my python while loop infinitely?

I am trying to do a while loop that execute a function while the verification is not changed.
my code looks like this:
from time import sleep
verif = 0
num = 5
def doso(num, verif):
if num%11 == 0:
verif += 1
elif num%14 == 0:
verif += 1
print(num)
return verif
while verif == 0:
doso(num, verif)
num += 1
sleep(1)
so for now it run infinitely... i would like if it stoped when it find a multiple of 11 or 14
**its an example
Try updating the variable:
while verif == 0:
verif = doso(num, verif)
num += 1
sleep(1)
To avoid running into an XY problem, note that you do not need verif at all. You can simply do:
num = 5
while True:
if num%11 == 0 or num%14 == 0:
break
else:
num += 1

How can I check for a key press at any point during a loop?

I am trying to make a timer that counts down to 0, then starts counting up. I am using the time and keyboard modules.
The keyboard module from PyPi.
Everything works as expected, and I am able to press a button to close the program, but it only works at the beginning of each iteration. Is there a way for it to check for a key press at any point while the loop is running? Do I need to be using a different module?
This is my code:
import time
import keyboard
m = 2
s = 0
count_down = True
while True:
if keyboard.is_pressed('q'):
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
Using callback is common approach in such case, here is solution:
import time
import keyboard
m = 2
s = 0
count_down = True
break_loop_flag = False
def handle_q_button():
print('q pressed')
global break_loop_flag
break_loop_flag = True
keyboard.add_hotkey('q', handle_q_button)
while True:
if break_loop_flag:
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1q
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
If you want to do any two things in parallel, independently of another, you need to consider using multiprocessing. However, even if you do, your loop will either still need to check if a key has been registered in the other process, or you need to terminate the process running the loop forcefully, which may result in unexpected outcomes.
However, in your case, since there are no side effects like files being written, this would work:
import time
import keyboard
from multiprocessing import Process
def print_loop():
m = 2
s = 0
count_down = True
while True:
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
def main():
p = Process(target=print_loop)
p.start()
# this loop runs truly in parallel with the print loop, constantly checking
while True:
if keyboard.is_pressed('q'):
break
# force the print loop to stop immediately, without finishing the current iteration
p.kill()
if __name__ == '__main__':
main()

Check whether a string is a valid number

I need to check if a string is a valid number or not.
Here are some examples of valid:
1234
-1234
12.4
0.6
-0.6
-1234567890.123456789
Non-valid:
+123
123.
.6
00.6
12-.6335
If the first digit is a 0, a decimal point "." must come after it.
I have tried the following code but it says "time limit exceeded". I'm not sure what that means.
def valid_float(number_string):
counter = 0
if number_string[0].isdigit() or number_string[0] == "-" or number_string[0] == "0":
while number_string[0] == "-":
if number_string[1].isdigit():
counter += 1
else:
counter = 0
while number_string[0].isdigit():
if number_string[1] == "." and number_string[2].isdigit():
counter += 1
else:
counter = 0
while number_string[0] == "0":
if number_string[1] == ".":
counter += 1
else:
counter = 0
if counter == 3:
return True
else:
return False
else:
counter = 0
The error you get means that the program keeps going for a long time because it is 'stuck' somewhere. Most of the time its because of a bad recursion function or, in this case, a while loop that will loop forever.
Your while loops will loop forever because you don't change the thing it checks as condition: if the condition is true in the beginning it will be true all the time so the program will never quit the while loop.
I wanted to correct your code but I can't figure out what you where trying so here is some code that will hopefully help you out:
for i in range(0,len(number_string)):
if i == 0 and number_string[0] == "." :
return false
if i != 0 and number_string[0] == "." :
continue
if i == 0 and number_string[0] == "-" :
continue
if i == 0 and number_string[0] == "0" and len(number_string[0])>1:
if number_string[1] != "." :
return false
if number_string[i].isdigit():
continue
return false

Trying to find the next prime number

MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1

List index out of range when coding a valid move for board game

Hey everyone im new here and im trying to make a game called HiQ now i got the board drawn and everything and i can click on one of the pieces, but when i do the piece does change color and i get an error in the shell as well (listed below) im not sure why im getting this and i was hoping you guys could give me better insight. Ill provide my code below as well and it is coded in python 3, thank you
builtins.IndexError: list index out of range
boardcirc =[[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[1,1,1,1,1,1,1,1,1],
[1,1,1,1,2,1,1,1,1],
[1,1,1,1,1,1,1,1,1],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0]]
def HiQ():
splash_screen()
make_board()
def make_board():
make_sqr()
make_circ()
get_click()
def get_click():
global count, boardcirc
while 1!=0:
count = count - 1
displaymessage("Pieces: " + str(count))
where = win.getMouse()
col = where.x//90
row = where.y//90
valid_move(row,col)
make_move(row,col)
def valid_move(row,col):
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
if boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
if boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
if boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
def make_move(row,col):
while valid_move(row,col) == True:
col = (col*85)+42
row = (row*85)+42
circ = Circle(Point(col,row),35)
circ.setFill("white")
circ.draw(win)
thats everything that applies to the error
For your valid_move(row,col), you can't have all those if statements.
Instead of doing this, use elif's after the initial if statement, and don't forget to write an else statement
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
elif boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
elif boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
elif boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
else:
return False

Categories