Variable not changing after trying to update it - python-3.x

I'm trying to make a variable update after a line of the code is passed. The problem I'm having is that, once that line of the code is passed and then printed again, the variable is the default one, in this case 10.
I don't know if I'm doing something wrong or anything, but I just can't see where I'm failing, maybe because I'm a beginner. Tried everything I could think of before asking for help but at this point I'm desperate. Thanks.
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
print(number + 1)
elif numberAction == "REM":
print(number - 1)
print(f"{number} : after updating.")

This is because you aren't updating the value stored in number. My guess is that you are trying to do so in your if/elif clauses; if that is the case, this should work:
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
number += 1 # equivalent to 'number = number + 1'
elif numberAction == "REM":
number -= 1 # equivalent to 'number = number - 1'
print(number)
print(f"{number} : after updating.")
Originally, you were only printing number after some operation. In order for the value in number to change, you would need to reassign some value to the variable.

Notice how I perform a computation where you performed output. I moved output below the computations.
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
number = number + 1
elif numberAction == "REM":
number = number - 1
print(number)
print(f"{number} : after updating.")

To add or subtract 1 from the variable num you need to do addition or subtraction operation on the value and store that in the same variable to "update" it.
In your code, in line 12 and line 14, you do the addition, subtraction respectively but you print the result instead of storing the result in the variable number which would "update" the prestored value which in this case is 10.
So, replacing print(number + 1) from line 12 with number += 1 to add 1 to the previous value and replacing print(number - 1) from line 14 with number -= 1 to subtract one to "update" the stored value based on the user's choice.
Then, in the last line when you print the number variable it will display the "updated" value of the variable number
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
number += 1
elif numberAction == "REM":
number -= 1
print(f"{number} : after updating.")

Related

How can I check whether neighbor (previous and next) digits in a row differ in 1 (Python 3)

