I want to print 'double' when x equals 'ok' two times consecutively in the while loop.
My script below:
import random
import time
a = 5
while True:
b = random.randint(0, 10)
print(b)
if a > b:
x = 'ok'
print(x)
You need to track your state.
import random
import time
a = 5
prev = False
while True:
b = random.randint(0, 10)
print(b)
if a > b:
if prev:
print('double')
x = 'ok'
prev = True
else:
x = 'ko'
prev = False
This answer is for a triple version of my question:
import random
import time
a = 5
i=0
rec=[]
while True:
b = random.randint(0, 10)
print(b)
if a > b:
x = 'ok'
# print(x)
rec.append(str(x))
i=i+1
else:
x='ko'
# print(x)
rec.append(str(x))
i=i+1
if i>=3 and (rec[i-1]=='ok' and rec[i-2]=='ok' and rec[i-3]=='ok'):
print('trible')
time.sleep(1)
A similar question was asked earlier but it didn't provide the correct answer.
I am trying to code to test threading in Python in which a ticker ticks every second. I am trying to keep the ticker function named 'clicking' running in a thread whose output is continously being incremented by one every second.
import time
import threading
import queue
q = queue.Queue()
apple = 0
orange = 0
rate = 1
clix = 0
def clicking(clix, rate):
while True:
time.sleep(1)
clix += rate
q.put(clix)
threading.Thread(target=clicking, args=(clix, rate)).start()
curr = q.get()
print(curr)
print('\nClicker Starting...')
endgame = False
while not endgame:
print(f'Clix: {curr}')
print('1. Apple : 10 clix | 2. Orange : 8 clix | 3. Exit')
ch = int(input('\nPurchase ID: '))
if ch == 1 and curr >= 10:
print(f'You have {curr} clix.')
print('Got an Apple!')
apple += 1
rate += 1.1
curr -= 10
elif ch == 2 and curr >= 8:
print('Got an Orange!')
orange += 1
rate += 1.2
curr -= 8
elif ch == 3:
endgame = True
stopflag = True
else:
print('Need more Clix')
But my otuput is always 1 instead of incrementing every second by defined rate. What am I missing? I even tried return clix in place of q.put(clix) but didn't work.
the problem is that you are not updating the curr variable inside the while loop. But do notice that when you write "curr = q.get()" inside the while loop it will get the next value in the queue and not the last value (as I suppose you intend). I guess a more straightforward approach is to keep track on the seconds increment inside your while loop using time.time()
import time
apple = 0
orange = 0
rate = 1
clix = 0
curr = 0
last_ts = time.time()
print('\nClicker Starting...')
endgame = False
while not endgame:
ts = time.time()
curr += (ts - last_ts) * rate
last_ts = ts
print(f'Clix: {curr:.0f}')
print('1. Apple : 10 clix | 2. Orange : 8 clix | 3. Exit')
ch = int(input('\nPurchase ID: '))
if ch == 1 and curr >= 10:
print(f'You have {curr:.0f} clix.')
print('Got an Apple!')
apple += 1
rate *= 1.1 # I guess you meant x1.1
curr -= 10
elif ch == 2 and curr >= 8:
print('Got an Orange!')
orange += 1
rate *= 1.2 # I guess you meant x1.2
curr -= 8
elif ch == 3:
endgame = True
stopflag = True
else:
print('Need more Clix')
this way you can exit properly also, notice that on your example even when the loop breaks the thread continues.
but in case you want to maintain a background thread, I suggest creating a class and storing class variables for the current counter and run condition.
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
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()
We are trying to make a program that solves any maze by recognising all junctions and eliminating the ones that do not lead to the entrance. We managed to create such a program but we are struggling to get the dots to connect to create a proper path. Does anybody have an idea how to do this because we are out of clues...Picture of the result, but the dots aren't connect by a line
The maze is basically a (n)x(n) grid in a numpy array with walls (true) and paths (false) see:picture of maze as seen from the variable explorer
import numpy as np
import maze_utils as mu
import matplotlib.pyplot as plt
size = 101
maze, start = mu.make_maze(size)
start = [start[1],start[0]]
#------------------------------------------------------------------------------
def junctions_finder(maze, size, start):
junctions = [start]
end = []
for y, row in enumerate(maze):
for x, column in enumerate(row):
if maze[x,y] == False:
if x == 0 or x == (size-1) or y == 0 or y == (size-1):
junctions.append([y,x])
end.append([y,x])
while True:
if x+1 < size and y+1 < size and\
maze[x+1,y] == False and maze[x,y+1] == False\
or x+1 < size and y-1 > 0 and\
maze[x+1,y] == False and maze[x,y-1] == False\
or x-1 > 0 and y-1 > 0 and\
maze[(x-1),y] == False and maze[x,(y-1)] == False\
or x-1 > 0 and y+1 < size and\
maze[(x-1),y] == False and maze[x,(y+1)] == False:
junctions.append([y,x])
break
else:
break
return junctions, end
#------------------------------------------------------------------------------
def eliminate_coor(junctions, end, start):
eliminated = []
for row in junctions:
a = row[1]
b = row[0]
connections = 0
U = False
D = False
L = False
R = False
UW = False
DW = False
LW = False
RW = False
SE = False
if row == start or row == end[0]:
connections = 2
SE = True
for i in range(1,size):
if SE == False:
if a+i <= size-1 and DW == False and D == False:
if maze[a+i, b] == True:
DW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a+i,b]:
connections = connections + 1
D = True
if a-i >= 0 and UW == False and U == False:
if maze[a-i, b] == True:
UW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a-i,b]:
connections = connections + 1
U = True
if b+i <= size-1 and RW == False and R == False:
if maze[a, b+i] == True:
RW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a,b+i]:
connections = connections + 1
R = True
if b-i >= 0 and LW == False and L == False:
if maze[a, b-i] == True:
LW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a,b-i]:
connections = connections + 1
L = True
if connections < 2:
eliminated.append([b,a])
return eliminated
#------------------------------------------------------------------------------
def junction_remover(junctions, eliminated):
counter = 0
for index, row in enumerate(junctions):
for erow in (eliminated):
if erow == row:
junctions[index] = -1
counter = counter + 1
for times in range(counter):
junctions.remove(-1)
return junctions, counter
#------------------------------------------------------------------------------
junctions, end = junctions_finder(maze, size, start)
counter = 1
while counter > 0:
eliminated = eliminate_coor(junctions, end, start)
junctions, counter = junction_remover(junctions, eliminated)
start = [start[1],start[0]]
junctions.pop(0)
pyjunc = np.array(junctions)
mu.plot_maze(maze, start=start)
plt.plot(pyjunc[:,0], pyjunc[:,1], 'o')
plt.plot(pyjunc[:,0], pyjunc[:,1]) would connect the dots... Or did you mean you have a bug you can't trace? In your picture it seems there's a beginning, but no end, so it retraces back to the beginning?
plt.plot(pyjunc[:,0], pyjunc[:,1], 'o')
plots the data points in the list with the circle marker 'o'. But you haven't defined a linestyle.
The quickest way to do this is to add it the format shorthand:
plt.plot(pyjunc[:,0], pyjunc[:,1], 'o-')
Which says to use a circle marker and a solid line '-'.
Expanding that out to how matplotlib interprets it, you could write:
plt.plot(pyjunc[:,0], pyjunc[:,1], marker='o', linestyle='-')
You can see the full documentation for plt.plot more ways to customise your plot