How to get back to start of loop from else - python

x=0
y=0
while 1==1:
while y!=5:
y=y+1
print(str(x) + str(y))
else:
x=x+1
#NOW GO TO WHILE 1==1 AND DO THAT AGAIN
This code should print 01; 02; 03; 04; 05 and then it should print 11; 12; 13; 14; 15. But in reality it does only the first five prints because I don't know how to get to the start again after else:.
EDIT: I am so sorry, i tried to make the code easier to understand and i made few mistakes instead, that werent really a problem.

Here's a working code with a similar structure than yours :
x = 0
y = 0
while x != 2:
while y != 5:
y = y + 1
print(str(x) + str(y))
else:
y = 0
x = x + 1
But please don't do that. Instead :
for x in range(2):
for y in range(5):
print '%d%d' % (x,y+1)

I would say a better approach is to do a nested for loop.

from itertools import count
for x in count():
[print('{}{}'.format(x, y)) for y in range(1, 6)]
and it's Pythonic (hope that wasn't your homework).

Just remove else: and use formatted print to avoid printing the sum.
A better version of your code is:
x = 0
while 1 == 1:
y = 1
while y <= 5:
print '%d%d' % (x,y)
y = y+1
x = x+1

First of all your code outputs:
1
2
3
4
5
and then stops. What you are asking for is this:
01
02
03
04
05
11
12
13
[...]
To get this output you need an infinite loop which continuously increments x to do this start off with this piece of code:
x = -1
while True:
x += 1
You then need a loop which will increment y from 1 to 5 and print the string concatenation of x and y:
for y in range(5):
print(str(x) + str(y+1))
Nest the for loop in the while loop and voila!
x = -1
while True:
x += 1
for y in range(5):
print(str(x) + str(y+1))

Related

Is there a way I can compare the same variable and choose the higher one and print it?

The value of y is changing every time the while loops continues, I tried the watchpoints modules but I need a way to find out the highest y has ever been and print it, I'll print the code that I'm trying to get to work.
import random
from watchpoints import watch
def alg(I):
print(I)
x = 1
while i > 1:
if (i % 2) == 0:
i = int(i / 2)
x = x + 1
else:
i = int(3 * i + 1)
x = x + 1
print(I)
y = 1
if i in range(1, 9):
y = 1
if i in range(10, 99):
y = 2
if i in range(100, 999):
y = 3
if i in range(1000, 9999):
y = 4
watch(a)#I want to know when y reachest the highest
print(y, "is the max number of caracters")#then print it
print("numero passaggi = ", str(x))
print("1: choice")
print("2: random")
type = int(input(" 1 or 2: "))
if type == 1:
i = input("Enter a number: ")
alg(int(I))
elif type == 2:
i = random.randint(1, 100) # 10^9
alg(I)
else:
print("Enter 1 or 2")
I want to know when y reaches the highest and print it below.
There are many ways to do this, but since you seem interested in "watching" the values of y as they change, one good option might be to make your alg function a generator that yields the values of y. The caller can then do whatever it wants with those values, including taking the max of them.
Note that instead of doing this kind of thing to figure out how many digits a number has:
if i in range(1, 9):
y = 1
if i in range(10, 99):
y = 2
if i in range(100, 999):
y = 3
if i in range(1000, 9999):
y = 4
you can just do:
y = len(str(i))
i.e. turn it into a string and then count the characters.
def alg(i: int):
x = 1
while i > 1:
if i % 2 == 0:
i = i // 2
x += 1
else:
i = 3 * i + 1
x = x + 1
print(f"i: {i}")
yield len(str(i))
print(f"numero passaggi = {x}")
print(f"Max number of digits: {max(alg(50))}")
i: 25
i: 76
i: 38
i: 19
i: 58
i: 29
i: 88
i: 44
i: 22
i: 11
i: 34
i: 17
i: 52
i: 26
i: 13
i: 40
i: 20
i: 10
i: 5
i: 16
i: 8
i: 4
i: 2
i: 1
numero passaggi = 25
Max number of digits: 2
The simplest method would be to create another variable to store the highest value that y has achieved and run a check each loop to see if the new y value is larger than the previous max.
Here is an example:
def exampleFunc():
i = 0
y = yMax = 0
while i < 20:
y = random.randint(1, 100)
if y > yMax:
yMax = y
i += 1
print(yMax)
The easiest way to approach something like this is to transform your function into one that returns all intermediate values, and then aggregate those (in this case, using the builtin max()).
from math import log10
def collatz_seq(n):
yield n
while n > 1:
if n % 2:
n = 3 * n + 1
else:
n //= 2
yield n
def print_stats(n):
seq = collatz_seq(n)
idx, val = max(enumerate(seq), key=lambda x: x[1])
digits = int(log10(val)) + 1
print(f"{digits} is the max number digits")
print(f"{idx} is the iteration number")
Here I use enumerate() to give me the index of each value, and I use math.log10() to obtain the number of digits in the number (minus one).