is it possible to create a code(without list comprehensions, please) that will compare whether neighbor (previous and next) digits in a row differ in 1 so if the condition is met returns the row and returns "good", if not met - "bad". Also, the difference between 9 and 0 doesn't consider as 1. Besides, I need to check whether the only one-digit number and return "one digit" then. I see for me just now it's tricky, so please help!
For example:
for (12345432):
return "good"
for (1793):
return "bad"
for (7):
return "one digit"
`
Another solution (with check for one digit):
i = 12345432
if i < 10:
print("One Digit")
else:
for a, b in zip(str(i), str(i)[1:]):
if abs(int(a) - int(b)) != 1:
print("Bad")
break
else:
print("Good")
Prints:
Good
You can keep (integer-) dividing the number and compare the previously seen digit and the new digit:
def good_or_bad(num):
digit_prev = num % 10
while num != 0:
num, digit = divmod(num, 10)
if abs(digit - digit_prev) > 1:
return 'bad'
digit_prev = digit
return 'good'
print(good_or_bad(12345432)) # good
print(good_or_bad(1793)) # bad

Polydivisible Calculator Fails, Despite Previous Implementation Working

To begin, a definition:
A polydivisible number is an integer number where the first n digits of the number (from left to right) is perfectly divisible by n. For example, the integer 141 is polydivisible since:
1 % 1 == 0
14 % 2 == 0
141 % 3 == 0
I'm working on a recursive polydivisible checker, which, given a number, will check to see if that number is polydivisible, and if not, recursively check every other number after until it reaches a number that is polydivisible.
Unfortunately, my code doesn't work the way I want it to. Interestingly, when I input a number that is already polydivisible, it does its job and outputs that polydivisible number. The problem occurs when I input a non-polydivisible number, such as 13. The next polydivisible number should be 14, yet the program fails to output it. Instead, it gets stuck in an infinite loop until the memory runs out.
Here's the code I have:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None
I'm assuming the problem occurs in the else statement inside the while loop, where, if the number fails to be polydivisible, the program resets i to 0, and adds 1 to the original number so it can start checking the new number. However, like I explained, it doesn't work the way I want it to.
Any idea what might be wrong with the code, and how to make sure it stops and outputs the correct polydivisible number when it reaches one (like 14)?
(Also note that this checker is only supposed to accept non-negative numbers, hence the initial if conditional)
The mistake is that you are no updating number after incrementing num.
Here is working code:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None
I have a similar answer to #PranavaGande, the reason is I did not find any way to iterate an Int. Probably because there isn't one...Duh !!!
def is_polydivisible(n):
str_n = str(n)
list_2 = []
for i in range(len(str_n)):
list_2.append(len(str_n[:i+1]))
print(list_2)
list_1 = []
new_n = 0
for i in range(len(str_n)):
new_n = int(str_n[:i+1])
list_1.append(new_n)
print(list_1)
products_of_lists = []
for n1, n2 in zip(list_1, list_2):
products_of_lists.append(n1 % n2)
print(products_of_lists)
for val in products_of_lists:
if val != 0:
return False
return True
Now, I apologise for this many lines of code as it has to be smaller. However every integer has to be split individually and then divided by its index [Starting from 1 not 0]. Therefore I found it easier to list both of them and divide them index wise.
There is much shorter code than mine, however I hope this serves the purpose to find if the number is Polydivisible or Not. Of-Course you can tweak the code to find the values, where the quotient goes into decimals, returning a remainder which is Non-zero.

Python Collatz Infinite Loop

Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return(result)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue

Decimal to binary self challenge

I have tried to write a small program that converts a decimal to binary that doesn't use the inbuilt function that do that. My program won't convert anything over 12287. 12288 just spits out an infinite loop. Where have I gone wrong? why can't I get above 12287?
while (number != 1) or (number != 0):
a = number // 2
b = number % 2
number = a
if b == 0:
output = "0" + output
if number == 1:
output = "1" + output
break
else:
output = "1" + output
You just need to change the condition from:
while (number != 1) or (number != 0):
To:
while number != 0:
Other than that, your code looks OK. Here is a more streamlined version of the same basic idea:
output = ""
while number:
number, b = divmod(number, 2)
output = str(b) + output
For 12288, number eventually becomes 0. This means while condition is always True.
Note that b becomes 0, so number will stay at 0.

how to convert decimal to binary by using repeated division in python

how to convert decimal to binary by using repeated division in python?
i know i have to use a while loop, and use modulus sign and others {%} and {//} to do this...but i need some kind of example for me to understand how its done so i can understand completely.
CORRECT ME, if I'm wrong:
number = int(input("Enter a numberto convert into binary: "))
result = ""
while number != 0:
remainder = number % 2 # gives the exact remainder
times = number // 2
result = str(remainder) + result
print("The binary representation is", result)
break
Thank You
Making a "break" without any condition, makes the loop useless, so the code only executes once no matter what.
-
If you don't need to keep the original number, you can change "number" as you go.
If you do need to keep the original number, you can make a different variable like "times".
You seem to have mixed these two scenarios together.
-
If you want to print all the steps, the print will be inside the loop so it prints multiple times.
If you only want to print the final result, then the print goes outside the loop.
while number != 0:
remainder = number % 2 # gives the exact remainder
number = number // 2
result = str(remainder) + result
print("The binary representation is", result)
-
The concatenation line:
Putting the print inside the loop might help you see how it works.
we can make an example:
the value in result might be "11010" (a string, with quotes)
the value in remainder might be 0 (an integer, no quotes)
str(remainder) turns the remainder into a string = "0" instead of 0
So when we look at the assignment statement:
result = str(remainder) + result
The right side of the assignment operator = is evaulated first.
The right side of the = is
str(remainder) + result
which, as we went over above has the values:
"0" + "11010"
This is string concatenation. It just puts one string on the end of the other one. The result is:
"0 11010"
"011010"
That is the value evaluated on the right side of the assignment statement.
result = "011010"
Now that is the value of result.
B_Number = 0
cnt = 0
while (N != 0):
rem = N % 2
c = pow(10, cnt)
B_Number += rem * c
N //= 2
# Count used to store exponent value
cnt += 1
return B_Number

Resources