Count the number of Factors using while Loop on Python - python

I am new to Python and so I am a little unaware of the advanced functions. Here's how I approached this problem by breaking it into two .
First I found the factors of this number.
a = int(input("Enter Number to find Factors: "))
b = 1
while a >= b :
if a % b == 0 :
print(b)
b+=1
Second, I prepared the psudo code for counting numbers
b = 17
count = 0
while b > 0 :
rem = b % 10
b = b // 10
count += 1
print(count)
can you guys help me how should I proceed like how should I join these I think I am having problem with syntax

Modify your first solution to increase the count each time one is found.
a = int(input("Enter Number to find Factors: "))
b = 1
count = 0
while a >= b :
if a % b == 0 :
count += 1
print(b)
b+=1

Is this what you were asking for?
def get_factors(n, list):
b = 1
while n >= b :
if n % b == 0 :
list.append(b)
b+=1
def count_digits(n):
count = 0
while n > 0 :
n = n // 10
count += 1
return count
n = int(input("Enter Number to find Factors: "))
# getting the list of factors
factors = list()
get_factors(n, factors)
# printing the factors and the amount of digits in each factor
for f in factors:
print("Factor:", f, ", Digits:", count_digits(f))
Every time you want to join more than one piece of code you can create a function using:
def function_name(parameters)
Then put your code inside the function or functions and you can apply the functions to whatever variables you want.
You can create functions that don't return anything. Those can be used like this:
function_name(parameters)
Or you can create functions that return values and they can be used like this:
a = function_name(parameters)
For more information you can check w3school they explain it well: https://www.w3schools.com/python/python_functions.asp

In this answer I show how to connect the codes without using def.
You can just copy the second code and paste it inside of the if of the first one:
a = int(input("Enter Number to find Factors: "))
b = 1
while a >= b :
if a % b == 0 :
b2 = b
count = 0
while b2 > 0 :
b2 = b2 // 10
count += 1
print(b, count)
b+=1
remember to copy the value of b to a different variable.

Related

Count how many times can a number be divided by 2

