it's becoming infinite loop. Please help. I want to make this program to get cubic root of a number that a user inputs. and how many times i need to cubic root the answers till i get 1.
number = float(input("Type your number: "))
steps = 0
croot = number ** 1. / 3
answer = croot ** 1. / 3
while answer != -10000:
number = answer
steps = 1
croot = number ** 1. / 3
if answer == 1.0:
break
print(steps)
CodePudding user response:
The reason you are entering an infinite loop is because you never redefine answer
therefore, you will never exit your while loop because answer
is always the same.
However, we can heavily simplify your code as well:
steps = 0
answer = 0
while answer != 1.0:
steps = 1
number = float(input("Type your number: "))
answer = number ** (1.0 / 3)
print(steps)
First, we start with default values of steps
and answer
. From what I can see, there is no need to define a third variable, croot
.
We are running the loop while the cube root, answer
, is not 1.0
. Therefore, there is no need for an if statement when we can simply make answer != 1.0
our condition for the while loop.
When we are inside the while loop, we increment the value of steps
and take in user input. Then, we can define answer
and print out steps
. This will allow for the loop to break if answer = 1.0
.
I hope this helped answer your question! Please let me know if you need any further clarification or details :)
CodePudding user response:
Your croot and answer are supposed to raise to the power of (1/3)? And you are using the same value for number in the while
loop? Maybe this is what you want?
croot = number ** (1. / 3)
answer = croot ** (1. / 3)
while answer != -10000:
number = answer
steps = 1
croot = number ** 1. / 3
answer = croot ** (1. / 3)
if answer == 1.0:
break
print(steps)