boolean string not counted in while/if statement in python[3.8]

I'm a beginner programmer and chose python[3.8] as my choice to learn. I don't even know what to ask or how to search this site. My program counts 30 to 40 and prints 'Go' for multiples of 3 and strings of 3 and remainders of 3. It counts Go's. Output should be 10 but it's 3. It's not counting the strings. There is no error msgs.
`enter code here`
s = '3'
x = 40
y = 30
num = 0
while y < x :
y=y+1
if y % 3 == 0 or y % 10 == 3 or s in 'y' :
print('Go',y)
num = num + 1
print(num, 'Go\'s')
I think the problem here is to understand how python works.
When you write s in 'y' it will always return false because y here is a character that composes the string which value is ythe character.
So what you'll need to do is use the function str(param) to convert your integer to a string with the same value.
This is a code that works the way you want to.
s = '3'
x = 40
y = 30
num = 0
while y < x :
if y % 3 == 0 or y % 10 == 3 or s in str(y) :
print('Go',y)
num = num + 1
y=y+1
print(num, 'Go\'s')

determine the position of a number after removing numbers containing 4 (python)

The question is like this: Starting from 1, if I give you a number, say 6, I want you to find out what number is in position 6, after removing number containing 4. Result: 7
My script is like this:
x = int(input('What position do you want? '))
y = 0 #variable to iterate until y = x
z = 1 #count how many iteration
while y < x:
y_str = str(y)
if '4' in y_str:
z += 1
continue
else:
y += 1
z += 1
print(z)
But I don't know why the code don't stop. What's wrong with my code
You probably want something like this:
x = int( input( 'What position do you want? ' ) )
y = 0
z = 0
while y < x:
if '4' in str(y):
z += 1
y += 1
print (z+y)
if you want to also go the additional skipped steps alternate the while with this:
while y < x + z:
your old code wasn't working, since your loop was stuck at the moment, when it first encountered something containing the '4'. You then were not incrementing the y, which then resulted in finding the '4' over and over again while further not incrementing y.
your program will go into an infinite loop when it first encounters a number which contains digit 4 because in the following code portion you are not updating y and continuing.
if '4' in y_str:
z += 1
continue

What's wrong with my Python 2 program?

https://www.urionlinejudge.com.br/judge/en/problems/view/1145
Write an program that reads two numbers X and Y (X < Y). After this, show a sequence of 1 to y, passing to the next line to each X numbers.
Input
The input contains two integer numbers X (1 < X < 20) and Y (X < Y < 100000).
Output
Each sequence must be printed in one line, with a blank space between each number.
My code is here:
x,y = raw_input().split(" ")
x = int(x)
xr = x
y = int(y)
lis = []
for i in range(1, y+1):
lis.append(i)
j = 0
for i in range(1, y+1):
while j <= x:
try:
if j < x:
print str(lis[j]),
j=j+1
else:
if x == y:
break
else:
print ""
x = xr + x
except IndexError:
break
Code's output is accurate. But the website is not accepting my code for some reason. Please help me find the bug?
Maybe the problem in on the line print str(lis[j]),, which add a space after the third digit and the site don't consider this valid, the problem say "with a blank space between each number." and maybe this is considered invalid.
Another possible solution is to split the list with the X numbers in lists of Y elements and print them with something like print " ".join(lis[Xs:Xf])
If you need just print you probably don't need list.
I don't know how to format code from phone.
sx,sy = raw_input().split(" ")
x = int(sx)
y = int(sy)
lines = int(y/x)+1
for line in range(lines):
offset = x*line
for i in range(x):
print i+offset,
if i+offset>=y:
print
break
print

Please review my code

Hi all I'm new to programming, and trying to understand while loop in Python.
I want to print the following
print 2
print 4
print 6
print 8
print 10
print "Goodbye!"
Here's what I wrote
x = 0
sum = x
while (sum != 10):
x = x + 2
print x
sum = x + 2
Print ('Good bye!')
Can any one please let me know where am I going wrong..
The most direct fix:
x = 0
sum = x
while (sum <= 10):
x = x + 2
print x
sum = x + 2
print ('Good bye!') # <-- lower case, unindented
A shorter solution:
for x in range(2, 12, 2): # start at 2, increment by 2, up to but not including 12
print x
print 'Good bye!'

Categories