How to countdown and count up forever endlessly - python

i = 10
while i>=1:
print("count down in " + str(i))
i = i - 1 #or i +=1
if i<10:
print("blasting off")
if i==0:
print("ready in " +str(i))
while i<=10:
print("starting up in " + str(i))
i +=1
how to reloop this endlessly like 10 to 0 than 0 to 10 forever

Put your two loops inside an infinite outer loop, for example:
while True:
for i in range(10,1,-1):
print(i)
for i in range(1,10):
print(i)

In python there is an easy way to do endless cycles. You can use the while(True), which will be always true. I hope this helped.
i = 10
temp = True
while(True):
i = 10
while i>=1:
print("count down in " + str(i)
i -= 1
if i<10:
print("blasting off")
if i==0:
print("ready in " +str(i))
while i<=10:
print("starting up in " + str(i))
i +=1

count_up = 0
count_down = 10
while True:
count_up += 1
count_down -= 1
print("Count_up: ", count_up)
print("Count_down:", count_down)
if count_up == 10: # once it counts up to 10 reset to 0
count_up = 0
if count_down == 0: # once it dounts down to 0 reset to 10
count_down = 10
This will go up 10 and down 10 endlessley
or if you just want to use 1 variable in this case i:
i = 10
while True:
print(i)
i -= 1
if i == 0:
for j in range(10):
print(i)
i += 1

This one here uses a generator, which is a construct in python that yields values whenever asked for the next one. The cool thing about it is that you can separate your value generation logic from your other code using these values (even if it's just a print). This helped me before in cases where the code got too entangled to understand easily.
def triangle(vmax):
""" Generator that yields values of a periodic triangle function between 0 to vmax,
starting at vmax. """
# init states
v = vmax - 1 # the last generated value
rising = True # indicates the current direction
# now yield values forever
while True:
if v == vmax:
rising = False
elif v == 0:
rising = True
v += 1 if rising else -1
yield v
t = triangle(10) # create the generator...
vals = [next(t) for i in range(30)] # ... now get 30 values from it
print(vals)

Related

Writing a "Chessboard" function in Python that prints out requested length of binary

I have an assignment for my Python course that I'm struggling with.
We are supposed to make a function that prints out binary as follows:
If the input is:
chessboard(3)
It should print out:
101
010
101
And so forth..
Its a "simple" program but I'm really new to coding.
I can produce a while loop that writes out the correct length and amount of lines but I'm struggling to produce variation between the lines.
This is what I have come up with so far:
def chessboard(n):
height = n
length = n
while height > 0:
while length > 0:
print("1", end="")
length -= 1
if length > 0:
print("0", end="")
length -= 1
height -= 1
if length == 0:
break
else:
print()
length = n
With the input:
chessboard(3)
It prints out:
101
101
101
Could someone help me figure out how I could start every other line with zero instead of one?
As I understand it, it is simple :
print("stackoverflow")
def chessboard(n):
finalSentence1 = ""
finalSentence2 = ""
for i in range(n): #we add 0 and 1 as much as we have n
if i%2 == 0: #
finalSentence1 += "1"
finalSentence2 += "0"
else:
finalSentence1 += "0"
finalSentence2 += "1"
for i in range(n): #we print as much as we have n
if i%2 == 0:
print(finalSentence1)
else:
print(finalSentence2)
chessboard(3)
returns :
stackoverflow
101
010
101
I am working on the same kind of assignment, but as we have only covered conditional statements and while loops so far, following the same logic, here is my solution:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101
def chessboard(x):
i = 0
while i < x:
if i % 2 == 0:
row = "10"*x
else:
row = "01"*x
print(row[0:x])
i += 1

Loops and Collatz Conjecture

I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :
start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))
def even_or_odd(number):
if number % 2 == 0:
return 'isEven'
else:
return 'notEven'
def collatz(n):
z = n
counter = 0
while True:
if n != 1:
if even_or_odd(n) == 'isEven':
n = n/2
counter += 1
continue
if even_or_odd(n) == 'notEven':
n = (n*3)+1
counter += 1
continue
else:
print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
return counter
break
def check_biggest_steps(steps_before, steps_after):
if steps_before > steps_after:
return steps_before
if steps_after > steps_before:
return steps_after
if steps_after == steps_before:
return steps_after
def compute_collatz(n_times, collatz_number):
for _ in range(n_times):
before = collatz(collatz_number)
collatz_number += 1
after = collatz(collatz_number)
collatz_number += 1
biggest_steps = check_biggest_steps(before, after)
print('Biggest Steps is :' + str(biggest_steps))
compute_collatz(how_many, start_num)
this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks
Don't read my code until you have tried it yourself.
Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.
.
def collatz(x):
while x != 1:
if x % 2 > 0:
x =((3 * x) + 1)
list_.append(x)
else:
x = (x / 2)
list_.append(x)
return list_
print('Please enter a number: ', end='')
while True:
try:
x = int(input())
list_ = [x]
break
except ValueError:
print('Invaid selection, try again: ', end='')
l = collatz(x)
print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)
you didn't save your biggest_steps and compared always the last 2 only.
I would suggest following change.
def compute_collatz(n_times, collatz_number):
biggest_steps = 0
for _ in range(n_times):
steps = collatz(collatz_number)
if steps > biggest_steps:
biggest_steps = steps
collatz_number += 1
print('Biggest Steps is :' + str(biggest_steps))

