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

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')

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).

Finding even numbers with while as

I'm doing this assignment:
Write a program that prints all even numbers less than the input
number using the while loop.
The input format:
The maximum number N that varies from 1 to 200.
The output format:
All even numbers less than N in ascending order. Each number must be
on a separate line.
N = int(input())
i = 0
while 200 >= N >= 1:
i += 1
if i % 2 == 0 and N > i:
print(i)
and its output like:
10 # this is my input
2
4
6
8
but there is an error about time exceed.
The simple code would be:
import math
N = int(input(""))
print("1. " + str(N))
num = 1
while num < math.ceil(N/2):
print (str(num) + ". " + str(num * 2))
num += 1
The problem is that the while loop never stops
while 200 >= N >= 1 In this case because you never change the value of N the condition will always be true. Maybe you can do something more like this:
N = int(input())
if N > 0 and N <= 200:
i = 0
while i < N:
i += 2
print(i)
else
print("The input can only be a number from 1 to 200")

String concatenation in while loop not working

I'm trying to create a Python program that converts a decimal to binary.
Currently I have
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ()
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = remainder + 0
print (working, x)
else:
x = remainder + 1
print (working, x)
print ("I believe your binary number is " ,x)
The while works on it's own if I print after that, but the if/else doesn't. I am trying to create a string that is added to with each successive division. Currently, if my starting int is 76, my output is
38 0
38 0
19 0
19 0
9 2
4 2
2 0
2 0
1 0
1 0
0 2
I am trying to get my output to instead be
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
This is my first attempt at string concatenation and I've tried a few variations of the above code to similar results.
There are a few issues with the code you’ve provided:
x starts with a value of (), and in any case, rather than concatenating strings to it, you’re adding numbers within the loop.
You’re trying to append the numbers rather than prepend, so the result would be reversed if it worked.
Your second print is not inside the conditional, so the output is duplicated.
What you need to do is initialize x with an empty string and then prepend strings to it:
working = int(input("Please enter a non-negative decimal number to convert to binary: "))
x = ""
while working != 0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = "0" + x
else:
x = "1" + x
print (working, x)
print ("I believe your binary number is", x)
Output:
λ python convert-to-binary.py
Please enter a non-negative decimal number to convert to binary: 76
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
I believe your binary number is 1001100
The problem is that you are not working with strings. You are first creating an empty tuple for x, and then overwriting that with an integer value later.
To do what you are attempting, you need to treat x as a string, and append the string literals '0' and '1' to it.
Try this instead:
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ''
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x += '0'
print (working, x)
else:
x += '1'
print (working, x)
print ("I believe your binary number is " , x[::-1])
Note how x is initially declared as an empty string '' instead of the empty tuple (). This makes it so that when you use the += operator later to append 0 or 1 to it, that it is treated as string concatenation instead of addition.
It should be
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ""
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = x + str(remainder)
print (working, x)
else:
x = x + str(remainder)
print (working, x)
print ("I believe your binary number is " ,x[::-1])
Change your code to below:
if remainder == 0:
x = str(remainder) + '0'
print (working, x)
else:
x = str(remainder) + '1'
print (working, x)
in your code, python interprets as an int you have to cast it to string.
another way is using built-in function bin(working), directly converts from number to binary value.

Credit Card Number Validator Function [Python 3]

I am a Starter in Python programming , and I took the challenge I found in the internet ( Credit Card Number Validator {Luhn Algorithm} ) and i wrote this Function :
def CheckNumber(CreditCardNumber) :
CheckNumberBool = False
CreditCardNumber = list(map(int, CreditCardNumber))
x = 1
y = 0
WorkingList = list()
#--------------------------------------------------#
while x <= 15 :
WorkingList[x].append(CreditCardNumber[x] * 2)
x += 2
#--------------------------------------------------#
while y <= 15 :
WorkingList[y].append(CreditCardNumber[y])
y += 2
#--------------------------------------------------#
WorkingListStr = str(sum(WorkingList))
#--------------------------------------------------#
while y <= 15 :
if WorkingList[y] >= 10 :
for x in WorkingListStr :
WorkingList.append(int(x))
y += 1
#--------------------------------------------------#
if sum(WorkingList) % 10 == 0 :
CheckNumberBool = True
print("This is a Valid Credit Card Number")
else :
CheckNumberBool = False
print("This isn't a Valid Credit Card Number")
But the problem is that when i run it in my Terminal Command Line (python3 myfile.py) , I get this error :
File "Credit_Card_Algorithm.py", line 13, in CheckNumber
WorkingList[x].append(CreditCardNumber[x] * 2)
IndexError: list index out of range
Thanks to all of your very helpful suggestions and sorry if i made a mistake , this is my first time writing to the huge StackOverflow Community ;-D

How to get back to start of loop from else

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

Categories