I am supposed to modify a program so that the loop stops after 3 iterations. It was a non terminating loop before, but I changed it and now it doesn't show up at all. can you see what I did wrong?
i = 1
while_iterations = 1
while (i <= 3):
print("Starting while iteration number", while_iterations)
for number in range(5, 10):
if (number % 2 == 1):
print("Found an odd number: ", number)
else:
print(number, "is not an odd number")
print("End of for loop.")
print()
while_iterations = while_iterations + 1
i=i+1
Your loop doesn't run because i = 1 and the condition is while( i > 3 ) which means it evaluates to false and skips the entire loop.
EDIT:
while_iterations = 1
while (while_iterations <= 3):
print("Starting while iteration number", while_iterations)
for number in range(5, 10):
if (number % 2 == 1):
print("Found an odd number: ", number)
else:
print(number, "is not an odd number")
print("End of for loop.")
print()
while_iterations = while_iterations + 1
There, this loop terminates. You don't need two index variables, while_iterations was enough.
It is stuck in an infinite loop because the condition while (i <= 3): is always True because you never modify i after initially setting it to 1. Try changing the condition to:
while (while_iterations <= 3):
Or you can remove while_iterations and replace all references to it with i.
Related
The program ask the user for an even integer. If he asks for it 6 times, the program ends. If the number is even, it returns it. My code so far:
i = 0
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(num)
else:
num = int(input("Num: "))
i+=1
if i == 6:
break
My program doesn't end after user gives 6 not even numbers, how can i fix this?
You don't need to check for i == 6 yourself, this is done automatically by the for loop.
But you need to break out of the loop when an even number is entered.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print("Success!")
break
else:
print("Failure")
The else: block of a loop is executed if the loop reaches its normal conclusion instead of exiting due to break.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(liczba)
break
This will do what you want, without all the extra lines you had.
for i in range (0, 3):
print() # When iterates creates a space from last section
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
penalty = (days_late * 5)
final_mark = (raw_mark - penalty)
# Selection for validation
if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
print("Student ID:", str(student_id[i]))
print() # Spacing for user readability
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("This means that the result is now:", final_mark,"(this was not a capped mark)")
elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
print("Student ID:", str(student_id[i]))
print()
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")
else:
print("Error, please try again with applicable values")
At the else i would like the loop to loop back through but not having iterated i to the next value, so that it can be infinite until all 3 valid inputs are entered... cannot use a while loop nor can i put the if - elif- else outside the loop. Nor can i use a function :(
You can have your for loop behave like a while loop and have it run forever and implement your i as a counter. Then the loop can be terminated only if it ever hits 3 (or 2 so that you indices dont change), while otherwise it is set back to 0:
cnt_i = -1
for _ in iter(int, 1):
cnt_i += 1
if ...
else:
cnt_i = 0
if cnt_i == 2:
break
But seriously, whatever the reason for not using a while loop, you should use it anyhow..
Try something like this. You can keep track of the number of valid inputs, and only stop your loop (the while) once you hit your target number.
valid_inputs = 0
while valid_inputs <= 3:
...
if ...:
...
elif ...:
...
else:
# Immediately reset to the top of the while loop
# Does not increment valid_inputs
continue
valid_inputs += 1
If you really cannot use a while loop...
def get_valid_input():
user_input = input(...)
valid = True
if (...): # Do your validation here
valid = False
if valid:
return user_input
else:
return get_valid_input()
for i in range (0, 3):
input = get_valid_input()
# Do what you need to do, basically your program from the question
...
...
There are some additional gotchas here, as in you need to worry about the possibility of hitting the maximum recursion limit if you keep getting bad input values, but get_valid_input should ideally only return when you are sure you have something that is valid.
You can put the input statement inside while loop containing try block.
for j in range(3): # or any other range
try:
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
break
except:
pass
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The program is about giving out the sum of odd and even numbers separately from 1 upto given n term.
INPUT
print()
print("Program to display sum of n terms of odd/even natural numbers!")
print()
num = int(input("Enter the number of natural numbers: "))
even_total = 0
odd_total = 0
i = 1
while i == num:
if(i % 2 == 0):
even_total = even_total + i
i += 1
else:
odd_total = odd_total + i
i += 1
print()
print("The sum of even numbers from 1 to {0} = {1}".format(i, even_total))
print("The sum of odd numbers from 1 to {0} = {1}".format(i, odd_total))
OUTPUT:
Program to display sum of n terms of odd/even natural numbers!
Enter the number of natural numbers: 10
The sum of even numbers from 1 to 1 = 0
The sum of odd numbers from 1 to 1 = 0
>>>
Your program has not completed the intended interations of the loop, which would have been more obvious if you had put some additional print statements inside the loop (e.g. print(i)) - this is a simple debugging technique that you can use in future. Although in fact there is a clue in the output that you see, where it says from 1 to 1 rather than something like from 1 to 10.
What is happening is that the first time the while i == num: is tested, it evaluates False (0 is not equal to 10), so the loop is never entered. If you change the == to <= here, then this will mostly solve the problem (the loop will go up to and including 10).
Other improvements that you can make will include:
In the print statements at the end, use num instead of i:
print("The sum of even numbers from 1 to {0} = {1}".format(num, even_total))
Inside the loop, the i += 1 is done in both the if and else blocks, so instead you could do a single unconditional i += 1 after the if...else...
if i % 2 == 0:
even_total += i
else:
odd_total += i
i += 1
(I've also suggested using += here with the totals, like you are already doing with i.)
You can also use a for loop using range instead, and then you don't need to explicitly increment i at all. Note that the upper limit of the range has to be one greater than the value of i on the last iteration.
for i in range(1, num + 1):
if i % 2 == 0:
even_total += i
else:
odd_total += i
You need to replace while i==num with while i<=num
print()
print("Program to display sum of n terms of odd/even natural numbers!")
print()
num = int(input("Enter the number of natural numbers: "))
even_total = 0
odd_total = 0
i = 1
while i <= num:
if(i % 2 == 0):
even_total = even_total + i
else:
odd_total = odd_total + i
i += 1 #a small optimization to reduce number of lines
print()
print("The sum of even numbers from 1 to {0} = {1}".format(i-1, even_total))
print("The sum of odd numbers from 1 to {0} = {1}".format(i-1, odd_total))
Since, while exiting the while loop your i will be greater than num, you should print i-1 in the print statements that follow the loop.
I input 4 and got the following output:
Program to display sum of n terms of odd/even natural numbers!
Enter the number of natural numbers: 4
The sum of even numbers from 1 to 5 = 6
The sum of odd numbers from 1 to 5 = 4
The condition for the loop is the problems. It should be:
while i<= num:
You are using thiswhile i==num: which means that when the loop run at first it will take num=1 which means that your while i==1 is true and the while loop breaks. So as farther it can't do the sum.
So you can use while<=num
Here is your code
print()
print("Program to display sum of n terms of odd/even natural numbers!")
print()
num = int(input("Enter the number of natural numbers: "))
even_total = 0
odd_total = 0
i = 1
while i <= num:
if(i % 2 == 0):
even_total = even_total + i
else:
odd_total = odd_total + i
i += 1
print()
print("The sum of even numbers from 1 to {0} = {1}".format(num, even_total))
print("The sum of odd numbers from 1 to {0} = {1}".format(num, odd_total))
You should try replacing the while loop with a for loop like
for i in range(1,num+1):
calculate even and odd sum..
or replace while i==num with either i!=num+1 (i not equal to num) or (i<=num)
The problem is with your test condition of while,
Because, we know, while loop will execute if the condition is true but in your case
while(i == num) :
here i=1 and num=10 the test condition is false and while loop will never execute.
So, replace while i == num: with while i<=num: and it will work fine.
And your last two print statements are wrong(has nothing to do with logic)
print("The sum of even numbers from 1 to {0} = {1}".format(i, even_total))
print("The sum of odd numbers from 1 to {0} = {1}".format(i, odd_total))
It should be
print("The sum of even numbers from 1 to {0} = {1}".format(num, even_total))
print("The sum of odd numbers from 1 to {0} = {1}".format(num, odd_total))
There are few more things but as you are a beginner its enough.
i wrote this program to check weather the no. is prime or not but it shows the number is prime multiple times. how can i solve it
To check weather the number is prime or not.
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
Here is my code to check whether a number is prime or not, hope it helps
# Program to Check whether given number is prime
def isPrime(number):
limit = int(number/2) # limit indicates how many times we need to run the loop
flag=0 # to keep track whether the number is prime or not
if number==0 or number==1:
print(f"The Given Number {number} is Not Prime")
return
for i in range(2,limit+1):
if number%i==0:
flag=1
break
if flag==0:
print(f"The Given Number {number} is Prime")
else:
print(f"The Given Number {number} is Not Prime")
isPrime(1)
Your problem is that the else part of your for-loop is wrong. You print "the number is prime" every time a division check fails, not just at the end.
I added an isPrime boolean that tracks if a single check failed. Only if none of them fail, you can print that the number is prime.
num = int(input("please enter the number you want to check\n"))
if num > 1:
isPrime = True
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
isPrime = False
break
if isPrime:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
You can simplify that even more, with a construct of python called for-else (credits to #TheGamer007):
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
It works because Python's for-loops can have an else: following, which only triggers if you don't break out of the loop.
This might be exactly what you were trying to do. In that case, all you did wrong was your indentation.
Also, from an algorithmical point of view, there are much better ways to check. A first simple improvement is that you don't need to check range(2,num), but only range(2, int(math.sqrt(num))+1)
All you need in order to determine whether a number is prime or not, is to find 1 number that is greater or equal to 2 that divides the number.
In your loop, you print out a message that says "the number is prime" for each number that does not divide the given number.
For example, if you want to check whether the number 9 is prime or not, you will loop all numbers from 2 to 8 and check if they can divide 9. So in your for loop, the number 5 for instance -> 9%5 != 0 -> "the number is prime" message will pop up, which is wrong.
The code below shows how you can use a boolean to rise up a flag when the number is NOT prime.
num = int(input("please enter the number you want to check\n"))
isPrime = True
while num < 1:
int(input("enter a positive value\n"))
if num == 1:
print("the number is not prime")
return
for i in range(2, num):
if (num % i) == 0:
isPrime = False
break
print(str(num) + " is prime? " + str(isPrime))
Use a variable, for example flag and initialize it to 0. If the number is not prime,i.e i%2==0 set flag to 1 and break, else flag = 0 .
After that come out of the for block, and with the help of if condition display the number is prime or not. That is if flag==0 the number is prime else not.
I would suggest the following implementation
We only need to check/loop up to a square root of the number and not the number itself and is thus faster.
The for-else structure gets you rid of the isPrime flag that you otherwise need. The way this works is that if the loop finishes normally without breaking (meaning you haven't found what you are looking for) it goes into the else
import math
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, int(math.sqrt(num))+1):
if (num % i) == 0:
print("the number is not prime")
print(i, "times", num//i, "is", num)
break
else:
print("the number is prime")
else:
print("the number is not prime")
One way to do it:
def is_prime(n):
count = 0
if x > 1:
for i in range(1, n + 1):
if x % i == 0:
count += 1
return count == 2
number = int(input("Insert a number: "))
if is_prime(number):
print(str(number) + " is a prime number")
else:
print(str(number) + " is not a prime number!")
is_prime(7) # >> Returns True
How does it work:
A prime number (n) must fullfill the following rules:
n > 1;
n divisible only to 1 and itself(
n % 1 == 0,
n % n == 0)
Perform the modulus operation from 1 to n iteratively. Increment the variable count
every time the result is 0. If the input satisfies the 2nd condition from above then count should be equal 2. If count equals 2 then the number is prime.
Ex:
is_prime(7): 7 % 1 = 0 (count += 1), 7 % 2 = 1, 7 % 3 = 1, 7 % 4 = 3, 7 % 5 = 2, 7 % 6 = 1, 7 % 7 = 0 (count += 1); >> 7 is prime
I have a small function to check if a number is prime or not. It works fine apart from one small detail - it prints out more than one print line on the program end.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()
If I enter the number 2 for e.g. when the program runs, it prints:
the number 2 is prime
the number 2 is prime
the number 2 is prime
It only needs to print the line once, so why is this?
Your else is in the wrong position. You have it on the if, but you actually want it on the for.
It might not be well known, but you can have a else on for-loops and it will execute if no break was executed during the loops.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()