Python while loop subtraction - python

This is a really stupid question but I haven't used this in awhile and can't remember how to do it. I'm doing a recursion problem and need to show the numbers counting down to basically show how the recursion is working. However, I can't seem to figure it out. Here is my code.
def main():
#have user input first number
x = int(input('Enter the first number: '))
#have user input second number
y = int(input('Enter the second number: '))
#calculate result by calling recursive function
result = mult(x, y)
#print the result
print(x, 'times', y, 'is', result)
#define a function that uses recursion
def mult(x, y):
# create a loop to display the numbers
count = y
while count > 0:
print('First number =', x, 'Second number =', count)
count -= 1
#use recursion to multiply the numbers
if x == 0:
return 0
elif x == 1:
return y
else:
return y + mult(x - 1, y)
main()
I need the output to say this:
Enter the first number: 5
Enter the second number: 7
First number = 5 Second Number = 7
First number = 5 Second Number = 6
First number = 5 Second Number = 5
First number = 5 Second Number = 4
First number = 5 Second Number = 3
First number = 5 Second Number = 2
First number = 5 Second Number = 1
5 times 7 = 35
So it's working for the most part, however now it is displaying this:
Enter the first number: 5
Enter the second number: 7
First number = 5 Second number = 7
First number = 5 Second number = 6
First number = 5 Second number = 5
First number = 5 Second number = 4
First number = 5 Second number = 3
First number = 5 Second number = 2
First number = 5 Second number = 1
First number = 4 Second number = 7
First number = 4 Second number = 6
First number = 4 Second number = 5
First number = 4 Second number = 4
First number = 4 Second number = 3
First number = 4 Second number = 2
First number = 4 Second number = 1
First number = 3 Second number = 7
First number = 3 Second number = 6
First number = 3 Second number = 5
First number = 3 Second number = 4
First number = 3 Second number = 3
First number = 3 Second number = 2
First number = 3 Second number = 1
First number = 2 Second number = 7
First number = 2 Second number = 6
First number = 2 Second number = 5
First number = 2 Second number = 4
First number = 2 Second number = 3
First number = 2 Second number = 2
First number = 2 Second number = 1
First number = 1 Second number = 7
First number = 1 Second number = 6
First number = 1 Second number = 5
First number = 1 Second number = 4
First number = 1 Second number = 3
First number = 1 Second number = 2
First number = 1 Second number = 1
5 times 7 is 35

The point of printing the two numbers is to keep track of the recursion. So naturally, the numbers must be printed from inside the recursing function. In other words, you don't want to create an additional loop (using while) to display the numbers, but the recursion is the loop.
You also only want to print the numbers once per recursion step.
What may have additionally confused you is that you have swapped the roles of "first"/x and "second"/y between the desired output and the argument order of the recursion. (You want the "second" number to decrease in the output, but you decrease the first argument (x) of mult.)
It should look like this:
def mult(x, y):
"""Calculate x * y by using recursion."""
print('First number =', x, 'Second number =', y)
if y == 0:
return 0
elif y == 1:
return x
else:
return x + mult(x, y - 1)
if __name__ == '__main__':
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
# calculate result by calling recursive function
result = mult(x, y)
# print the result
print(x, 'times', y, 'is', result)

Just a small change you need to make, you need to update the value of y in the while loop.
#create a loop to display the numbers
while y > 0:
print('First number =', x, 'Second number =', y)
y -= 1

It looks to me like you aren't storing your modified y value. So, the while loop should read like this:
y_temp = y
while y_temp > 0:
print('First number =', x, 'Second number =', y_temp)
y_temp -= 1

Your while loop is outside the recursive call, so the value of y is not getting updated. Move the print statements to be inside the mult function, above the if statement.
def mult(x, y):
print('First number =', x, 'Second number =', y)
print('First number =', x, 'Second number =', y - 1)
if x == 0:
return 0
elif x == 1:
return y
else:
return y + mult(x - 1, y)

You forgot to update y, you're not decreasing y.

Related

Printing the largest number from the outputs (collatz conjecture-python)

I need help for printing the largest number from the multiple outputs. How can I modify this code to do so?
x = int(input("Enter a number : "))
while(x!=1):
if(x%2==0):
x = x/2
print("\n",x)
else:
x = 3*x+1
print("\n",x)
When I typed "20" as the input, I get a list of numbers and I can easily say that 16 is the largest out of the outputs. But it is really hard when the input is big. I need a code to print out the largest number from the outputs
You could create a generator that generates the Collatz sequence and then use the max() function to find the largest number:
def collatz_sequence(x):
yield x
while x > 1:
x = x // 2 if x % 2 == 0 else 3 * x + 1
yield x
print(max(collatz_sequence(5))) # Output: 16

using the calculation number for the next calculation

experts.
I'm trying to define a function (collatz) that:
Asks for a number. If it is even it prints number // 2, if it odd it prints 3 * number + 1. (OK)
The result, whatever it is, must enter a loop until the result is 1. (NOK)
So, i´m not figure out because the result is not used and is in an infinite loop. Any suggestion?
def collatz():
number = int(input('Enter the number: '))
x = number % 2
while number != 1:
if x == 0:
print(f'{number // 2}')
else:
print(f'{3 * number + 1}')
number = number
print(f'{collatz()}')
You need to actually assign the result back to number.
As well:
The divisibility check needs to be in the loop.
The outer print() is not needed.
The f-strings are redundant. print() converts its arguments to string automatically.
def collatz():
number = int(input('Enter the number: '))
while number != 1:
if number % 2 == 0:
number //= 2 # Short for "number = number // 2"
else:
number = 3*number + 1
print(number)
collatz()
Example run:
Enter the number: 3
10
5
16
8
4
2
1

