For loop should loop 9 times, instead loops once - python

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

Related

How to start a loop from where the user stop the loop?

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.

Understanding iterative properties of Python "in" operator within for loop and if statement

The following code returns the summation of the values in list "A" that exist before the first even value in the list.
Example:
if list A = [1,3,5,4] the result would return 1 + 3 + 5 = 9
if list A = [1,2,5,4] the result would return 1
def for_version(L):
found_even = False
total = 0
for num in L:
if num % 2 != 0 and not found_even:
total = total + num
else:
found_even = True
return total
A = [1,3,5,9]
for_version(A)
I don't understand how, after the first iteration, we don't lose the 1st integer in the list. In other words, here's how I imagine the code is working.
Starts at the first value in the list "A" and prepares to move through all values one at a time:
for num in L:
Checks the first iteration of the if statement:
if num % 2 != 0 and not found_even:
Although the first number in the list IS ODD, because found_even was set to False originally the code should move to the else statement:
else:
found_even = True
I imagine that the if statement has now been completed on the first value of the list and all that occurred was that the found_even bool was changed to True.
I assumed that the code would then move on; that the if statements would then be tested on the NEXT value in the list. This, however appears incorrect. If my thinking were right, in the example above, it would mean that the first value in the list "1" would be ignored when completing the summation, and we would end up with 3 + 5 = 8 NOT 1 + 3 + 5 = 9.
I obviously don't understand something very foundational about how the
for num in L:
line works... It's as if it did not, in fact, move to the next integer in the list and reruns the code on the first integer in the list. Can someone please explain why this is.
Although the first number in the list IS ODD, because found_even was set to False originally the code should move to the else statement[.]
You got your logic wrong right there. not False is true, so the if statement test tests true and the else suite is not executed.
You can test this yourself:
>>> num = 1 # odd
>>> found_even = False
>>> num % 2
1
>>> num % 2 != 0
True
>>> not found_even
True
>>> num % 2 != 0 and not found_even
True
The code itself is overly complicated; just return early. There is no need to iterate on, or use a flag; return ends a function and iteration:
def for_version(L):
total = 0
for num in L:
if num % 2 == 0:
return total
total += num
Alternatively, use break to stop the loop, and return afterwards.
The Python standard library has a helpful tool in the itertools library for this, called itertools.takewhile(); it'll give you all elements of an iterable until the given test fails. It then just stops iterating:
from itertools import takewhile
sum(takewhile(lambda x: x % 2, A))
I removed the != 0 test there; % 2 only results in 0 or 1, and 0 is considered a false value in a boolean test. I also used the sum() function to add up all the numbers that takewhile does pass through.
You don't need to keep track if you found or not the first even number, just break and leave the for loop when you find it:
for num in L:
if num % 2 != 0:
total = total + num
else:
break

convert a for loop into a while loop

I am trying to figure out how to change a for loop into a while loop for this function:
def sumIt():
A=1
number=int(input('Enter a number(integer):'))
total=0.0
for counter in range(number):
total+=A
A+=1
print('The sum from 1 to the number is:',total)
averageIt(total,number)
#average sum and number
def averageIt(total,number):
print('The average of the sum and the number is:',(total+number)/2)
sumIt()
would I just say:
while number>1:
You can increment the counter variable manually:
counter = 0
while counter < number:
total += A
A += 1
counter += 1
or you could decrement the counter starting at number:
counter = number
while counter:
total += A
A += 1
counter -= 1
where we use the fact that any non-zero number is True in a boolean context; the while loop will end once counter reaches 0.
You use counter instead of number here because you still need to use number later on for the averageIt() function.
You can by creating the counter yourself:
number=int(input('Enter a number(integer):'))
total = 0.0
counter = 0
while counter < number:
total += A
A += 1
counter += 17
The for block is still the more Pythonic and readable way however. Also try to avoid to cast the result of an user input without verification/try block: if he entered 'abc', your code will raise the exception ValueError, since it's impossible to convert abc into an integer.
Why even use a loop at all?
Instead of
for counter in range(number):
total+=A
A+=1
Just use
total += (number*(number+1) / 2) - (A*(A-1)/2) # account for different starting values of A
A += number

Python 101 and Math Logic - Listing square root numbers less than n

I'm stuck on a Python 101 type problem involving loops. Here are the directions:
The square numbers are the integers of the form K × K, e.g. 9 is a square number since 3 × 3 = 9. Write a program that reads an integer n from input and outputs all the positive square numbers less than n, one per line in increasing order. For example, if the input is 16, then the correct output would be
1
4
9
This is what I have so far but it sort of works but runs on forever. My code never reaches the if statement so it breaks(stops) before it gets to 17.
Suppose n = 17.
n=int(input())
counter = 1
while counter * counter < n:
for counter in range(1,n):
a = counter*counter
print(a)
if a < n:
break
Results:
1
4
9
16
25
36
49
64
81
Here is a correction of your code.
n=int(input())
counter = 1
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
There were three things wrong with your code. First, the condition you want to break on is a >= n not a < n. Second, that condition needs to be tested before you print the number. Thus the if statement needs to be inside the for loop and before your print, statement. Third, the outer while loop is not really necessary :) Though you can add it, but a simple inner for loop will suffice.
if a < n: will never succeed unless n = 2; because inside the loop a is becoming (n-1)*(n-1) which is greater than n for n > 2; that's why the infinite loop. Try this:
>>> counter = 1
>>> n = 16 # int(input())
>>> r = counter**2
>>> while r<n:
print r
counter += 1
r = counter**2
1
4
9
Or just modify yours one by removing the outer loop, and placing the conditional inside the for loop like:
for counter in range(1,n):
a = counter*counter
if a >= n:break
print(a)
Your code loops might be the case in you semantics error try this out light on the memory and simple
def number(n):
for i in range(0,n):
w=i*i
if w>n-1:
break
print(w)
number(144)
You've got three issues here, but, as you can tell, you're on the right track.
First off, you're using two loops when you only need to be using one, and I think it's because you're a little unclear as to how the while loop works. The while loop checks that the condition is true before each time it runs. If the condition becomes false while going through the loop, the loop will still finish - it just won't start another. For example:
n = 17
while n < 18:
n += 1
print n
n += 1
print n
prints:
18
19
In your case, each iteration through the while loop creates a for loop. In order for a single iteration through the while to take place, your computer has to go through for every number from 1 to n, meaning that it'll print out all those extra numbers before your while loop even has a second chance to do its check. The easiest way to fix this is to remove the while loop and structure your code a little differently. As I'll show you in a few lines, you don't really need it.
When you say if a < n:, you've got your sign backwards and you need an equals sign. The problem asks that you give all values less than n, but, without the =, the program won't stop until it's greater than n. It should be if a >= n:.
Finally, the order of the operations isn't what you want it to be. You'd like it to check that a is less than n before printing, but you print before you do that check. If you switch them around, you'll get something like this:
n=int(input())
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
which should do the trick.
What about
n= int(input())
counter= 1
while counter * counter < n:
print( counter * counter )
counter+= 1
?
Turtle man was perfect but for me. I needed to be able to get all the way to 100 so if you need to get past 81 do this
n = int(input())
counter = 1
for counter in range(1,n + 1):
a = counter*counter
if a > n:
break
print(a)

Return outside function error in Python

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

Categories

Resources