Using conditional statements in while loop - python

I was under the impression that adding the following if statement in my while loop makes python pick only the odd values of i that are smaller than 7 and sums them. However, this is not the case.
Here's my code:
i = 0
sum = 0
while i < 7:
if (i % 2) == 1:
sum += i
i += 1
I expect sum to be 9 but an infinite loop occurs, causing the sum to be infinite.
I can't seem to understand how. Any help is appreciated. Thanks in advance!

You only increment i inside the if, so if the condition is not meant, i stays the same forever
i = 0
sum = 0
while i < 7:
if (i % 2) == 1:
sum += i
i += 1
print(sum)
Output:
9

As you keep conditioning i % 2, but if it doesn't go through, the i never changes, it will always exit the if statement, to solve it:
i = 0
sum = 0
while i < 7:
if (i % 2) == 1:
sum += i
i += 1
print(sum)
You have to unindent by 4 spaces your i += 1 line.

For similar cases it is better to use for loop than while loop. Especially if you have long loops. link
sum = 0
for i in range(7):
if (i % 2) == 1:
sum += i

Related

While loop with if statement

I am combining a while-loop with an if-statement to add a number from 0-24 if the number is even. I constantly go to an infinite loop.
number = range(0,50)
i = 0
total = 0
while number[i]<25:
if number[i]%2==0:
total+=number[i]
i+=1
print(total)
The problem is, that you are adding 1 to i inside the if statement.
You could simplify your code like this:
total = 0
for i in range(0, 25):
if i % 2 == 0:
total += i
print(total)

How to run the python code with limit number in for loop?

I have a simple for loop code for calculate the sum of all multiples of 3 & 5 less than 100, and since I place the print under the if, it will shows all the sum of multiples of 3 & 5, and I want it only shows the sum of 3&5 before 100, what should I do? thanks.
range(1,100)
total = 0
for i in range(1, 100):
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
If I interpret your question correctly, you're asking how to only print the sum at the end, not at every point in the loop. The answer to this is to de-indent the print statement to be outside the if and for blocks:
range(1,100) # note: this line does nothing, you can remove it
total = 0
for i in range(1, 100):
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
You can compute this sum more simply with the sum function:
print(sum(
i for i in range(1, 100)
if i % 3 == 0 or i % 5 == 0
))
If what you are trying to ask is to print the total only once and not again and again, then the answer is simple, just unindent the line with the print statement, that is:
total = 0
for i in range(1, 100):
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
This is because, if the statement is indented, it will be treated as a part of the for loop and will run on every iteration of the for loop. Instead, unindent it to make it run only once and that is after the for loop is done running. The output for this code will be like this:

Python list index out of range but shouldn't be

startDate, stopDate, startTime, stopTime, startBehavior, and stopBehavior are all lists with the same length. I'm getting a list index out of range in line 5 (if startDate[i] != stopDate[j]) and I'm not sure why. It was working before and now it's not. I'm trying to print the specific behaviors based on the conditions in the if/elif statements.
i = 0
while (i < len(startDate)):
j = 0
while (j < len(stopDate)):
if startDate[i] != stopDate[j]:
j += 1
elif startDate[i] == stopDate[j]:
if stopTime[j] < startTime[i]:
j += 1
elif stopTime[j] > startTime[i]:
if startBehavior[i] != stopBehavior[j]:
j += 1
elif startBehavior[i] == stopBehavior[j]:
print(startBehavior[i])
print(stopBehavior[j])
print('')
i += 1
any help would be appreciated! thank you in advanced!
If you run the following snippet, it will run forever, even though i is clearly greater than 100.
i = 0
while i < 100:
while True:
i += 1
print(i)
Your code is doing something similar -- in the case that i == len(startDate) - 1; startDate[i] == stopDate[j]; stopTime[j] > startTime[i]; and startBehavior[i] == stopBehavior[j], your code will increment i so that i == len(startDate), and then, since j < len(stopDate) is still True, you will not have exited your second while loop. When you try to access startDate[i], you will get an IndexError.
This is somewhat data-dependent so it is possible that it worked before without ever having this issue.

Repeat counter when index ends

Simple question - I want a loop that counts up and returns to 0 when it reaches a certain number.
Tried something like:
while i < 7:
i += 1
if i == 7
i -= 1 #(or change i in any other way - you get the idea)
My Python actually crashed when I tried the above.
EDIT: Yes, the if condition is never met - it still crashes when I change it to if i == 6 though.
while i < 7:
i += 1
if i == 7:
i = 0
The problem is the i-=1 line. Your code works as i counts up to 6, but when it reaches 6, it is incremented to 7, and then subtracted down to 6 again. Your current sequence is 0,1,2,3,4,5,6,6,6,6,...
If you want to count up to 7 then count down to 0 here is what you can try:
i = 0
add = True
while True:
if add:
i += 1
else:
i -= 1
if i in [0, 7]:
add = not add
This is your corrected code,
i = 0
while i < 7:
i += 1
if i == 6:
i = 0
It reaches 0 on reaching 6.
Lot's of syntax Error fixed.

Project Euler Python

I am working on the Project Euler problems. I am on Problem 1 and for some reason I am getting the wrong answer for it. I don't know if its my math logic that's the problem or if the logic for the code is wrong. Here's the code:
def getSumMult3_5(n):
count = 0
i = 0
i_1 = 0
while i*5 < n:
count += i*5
i += 1
while i_1*3 < n:
count += i_1*3
i_1 += 1
return count
print getSumMult3_5(1000)
It's returning that
count = 266333
but that is not the correct answer. Count should equal 233168. Can anybody help me figure out why it's doing this?
Thanks!
You're double counting numbers that are multiples of both 5 and 3, such as 15.
You are double counting multiples of 15. You can solve this by introducing a third while statement to decrease the count by 1 for each multiple of 15.
I suggest using an if/else statement:
def getSumMult3_5(n):
s = 0
for i in range(1, n+1):
if i%3==0:
s+=i
elif i%5==0:
s+=i
return s
print getSumMult3_5(1000)
This is because that if the number is a multiple of 3, it does not check whether it is a multiple of 5; if it is not a multiple of 3, it checks whether it is a multiple of 5.
I also recommend using s as a variable name because it represents sum, which can't be used as it is a keyword. Count seems to refer to the number of times something occurs.
By only using one variable, and using an if/else statement, execution time will be less and it will be less confusing to read.
Good luck!
Here's my code:
running_sum = 0
for i in range(1,1000):
if i % 3 == 0:
running_sum+=(i)
elif i % 5 == 0:
running_sum+=(i)
print running_sum
You're double-counting numbers like 15 that are multiples of both

Categories