Regarding the def and return function in python

I was writing a program to write the multiplication table of number given by the user.
Here's my code:
def mul_table(n):
for i in range(1,11):
print(n,"x",i,"=",(n * i))
i = i + 1
return(n)
x = int(input("Enter the number: "))
x1 = mul_table(x)
print(x1)
But in the output it shows the number entered by the user also in the end like this (I know have written the value after "return" but if I leave it empty then it shows None, so how can I get rid of this?):
Enter the number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
**5**
Can anyone tell me that how can the program return nothing (absolutely nothing, not even the "None" text or the number entered by the user) in PYTHON 3.9.1 ?
Your mul_table function handles the printing itself. It needs no return value, and you shouldn't print it even if it exists - you should just call the function:
def mul_table(n):
for i in range(1,11):
print(n,"x",i,"=",(n * i))
i = i + 1
# return statement removed here
x = int(input("Enter the number: "))
mul_table(x) # No need to capture the return value or print it
The problem is that mul_table method is returning n and you are printing it with print(x1). Remove this call to print if you don't need it.
There are several issues, here is a working version
def mul_table(n):
for i in range(1,11):
print(n,"x",i,"=",(n * i))
x = int(input("Enter the number: "))
mul_table(x)
You print inside the function, so you don't need to call mul_table in a print statement
You also don't need a return statement in the function (though it returns None if you omit the return statement or use a return statement without a return value)
i = i+1 inside the function is wrong, you are using a for statement where i gets values 1, 2, ..., 10 successively.

Python how to check if value changed

I want to print "Same number" if the new number value equals to the last one(same number), else print number variable value if it has changed. How can I do that?
from random import randint
x=0
number=(randint(0,9))
while(x<10):
x+= 1
if(number=="""LAST PRINTED VALUE NUMBER"""):
print ("Same number")
else:
print(number)
You can chage last number in the while loop:
x, last = 0, -1
while (x < 10):
number = randint(0, 9)
if (number == last):
print ("Same number")
else:
print("Last number is {0} now it is {1}".format(last,number))
last = number
x += 1
Output:
Last number is -1 now it is 1
Last number is 1 now it is 2
Last number is 2 now it is 4
Same number
Last number is 4 now it is 2
Last number is 2 now it is 6
Last number is 6 now it is 7
Same number
Last number is 7 now it is 2
Same number
Just save the last one:
from random import randint
x=0
old = number= randint(0,9)
while(x<10):
x+= 1
if(number==old and x > 0):
print ("Same number")
else:
print(number)
old = number
number = randint(0,9)
from random import randint
x = 0
number = -1
while(x < 10):
y = number
number=(randint(0,9))
x+= 1
if(number== y):
print ("Same number")
else:
print(number)
You just need a third variable. Within the "else" after the print statement, set this third variable to "number".
I have a different method:
from random import randint
new = randint(0, 10)
old = new
for i in range(10):
new = randint(0, 10)
if new == old:
print("Same number ({0})".format(new))
else:
print("Diffrent (Last: {0} Now: {1})".format(old, new))
old = new
Output:
Diffrent (Last: 6 Now: 9)
Diffrent (Last: 9 Now: 0)
Diffrent (Last: 0 Now: 2)
Same number (2)
Diffrent (Last: 2 Now: 6)
Same number (6)
Diffrent (Last: 6 Now: 7)
Diffrent (Last: 7 Now: 4)
Same number (4)
Diffrent (Last: 4 Now: 10)

While loop while rolling dice

I am trying to use a while loop instead of a for loop while rolling dice. I do not think elif is right, but I cannot figure out how to use the while loop within this. This is what I have so far:
import random
def rolldiewhileloop():
number = 10
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
while number > 0:
flip = int(random.random() * 6)
if(flip == 1):
one = one + 1
elif flip == 2:
two = two + 1
elif flip == 3:
three = three + 1
elif flip == 4:
four = four + 1
elif flip == 5:
five = five + 1
elif flip == 6:
six = six + 1
return [one, two, three, four, five, six]
In your current while loop you aren't changing the value of number, so this will be an infinite loop. Since you are starting at 10 and looping until number is less than or equal to zero, you should probably be decrementing by one on each iteration:
number = 10
while number > 0:
number -= 1
# the rest of the loop
Note that number -= 1 is equivalent to number = number - 1.
As a side note, instead of multiplying the result of random.random() it would be better to use random.randint(1, 6). Also, since you are returning an array already it would be more Pythonic to create a list of the results and modify that, rather than creating a separate variable for each possibility. For example:
def rolldiewhileloop():
results = [0] * 6
number = 10
while number > 0:
number -= 1
flip = random.randint(1, 6)
results[flip-1] += 1
return results
You need to decrement number on each pass of the while loop. Put number -= 1 as the last line in the while loop.

Categories