How do I exit this while loop?

I’m having trouble with exiting the following while loop. This is a simple program that prints hello if random value is greater than 5. The program runs fine once but when I try to run it again it goes into an infinite loop.
from random import *
seed()
a = randint(0,10)
b = randint(0,10)
c = randint(0,10)
count = 0
while True:
if a > 5 :
print ("aHello")
count = count + 1
else :
a = randint(0,10)
if b > 5 :
print ("bHello")
count = count + 1
else :
b = randint(0,10)
if c > 5 :
print ("cHello")
count = count + 1
else :
c = randint(0,10)
if count == 20 :
count = 0
break
count = 0
Your while loop might increment the variable count by 0, 1, 2 or 3. This might result in count going from a value below 20 to a value over 20.
For example, if count's value is 18 and the following happens:
a > 5, count += 1
b > 5, count += 1
c > 5, count += 1
After these operations, count's value would be 18 + 3 = 21, which is not 20. Therefore, the condition value == 20 will never be met.
To fix the error, you can either replace the line
if count == 20
with
if count >= 20
or just change your program logic inside the while loop.
Does the following code help?
while True:
if a > 5 :
print ("aHello")
count = count + 1
if count == 20 :
break
else :
a = randint(0,10)
if b > 5 :
print ("bHello")
count = count + 1
if count == 20 :
break
else :
b = randint(0,10)
if c > 5 :
print ("cHello")
count = count + 1
if count == 20 :
break
else :
c = randint(0,10)
You have to check the value of count after incrementing it every time.
The "break" condition might fail if two or more values of the variables a, b, and c are greater than 5. In that case the count will be incremented more than once and count will end up > 20, and the loop can never terminate. You should change:
if count == 20 :
to
if count >= 20:
At the end of iteration, count might be greater than 20 due to multiple increments. So I would update the last if statement to:
if count >= 20:
to feel safe.
If your goal is to stop counting when count is >= 20, then you should use that condition for your while loop and you won't need to break at all, as you only break at the end of the loop anyways.
The new while statement would look like
while count < 20:
# increment count
and then outside of the while loop you can reset count to 0 if you want to use it again for something else.
since you increment count 2 or 3 times in one iteration, it may skip past your count == 20 check
Here's one way to get exactly 20 lines.
from random import seed, randint
seed()
a = randint(0,10)
b = randint(0,10)
c = randint(0,10)
count = iter(range(20))
while True:
try:
if a > 5:
next(count)
print ("aHello")
else:
a = randint(0,10)
if b > 5:
next(count)
print ("bHello")
else:
b = randint(0,10)
if c > 5:
next(count)
print ("cHello")
else:
c = randint(0,10)
except StopIteration:
break
Note there is still a lot of repetition in this code. Storing your a,b,c variables in a list instead of as separate variables would allow the code to be simplified further

