I'm new to python or coding in general. And encountered some while loop question in the following code.
a = int(input('input a number here: '))
def largest_factor(x):
factor = x - 1
while factor > 0:
if x % factor == 0:
return factor
factor -= 1
print(factor)
largest_factor(a)
I'm using python 3.5, and in my understanding, the loop will not break until 0 > 0, so I put the print(factor) to exam that, however, it stopped at the largest factor(e.g. when x = 100, factor prints from 99 all the way to 50, and stopped), and did not reach 0. Is the return statement killed the while loop? Thank you for your time.
There are two ways to leave this loop, waiting until the while statement terminates or by returning the factor.
Your assumption is correct. Once the loop hits the return statement, the function will end. Since 100 is divisible by 50, the loop ends with the function ending.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
This code is running for the 1-10 interval but for interval 20-30 it is writing 21 and 27 and I am unable to understand what's wrong in the code. I don't want to know other code; I want to know what's wrong in my code.
start = int(input("Enter the first number of the interval")) #starting of interval
end = int(input("Enter the last number of the interval")). #end of interval
for i in range(start, end+1):
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
This part of code should
print a number if it's prime, otherwise break
but it doesn't.
Do you notice something strange in your code? I do, and it's the fact that in every case the inner for loop breaks after the first iteration, rethink this aspect of your code, and it will work fine.
First, I am not sure whether you want the period after the inputting for the end. Also, your code checks if i is not divisible by x, then print. So for example, your code checks if 21 is divisible by 2. It is not, so your code prints it out and breaks.
Introduction
Your code is effectively testing if a number is odd and if it is, it prints it out.
If start is 1 and end is any number greater than 1, your code is printing every odd number greater than 2 in the interval [1, end].
It is printing all odd numbers, but not all odd numbers are prime!
Dissecting your code
Let's consider the [1, 20] interval. Your code outputs every odd number greater than 2 in the interval [1, 20].
3, 5, 7, 9, 11, 13, 15, 17, 19.
2 is prime and is missing from this list. We can fix that by writing the following within the outer loop but above the inner loop:
if i == 2:
print(i)
Now the output is `
2, 3, 5, 7, 9, 11, 13, 15, 17, 19.
This is better but 9, 15 are not prime numbers.
The if statement with condition (i == 0 or i == 1) inside of your inner loop is not causing any problems. Let's simplify the inner loop by moving this just outside of the inner loop (just above) so that your code becomes
for i in range(start, end+1):
if (i == 0 or i == 1):
# 0 and 1 are not prime
continue
if (i == 2):
# 2 is prime
print(i)
for x in range (2,end):
if (i % x != 0):
print(i)
break
else:
break
All that remains as the potential culprit for your problems is the inner loop so let's focus on that.
Whenever i is even, in the first iteration of the inner loop, we
have x = 2. We know that if i is even that i % 2 is 0 and so i % x != 0 is False and so we move onto the else, in which case we
break out of the inner for loop. This is all fine because no even
integer greater than 2 is prime!
Whenever i is odd, in the first iteration of the inner loop, we
have x = 2. We know that if i is odd that i % 2 is NOT 0 and so
i % x != 0 is True and then we print i and then break out of
the for loop.
We never once have x = 3 or x = 4 and so on!
The above describes precisely what you code is doing, which is ignoring even integers and simply printing out every odd integer.
Solution that outputs what you want
It would help me if I knew what definition of a prime number you have and/or what algorithm you are trying to implement. But since I don't have this information, I can only suggest a solution.
In order to solve your problem, you need to clearly have in mind what a prime number is. There are many equivalent definitions of a prime number (see the Wikipedia prime number page for examples of definitions). I chose a definition that suggests a natural algorithm for finding prime numbers. Whatever definition of prime number you were given, it is possible to prove mathematically that it is equivalent to this (for some this is the first definition of a prime number that they see!):
An integer i is prime if and only if i > 1 AND for all k in {2, 3,
..., i - 1}, i % k != 0.
In words this says that an integer i is prime iff i is strictly greater than 1 and for all integers k from 2 up until i - 1, k does not divide i evenly.
Here it is
start = int(input("Enter Start: "))
end = int(input("Enter End: "))
print(f"\nPrime numbers between [{start}, {end}]:")
for i in range(start, end + 1):
if (i == 0 or i == 1):
# i is not prime
continue
if (i == 2):
# i is prime
print(i)
continue
for x in range(2, i):
if (i % x) == 0:
break
if (i % x) != 0:
print(i)
Example session:
Enter Start: 20
Enter End: 30
Prime numbers between [20, 30]:
23
29
The (i == 0 or i == 1) check should be placed outside the inner for loop. Otherwise, for all i greater than or equal to 2, for every iteration in the inner loop, you will be checking to see if it is less than 2 or not. You are doing this check too much.
We know that when i == 2 that i is prime.
For i > 2, we appeal to the definition of a prime number above.
The inner loop and the last statement applies the second part of the prime definition.
I just started studying python on hyperskill for the past few weeks.
Here's the scenario:
Write a program that reads from the console integers (one in a line) until their sum is equal to 0. Immediately after that, it should display the sum of the squares of all the entered numbers.
It is guaranteed that at some point the sum of the entered numbers will be equal to 0. After that, reading is not necessary to continue.
In case the first integer equals to 0, also stop reading values from the input. Print out 0 instead of the sum of the squares.
For example, we are reading the numbers 1, -3, 5, -6, -10, 13. At this point, we have noticed that the sum of these numbers is 0 and output the sum of their squares, not paying attention to the fact that there are still unread values.
num = int()
listtrigbreak = []
listsquares = []
sumtrig = 0
sumsqua = 0
while sumtrig != 0: # until sum of trig is not 0,
num = int(input()) #accept numbers
if num == "0": # while first input is 0,
print(0) # print 0
break # and break the loop
listtrigbreak.append(num) # append num to listtrig
sumtrig += sum(listtrigbreak) # add sum of list to sumtrig
for x in listtrigbreak: # for each number in listtrigbreak
squared = x ** 2 # convert each to squares, save variable
listsquares.append(squared) # add squared to listsquq
sumsqua = sum(listsquares) # sum of squares in listsqua
else:
print(sumsqua)
I can't even get past the first while loop. Whenever I run it, it skips the entire while loop and heads over to this:
else:
print(sumsqua)
I've really had a hard time with boolean logic from the start. I need explanations.
As other comments already pointed out, the while loop is a bit tricky since you initially declare the variable to 0. You could use a boolean switch that controls the while loop, like so:
input_integers = []
stop = False
while not stop: # So while we should keep asking user input...
num = int(input())
input_integers.append(num)
if sum(input_integers) == 0 and len(input_integers) > 0:
print('done')
stop = True
Now add the other functionalities in it, and you're done.
I'm in the middle of my homework. And i can't find out how to do this solution.
I have tried to used the break under for-statement but nothing return.
The problem is "Complete the following program so that the loop stops when it has found the smallest positive integer greater than 1000 that is divisible by both 33 and 273."
This is my code that i have tried to do it
n = 1001 #This one is required
while True: #This one too
for i in range(n,___): # I don't know what should i put in the blank
if i%33 == 0 and i%273 == 0: # I really confused about this line
break # Should i break it now?, or in the other lines?
print(f"The value of n is {n}") #This one is also required
I don't know that i should put break in which lines (or i don't have to used it?) or i should created a function that called a minimum number of the list?
I'm sorry about my language and how silly i am at my programming skill
I would accept every comment. Thank you
You already have a while True: loop, you don't need the inner for loop to search for your number, just keep incrementing n in the while loop instead of adding a new counter, when the number you're looking for is found, the infinite while True: loop will stop (using break), and so your print statement will be executed:
n = 1001 # start at 1001
while True: # start infinite loop
if n % 33 == 0 and n % 273 == 0: # if `n` found
break # exit the loop
n += 1 # else, increment `n` and repeat
print(f"The value of n is {n}") # done, print the result
Output:
The value of n is 3003
Thanks for saying it's homework! Makes it better to explain things in more detail than just giving an answer.
There are few things to explain:
1) n%33 is the remainder of dividing n by 33. So 66%33 is 0 and 67%33 is 1.
2) For loops are generally when you need to loop over a defined range (not always, but usually). E.g. "add up the first 100 integers". A while loop makes more sense here. It will definitely terminate, because at some point you'll get to 33 * 237.
3) if i%33 == 0 and i%237 == 0: means we want to do something when the number can be divided evenly (no remainder) by both 37 and 237.
n=1001
while True:
if n%33==0 and n%237==0:
print(n)
break
n+=1
A for loop will not help you here, because you don't know when to end the loop. You usually use for loops when the range of things you want to loop over is already known.
Instead, do the following:
before starting your while: True loop: set i to 0,
then increase i with 1 every time to the loop
also, don't forget to stop the loop when i>1000!
Well you could still use a for loop, as long as the upper limit is at least as high as the maximum possible result. The result would be in i, not in n, and the for loop will suffice, not an additional while loop. The for loop will break when the remainder when dividing by both 33 and 237 is zero (i.e. they are both factors).
n = 1001 #This one is required
for i in range(n, 33 * 237 + 1): # I don't know what should i put in the blank
if i % 33 == 0 and i % 237 == 0: # I really confused about this line
break #
print(f"The value of i is {i}") #This one is also required
You could also use a while loop and use the same logic for the condition. In this case we test that at least one is not a factor and continue the loop until both 33 and 237 are evenly divisible into i.
n = 1001 #This one is required
i = n
while i % 33 or i % 237:
i += 1
print(f"The value of i is {i}")
I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.
n = raw_input("Enter number")
a = 1
while a < n:
a = 1
print(a*a)
a += 1
if a > n:
break
When I run this code it infinitely prints "1" ... I'm guessing that the value of a does not increase by += so it's a=1 forever. How do I fix this?
There are some problems. First, your input (what raw_input() returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
Second, you are setting a = 1 each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line
a = 1
Finally, it's not necesary to check if a > n, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
There is a small error in your code:
while a < n:
a=1 # `a` is always 1 :)
print a*a
a += 1
if a > n:
break
You're setting the value of a back to 1 on every iteration of the loop, so every time it checks against n, the value is 2. Remove the a=1 line.
As others have noted, your specific problem is resetting a each time you loop. A much more Pythonic approach to this is the for loop:
for a in range(1, n):
print(a ** 2)
This means you don't have to manually increment a or decide when to break or otherwise exit a while loop, and is generally less prone to mistakes like resetting a.
Also, note that raw_input returns a string, you need to make it into an int:
n = int(raw_input("Enter number: "))
an even better idea is to make a simple function
def do_square(x):
return x*x
then just run a list comprehension on it
n = int(raw_input("Enter #:")) #this is your problem with the original code
#notice we made it into an integer
squares = [do_square(i) for i in range(1,n+1)]
this is a more pythonic way to do what you are trying to do
you really want to use functions to define functional blocks that are easy to digest and potentially can be reused
you can extend this concept and create a function to get input from the user and do some validation on it
def get_user_int():
#a function to make sure the user enters an integer > 0
while True:
try:
n = int(raw_input("Enter a number greater than zero:"))
except TypeError:
print "Error!! expecting a number!"
continue;
if n > 0:
return n
print "Error: Expecting a number greater than zero!"
and then you can build your input right into your list
squares = [do_square(i) for i in range(1,get_user_int()+1)]
and really do_square is such a simple function we could easily just do it in our loop
squares = [x*x for x in range(1,get_user_int())]
The first line in your loop sets's a to one on every iteration.
You assign a=1 inside the loop. That means it's overwriting the a+=1.
try this:
n = eval(raw_input("Enter number"))
a=1
while a < n:
print a*a
a += 1
The issue here is that the value of a gets overridden every time you enter in the loop
Problem is in the condition of the while loop, to print squares of numbers upto a limiting value, try this..
def powers(x):
n=1
while((n**2)<=x):
print(n**2, end =' ')
n +=1
I mostly have experience programming in visual basic, and am trying to learn python. I am trying to make a conditional loop in the form of a do until loop. I am not sure how to do it in python and i could use some help. I have a do until loop with an if statement within it. this is what i have.
number = 18
do while number = 1
if number%2==0 then
number = number/2
else number = (number*3)+1
loop
print(number)
Any help would be great. Thanks
There is no do … while loop in Python. I believe somewhere in the FAQ it explains why, and how to work around it.
But that doesn't matter because what you've written isn't a do … while loop, it's just a plain while loop. The whole point of a do … while in every language that has one is that you put the test condition after the loop body, instead of before, which guarantees that the loop will run at least once, and which allows you to avoid doing pre-loop setup that you'd have to duplicate inside the loop.
So, to translate your code to Python:
number = 18
while number == 1:
if number%2==0:
number = number/2
else:
number = (number*3)+1
print(number)
However, it's worth noting that since number = 18 before the loop, it will never be == 1 the first time through, so this is just going to skip the whole thing and print out 18.
You may have wanted while number != 1 or while number > 1, but you have to figure out what you actually want to write before anyone can write it.
There is no 'do/while' in Python. The closest is a loop that is guaranteed to loop once then get an exit test after 1 iteration.
while True: # kinda like 'do'
# do something at least once
if fail_condition(): # here is your 'while' test
break # end the loop if 'fail_condition' is True
# loop again if 'fail_condition' is not True
Roughly your code (Collatz/Hailstone?) would look like this:
number, i = 18, 0
while number>1:
i+=1
if number%2==0:
number = number/2
else:
number = (number*3)+1
print 'Reached {} after {} loops'.format(number,i)
# prints 'Reached 1 after 20 loops'
is that above code even in python? instead of do while, have it just be while. and after the if statement, dont have then. a quick reformatting would look something like this:
number = 18
while number == 18:
if number%2==0:
number = number/2
else:
number = (number*3)+1
print(number)
do while is not a usual construct in python. Simply use a while loop.
https://wiki.python.org/moin/WhileLoop
Your code could be modified as follows for instance.
number = 18
while number == 1:
if ( number % 2 ) == 0:
number = number / 2
else:
number = ( number * 3 ) + 1
print number
One of the biggest differences between these languages is that python is all about tab delimitation. You need not specify the start and end of a loop, the tabs do that for you. Additionally not the ':'s after conditional statements.
I would note however that the above code would not yield any valid answer. Perhaps you meant for the loop to run while number was not equal to 1?