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")
Related
I've got 2 problems here.
my first problem is that the code shows me only one time a factor even though it's multiple x times by the same factor. I don't know how to add it to the factor list.
Another problem is I'm not sure in print - how the sep works and how can I write "*" only between elements of factor list.
I can't use any import functions here (intertools, maths etc.)
Please help me.
def factorize(n):
prvocisla = []
faktor = []
#prime numbers
for num in range(1, 2000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prvocisla.append(num)
count = 0
for i in prvocisla:
if n % i == 0:
count += 1
faktor.append(i)
print(n, " =", *faktor , sep=' *', end='\n')
factorize(360)
My result:
360 * = *2 *3 *5
The right result:
360 = 2 * 2 * 2 * 3 * 3 * 5
I try the count function with adding same factor to the list "count times" but it shows me an Error.
The problem is that in your second 'for' loop you evaluate if there is a prime number in your number, but not how many times it is present.
To do this you need to repeat the cycle every time you find a prime number and divide the initial number by the prime number. this way you will get to 1 and get all the factors in the array.
Here the right code:
def factorize(n):
prvocisla = []
faktor = []
#prime numbers
for num in range(1, 2000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prvocisla.append(num)
count = 0
t = n # <-- a temporary variable which get n value
while t>1:
for i in prvocisla:
if t % i == 0:
count += 1
faktor.append(i)
t = t/i <-- divide t every time you find a factor
break
print(f"{n!s} = {' * '.join(str(k) for k in faktor)}")
factorize(360)
For the print I use the #CreepyRaccoon suggestion.
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'))
I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly. I'm not sure what is wrong exactly, but I feel the code may be too complicated and somewhere, there is an error.
enter code here
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
for j in range(count):
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
while i <= len(list):
while t != 0 :
initial_guess = 10
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
i = i + 1
break
initial_guess = better_guess
i = i + 1
There are some errors in your code, #x pie has pointed out some of them but not all. The most important is that you are need to initalize t for every number in the list, so you can get the iterations for the numbers separately. Also, t needs to be incremented in the while loop, not inside the if block.
You can also clean up the code considerably, for example the j variable is not being used, list comprehension can be used to shorten the code (pythonic way), and iterating over lists can be done with for num in list.
Putting this altogether produces this:
count = int(input('How many numbers am I estimating John? \nCOUNT> '))
print("Input each number to estimate.")
list = [float(input(f'NUMBER {i+1}> ')) for i in range(count)]
print("The square roots are as follows:")
for num in list:
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + num/initial_guess) / 2
t += 1
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {num}^0.5 = {better_guess}")
break
initial_guess = better_guess
Sample run:
How many numbers am I estimating John?
COUNT> 4
Input each number to estimate.
NUMBER 1> 1
NUMBER 2> 9
NUMBER 3> 16
NUMBER 4> 4
The square roots are as follows:
OUTPUT After 9 iterations, 1.0^0.5 = 1.0
OUTPUT After 7 iterations, 9.0^0.5 = 3.0
OUTPUT After 7 iterations, 16.0^0.5 = 4.0
OUTPUT After 8 iterations, 4.0^0.5 = 2.0
#viggnah is right, and I just ignored the num of iterations. But I think #viggnah 's num of iterations are 1 bigger than the actual num of iterations. E.g., if input is 4 and initial guess is 2, the iteration should be 0 rather than 1. Also I add except in case of illegal input.
I suppose the following code works as you expect.
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
while True:
try:
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
break
except:
print("Invalid input! Try again.")
while i < len(list):
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
break
t = t + 1
initial_guess = better_guess
i = i + 1
You need to understand:
We only need initialize guess once for each number. So do it in the first while loop;
tneeds to be updated when initial_guess==better_guess rather than i, I believe this is a clerical error;
initial_guessneeds to be updated in the second loop;
My Attempt:
n = 10
total = 0
i = 0
while i < n:
if i % 2 == 0:
print(total)
else:
print(i)
total = total + int(input())
i = i + 1
Terminal is still counting every number
Mistake:
You are on right track but just printing in case its even wont help. You actually need to add that number to the total sum so far as:
n = 10
total = 0
i = 0
while i < n:
if i % 2 == 0:
total+=i
else:
print(i)
i+=2
print(total)
Or simply:
print(sum([i for i in range(n) if i%2==0]))
n = 10
total = 0
for i in range(10):
if i % 2 == 0:
total = total + i
print("Total of even numbers is " + total)
n = 10
sum = 0
for i in range(0, n):
if i % 2 == 0:
sum += i
print (sum)
is there a way to keep the counter going without counting the negatives and only to stop when the input is zero?
count = 0
total = 0
n = input()
while n != '0':
count = count + 1
total = total + int(n) ** 2
n = input()
print(total)
Here is an example of execution result.
Input: -1 10 8 4 2 0
Output: 184
Since you want only number to enter the loop you can use isnumeric() built in function to check that.
You need if() : break here.
num = input()
...
while(isnumeric(num)):
...
if(num == "0"):
break;
The response you wait for is:
ignore negative number
count positive numbers
stop when input is 0
count = 0
total = 0
n = int(input())
while (n != 0):
count += 1
if (n > 0):
total = total + n**2
num = int(input())
print(total)
Your code was already OK except that you did not cast the number n into int and you did not test n to take away negative values.
Execution:
When you enter -1 10 8 4 2 0, it should show 184
You can parse your Input to an integer (number) and check if it's larger than zero:
count = 0
total = 0
num = int(input())
while number != 0:
if number < 0:
continue
count += 1
total = total + num**2
num = int(input())
print(total)
The difference between pass, continue, break and return are:
pass = ignore me an just go on, usefull when you create a function that has no purpose yet
continue = ignore everything else in the loop and start a new loop
break = break the loop
return = end of a function - a return statement can be used to give an output to a function but also as a way to break out of the function like the break statement does in loops.