python - infinite coin flip that stops when number of heads = number of tails

I'm new to python and I'm trying to create a coinflip loop which will keep flipping and counting the number of flips until the number of heads = the number of tails, where it will stop and print the total number of flips it took to reach that. I'm trying to get the results in order to work on my maths coursework, but I cannot seem to figure out how to get it to stop or print the results, and when I do it prints 0. Here is the code I have so far:
import random
heads = 1
tails = sum(random.choice(['head', 'tail']) == 'tail'
count = 0
while True:
coinresult = random.randint(1, 2) if heads == tails:
break
print("The number of flips was {count}".format(count = heads + tails))
not sure what is going on with your indentation but try this:
import random
heads = 0 #initialize the count variables
tails = 0
while True:
coinresult = random.randint(1, 2) #flip coin
if coinresult == 1: #if result = 1 then increment heads counter
heads += 1
elif coinresult == 2: #if result = 2 then increment tails counter
tails += 1
if heads == tails: #check if counts are equal and break loop if they are
break
print("The number of flips was {count}".format(count = heads + tails))
import itertools as it
import random
def flips():
while True:
yield (random.getrandbits(1)<<1) - 1
def cumsum(seq):
s = 0
for i in seq:
s += i
yield s
def length(seq):
n = 0
for _ in seq:
n += 1
return n
print("The number of flips was {}".format(length(it.takewhile((0L).__cmp__, cumsum(flips())))))
I think this will be a nice implementation
import random
s = 0
iteration = 0
while True:
coin = random.sample([-1,1], 1)[0]
s = s + coin
iteration = iteration + 1
if s == 0:
break
print(iteration)

ConnectFour in python: embedding a while loop under a for loop

So I'm trying to implement a ConnectFour game in python, and I'm having some trouble with counting the pieces (from a single player) that are lined up together in a row. My code:
class ConnectFour(object):
def __init__(self):
self.row=6
self.col=7
self.board = []
#initialize the board
for arow in range(self.row):
row = []
for acol in range(self.col):
row.append(None)
self.board.append(row)
#function for counting the number of the same pieces in a row
def count_it(self, row, column, step_row, step_col):
assert row >= 0 and row < 6 and column >= 0 and column < 7
assert step_row != 0 or step_col != 0
counter1 = 0
counter2 = 0
if self.board[row][column] == None:
return 0
elif self.board[row][column] == 1:
for i in range(6):
while self.board[row + (i*step_row)][column + (i*step_col)] == 1:
counter1 += 1
return counter1
else:
for i in range(6):
while self.board[row + (i * step_row)][column + (i*step_col)] == 2:
counter2 += 1
return counter2
When I input a location and "step" in my function, I would like to get the number of pieces player 1 or player 2 has lined up but when I enter:
x= ConnectFour()
x.board[5][6] = 1
x.board[4][6] = 1
x.count_it(5,6,-1,0)
I get no output.
There is no need for that while inside for: whenever the while condition is true, it will become an infinite loop since the body of that loop does not affect the condition, it just keeps incrementing a counter forever.
One approach would be a single while loop:
while self.board[row + (counter1*step_row)][column + (counter1*step_col)] == 1:
counter1 += 1
Another approach is to leave the for loop, but i and counter1 actually serve the same purpose:
for i in range(6):
if self.board[row + (i*step_row)][column + (i*step_col)] != 1:
break
counter1 += 1
In both cases, take care of array boundaries, either by some ifs, or by placing sentinels at the border of the array.

Categories