How do I make a loop start from where it was left off? For example
def nextSquare():
i=0
while i<10:
k = (input("enter number"))
i=i+1
if k=='Done':
break;
else:
continue
If I stopped the loop at 5 the next time I want it to run from i = 6 instead of i = 0.
Thanks.
In order to store the iteration index, you can pass it as a parameter and return it back to the calling function.
For example:
def lol(i):
while(i < 10):
print(i) #unique value of i
k = int(input())
if k == 5:
print("Iteration skipped")
break
else:
print("Next iteration")
i += 1
return i
i = 0
i = lol(i)
i = lol(i)
i = lol(i)
i = lol(i)
In this example, I am calling lol four times. It stores the iteration index as i when it is called. It passes the same index so that it resumes the iteration from that index. If k != 5, then it increments the index, and returns it. Else, the operation is skipped.
ALSO
Looking at your example, I would say that there is a logical mistake.
k = (input("enter number"))
In this statement, you are asking for a number. However, you are comparing it to 'Done'. A logical mistake, I would say.
Related
I have a while loop which calls the function mainrt() on each iteration.
if __name__ == "__main__":
inp = sys.stdin.read()
inpList = inp.split('\n')
inpList.pop()
for n in inpList:
i = 0
p = 0
n = int (n)
while True:
i += 1
p = n*i
if n == 0:
print "INSOMNIA"
break
else:
res = True
res = mainrt(p)
if res == False:
print p
break
And the mainrt()
def mainrt(n):
#print n
while True:
rem = n % 10
if rem in diMon:
pass
else:
diMon.insert(rem,rem)
if len(diMon) == 10:
return False
break
n = n/10
if n == 0:
return True
break
else:
continue
The problem is as i take input from stdin.read() the first line of the input processed properly by the function, but the second line of the input get printed as it is. It is not being processed by the function
example
INPUT
3
5
OUTPUT SHOLD BE
30
90
But instead I get
30
5
Why the function not processing the input the second time???
There is no run time error so far.
In your mainrt function I do not see that you declare diMon list, so it looks like it is a global variable and you do not clean that list. That mean your mainrt return False at the first check of if len(diMon) == 10: for the second input. You should declare diMon at the beginning od mainrt function or clear it at the end of while loop body.
EDIT:
Now I checked your code one more time and I suggest you to declare diMon at the beginning of for loop
for n in inpList:
diMon = []
i = 0
p = 0
n = int (n)
def fibonacci(n):
first = 0
second = 1
count = 0
while count <= n:
if (second % 2 == 0):
first, second = second, first + second
count += 1
return first, second
print (fibonacci(4000000))
Can somebody please explain what is wrong with this code? In IDLE the page restarts but returns no answer. By the way, I'm a beginner programmer, only just finished the CodeAcademy course.
Since this is for Problem 2 of Project Euler, you're computing the wrong values. It asks for the sum of all even Fibonacci numbers up to a value of four million, not the four millionth value. That would be too large.
Since we want to keep generating values, we'll use a generator and combine it with itertools.takewhile(). Then we'll filter() it down to the even values, and find the sum().
import itertools
def fibonacci_gen():
first = 0
second = 1
while 1:
first, second = second, first + second
yield second
>>> a = fibonacci_gen()
>>> sum(filter(lambda y: not y%2, itertools.takewhile(lambda x: x<=4e6, a)))
4613732
For a solution that doesn't use these features:
def fibonacci_4m():
result = 0
first = 0
second = 1
while second <= 4e6:
first, second = second, first + second
if not second%2:
result += second
return result
>>> fibonacci_4m()
4613732
second % 2 starts off as 1, which is not odd. Consequently your while loop doesn't run anything in the body, so the loop runs forever.
You probably want to always compute the next Fibonacci number, but only increment the count if the second is even.
Your problem is that you have your count variable inside the if statement. You have created an infinite while loop. Move it outside of the if statement:
if(second % 2 == 0):
first, second = second, first + second
count +=1
Also you will have to add more code to make this work properly.
In your while loop, nothing changes when the if statement fails to execute its conditional code. Try the following instead:
def main():
for index in range(1, 41):
print('even_fibonacci({}) = {}'.format(index, even_fibonacci(index)))
def even_fibonacci(index):
for number in all_fibonacci():
if not number & 1:
index -= 1
if not index:
return number
def all_fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
if __name__ == '__main__':
main()
I know I'm missing something really simple here....but I cannot put my finger on it.
My code is trying to find divisors for the items in "numbers". When count reaches 10 I know I have found the first item in numbers which has 10 divisors...but I cannot see to exit the loop. It just keeps printing the items in numbers that have 10 or more divisors.
I thought it was the indent, but no. I then moved the counter inside the first for loop to see if that was it, and still nothing.
numbers = []
numbers = [i for i in range(1, 100)]
for i in range(1, 100):
test = sum(numbers[0:i])
count = 0
for j in range(1, test+1):
if test % j == 0:
count +=1
if count == 10:
print test
break
Suggestions?
break breaks only the inner-most for loop. You need to check for count == 10 after that as well:
for i in range(1, 100):
test = sum(numbers[0:i])
count = 0
for j in range(1, test+1):
if test % j == 0:
count +=1
if count == 10:
print test
break # Breaks for j but not for i
if count == 10:
break # Breaks for i
You have to exit both for loops. There are two options:
1) Put the code in a function and use return instead of break
def process_something():
for a in items:
for b in other_items:
if some_condition:
return
2) Use a helper variable to detect that the outer loop should break too:
for a in items:
done = False
for b in other_items:
if some_condition:
done = True
break
if done:
break
In your case, you can use if count == 10: instead of if done: but I don't like duplicating "application logic" (DRY principle), so count == 10 should be in code only once. But this is a matter of taste.
3) Wrap the outer loop in a try:/catch ...: and raise exception instead of break, but please don't do this.
The following code should be taking two numbers from the user and then state which number is higher, 9 times, thus "counter <10 " except it only takes the two numbers once, and then the loop is finished. I thought I could increment the loop by using "counter=counter +1" in my loop, but it doesnt seem to work. Any help would be appreciated, thanks!
counter = 0
for counter in range(counter < 10):
num1 = float(input("Enter number 1: "))
num2 = float(input("Enter number 2: "))
if num1 > num2:
print(num1)
else:
print(num2)
counter = counter + 1
counter < 10 returns True which is equal to 1:
>>> counter = 0
>>> counter < 10
True
>>> True == 1
True
In turn, range(1) yields 0 (single item):
>>> list(range(counter < 10))
[0]
That's why it loop once.
Instead of range(counter < 10), you should use range(9). You don't need to declare counter = 0 and to increment yourself counter = counter + 1. for statement take care of it:
>>> for i in range(3):
... print(i)
...
0
1
2
counter<10 is equivalent to 1. That is why, the loop runs just once ( range(1) = {0} ).
You can use either :
for counter in range(10):
...
or
counter = 0
while( counter<10 ):
...
counter+=1
for your purpose.
To make it more clear to you, the expression within the brackets are evaluated at first place. If you want to use for, then you need to pass a sequence, over which the for will loop through. The range() is used to generate the sequence . But here you are passing (count < 10) to range(), which is a condition. So while evaluated, it returns True since counter is 0 (initialized in the first line) and is less than 10. And this returned True is equivalent to 1, so the rest goes as described by falsetru
If you want to pass a condition, then you should use while loop, instead of for. In for, you don't even need to initialize the variable counter separately. If you write :-
for counter in range(9):
this will initialize counter variable and it would be incremented in each iteration.
For your question you can use either of the following:-
for counter in range(9):
# No need to initialize counter
do_stuff
or
# Initialize counter
counter = 0
while(counter <10):
do_stuff
This is the problem:
Given the following program in Python, suppose that the user enters the number 4 from the keyboard. What will be the value returned?
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
return counter
Yet I keep getting a outside function error when I run the system
what am I doing wrong?
Thanks!
You can only return from inside a function and not from a loop.
It seems like your return should be outside the while loop, and your complete code should be inside a function.
def func():
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N -= 1
return counter # de-indent this 4 spaces to the left.
print func()
And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.
You have a return statement that isn't in a function. Functions are started by the def keyword:
def function(argument):
return "something"
print function("foo") #prints "something"
return has no meaning outside of a function, and so python raises an error.
You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.
As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
print(counter)
break
It basically occours when you return from a loop you can only return from function