n = int(input())
counter = 0
while n > 0:
if (n // 2) > 1:
counter = counter +1
print (counter)
Hi,
I am a python learner and I am having problems with this homework I was given.
Read a natural number from the input.
Find out how many times in a row this number can be divided by two
(e.g. 80 -> 40 -> 20 -> 10 -> 5, the answer is 4 times)
And I should use while loop to do it.
Any Ideas, because I really don't have any idea how to do it.
This is my best try
You are not changing n. I would write it like this:
while (n % 2) == 0:
n //= 2
counter += 1
Try this, we take the value from "n" and check whether it is divisible by two or not. If it is divisible by two, we increment the counter and then divide that number by 2. If not, it will print the output.
n = int(input("Input your number: "))
counter = 0
while n % 2 != 1:
counter = counter + 1
n = n/2
print(counter)
Your while loop condition is wrong.
While the number is evenly divisible by 2, divide it by 2 and increment counter
num = int(input('Enter a number: '))
counter = 0
while num % 2 == 0 and num != 0:
num = num / 2
counter = counter + 1
print(counter)
The code above will not work as intended. The intended functionality is to take an input natural number and find out how many times in a row the number can be divided by 2. However, the code will only divide the number by 2 once.
To fix this, you can change the code to the following:
n = int(input())
counter = 0
while n > 0:
if (n % 2) == 0:
counter = counter +1
n = n // 2
print (counter)
You need to test whether a number is divisible by 2. You can do this in one of two ways...
x % 2 == 0 # will be True if it's divisible by 2
x & 1 == 0 # will be True if it's divisible by 2
So, you need a loop where you test for divisibility by 2, if True divide your original value by 2 (changing its value) and increment a counter
N = int(input())
counter = 0
if N != 0:
while N % 2 == 0:
counter += 1
N //= 2
print(counter)
Or, if you prefer more esoteric programming, then how about this:
N = int(input())
b = bin(N)
print(0 if (o := b.rfind('1')) < 0 else b[o:].count('0'))

Finding probability from random number generator

I am working on a personal problem that requires me to find the probability that the sum of three randomly chosen real numbers between 0 and 1 is greater than 1. I have tried writing the code in python, but I think there's an error:
import random
a = random.random()
b = random.random()
c = random.random()
n = int(input("Enter a range: "))
for i in range(n):
wanted = 0
if (a + b + c > 1):
wanted += 1
else:
wanted += 0
print("The ratio is " + str(wanted/n))
Can you please point out the problems with my code or direct me otherwise?
To me seems like two issues :
each time you want to create a new set of random numbers, so they should go inside the loop
and wanted=0 should be before loop, you are resting it to 0 each time
import random
n = int(input("Enter a range: "))
wanted = 0
for _ in range(n):
a = random.random()
b = random.random()
c = random.random()
if a + b + c > 1:
wanted += 1
print(f"The ratio is {wanted/ n:.2%}")

How to generate a series using While loop

n = int(input("Enter n: "))
sum = 0
i = 1
while i <= n:
sum = sum +1
i = i+1
print("The sum is" , sum)
I tried the above code but didn't got my answer.
The question is to generate a series that is: 1,4,7,10,13,16,19,22 using while loop.
To generate series you need to do two things:
Put the print inside the loop to output accumulator variable's value every iteration
Add 3 to sum every iteration and not 1 since it's the difference between series members
n = int(input("Enter n: ")) # n=8 should work
sum = 1
i = 1
while i <= n:
print(str(sum)+",")
sum = sum +3
i = i+1
I see two errors:
You should add i to sum,not 1 (this assumes you are interested in the sum as implied by the code)
You should be incrementing i by 3 not by 1
If I understand you correctly, you want this:
i = 1
while i <= 22:
print(i)
i += 3
n = int(input("Enter n: "))
count = 0
i = 1
sum = 0
while count <= n-1:
print(i)
sum += i
i += 3
count += 1
print("Sum is", sum)
You are going to want to increase the count by three every time with i += 3.
def createList():
user_input = input()
i = 1
list_of_vals = []
while i < int(user_input): # The max value:
list_of_vals.append(i)
i += 3
return list_of_vals
print (createList())
I think you want something like this:
n = int(input("Enter n: "))
series_sum = 0
i = 1
series = []
add = 3
while i <= n:
series.append(i)
series_sum = series_sum + i
i = i + add
print("series: ", series)
print("The sum is" , series_sum)
This would get you a series (and sum of elements) with the last element less than n, starting from i = 1 and increment add = 3

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

How do I exit this while loop?

I’m having trouble with exiting the following while loop. This is a simple program that prints hello if random value is greater than 5. The program runs fine once but when I try to run it again it goes into an infinite loop.
from random import *
seed()
a = randint(0,10)
b = randint(0,10)
c = randint(0,10)
count = 0
while True:
if a > 5 :
print ("aHello")
count = count + 1
else :
a = randint(0,10)
if b > 5 :
print ("bHello")
count = count + 1
else :
b = randint(0,10)
if c > 5 :
print ("cHello")
count = count + 1
else :
c = randint(0,10)
if count == 20 :
count = 0
break
count = 0
Your while loop might increment the variable count by 0, 1, 2 or 3. This might result in count going from a value below 20 to a value over 20.
For example, if count's value is 18 and the following happens:
a > 5, count += 1
b > 5, count += 1
c > 5, count += 1
After these operations, count's value would be 18 + 3 = 21, which is not 20. Therefore, the condition value == 20 will never be met.
To fix the error, you can either replace the line
if count == 20
with
if count >= 20
or just change your program logic inside the while loop.
Does the following code help?
while True:
if a > 5 :
print ("aHello")
count = count + 1
if count == 20 :
break
else :
a = randint(0,10)
if b > 5 :
print ("bHello")
count = count + 1
if count == 20 :
break
else :
b = randint(0,10)
if c > 5 :
print ("cHello")
count = count + 1
if count == 20 :
break
else :
c = randint(0,10)
You have to check the value of count after incrementing it every time.
The "break" condition might fail if two or more values of the variables a, b, and c are greater than 5. In that case the count will be incremented more than once and count will end up > 20, and the loop can never terminate. You should change:
if count == 20 :
to
if count >= 20:
At the end of iteration, count might be greater than 20 due to multiple increments. So I would update the last if statement to:
if count >= 20:
to feel safe.
If your goal is to stop counting when count is >= 20, then you should use that condition for your while loop and you won't need to break at all, as you only break at the end of the loop anyways.
The new while statement would look like
while count < 20:
# increment count
and then outside of the while loop you can reset count to 0 if you want to use it again for something else.
since you increment count 2 or 3 times in one iteration, it may skip past your count == 20 check
Here's one way to get exactly 20 lines.
from random import seed, randint
seed()
a = randint(0,10)
b = randint(0,10)
c = randint(0,10)
count = iter(range(20))
while True:
try:
if a > 5:
next(count)
print ("aHello")
else:
a = randint(0,10)
if b > 5:
next(count)
print ("bHello")
else:
b = randint(0,10)
if c > 5:
next(count)
print ("cHello")
else:
c = randint(0,10)
except StopIteration:
break
Note there is still a lot of repetition in this code. Storing your a,b,c variables in a list instead of as separate variables would allow the code to be simplified further

Categories