Please can anyone explain the continue statement, I have been trying my best to break it down to my understanding but all efforts have been futile. Here is a sample program I found in the python docs and I can't understand it.
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
else:
print("Found a number", num)
The continue statement causes Python to skip the rest of the current iteration of the loop, and jump to the beginning of the next iteration.
See this documentation page for Python 3. The original example on that page is:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
When continue is encountered, the print at the end of the loop is skipped, and execution goes to the for again to get the next iteration. Note how for even numbers, "Found an even number" is printed, but "Found a number" is not printed. This is because the continue skipped the rest of the loop body.
Your modification to the sample - inserting the else - makes the continue obsolete, because the print("Found a number", num) wouldn't be executed anyway (it sits in an else) branch.
This way you've discovered that continue (and also break) are often an alternative control flow mechanism to if...else. Which to use depends on the situation and style preferences.
Related
I was following a lesson on for loops that told me, as an assignment, using for loops, to print out the even numbers from 1-10, and then print out how many even numbers there are. I was playing around with that and came to this solution:
number_even = 0
for i in range(1,10):
if i % 2 == 0:
print(i)
number_even += 1
if i:
print ('We have', number_even, 'even numbers')
I understand everything up until
if i:
print ('We have', number_even, 'even numbers')
I honestly was just playing around with Python, but dont understand how I get an expected output from this code. Please help.
Your code is generally fine but the last if has no sense - you can just delete that condition and leave print statement.
if some_number evaluates to True if and only if some_number is 0 (with assumption it's an integer)
But let me share one more version of this task that can help you understand python a bit more:
even_numbers = [] # This will be our list of even numbers
for i in range(1,10):
if i % 2 == 0:
even_numbers.append(i) # We add number to the list
print(even_numbers)
print ('We have', len(even_numbers), 'even numbers')
At the end of your loop, i=9, that's why it prints. If you set i=0 before if i: but after the loop, nothing prints.
if i: is equivalent to if i!=0:
I think your confusion comes from the confusing nature of Python scopes.
The variable i doesn't fall out of scope when your loop ends, like it might in other languages. So, when you reach if i, this will succeed because i == 9
Q) all prime numbers can be written in the form of 6m+1 or 6m-1 for some m>=1. write a program to print "Cannot be decided" if the above property is fulfilled or "Composite number" otherwise.
I can't figure out how to put the given statement into a code. i tried a few codes (such as the one given below) but nothing is striking me. Please help. my code is in the pastebin link because formatting here isn't working properly
https://pastebin.com/sMqT6Eic
n=int(input())
for m in range(1,n):
if n==6*m+1 or n==6*m-1:
print("Cannot be determined")
else:
print("Composite number")
break
There is no point to having a loop, it's just unnecessary work and it's much less clear. Every prime p greater than 3 must be of the form 6m + 1 or 6m - 1 for some integer m. That's equivalent to saying that p = 1 mod 6 or p = -1 = 5 mod 6. So just make that the test.
n=int(input('Enter value to test for primality: '))
# assume n > 3
if n % 6 in (1, 5):
print("Cannot be determined")
else:
print("Composite number")
There is indentation errors and also remove the ''' near the declaration of n variable. Break the loop when the condition is satisfied not outside the if statement. It will check only for m=1 and break the loop. Take a new variable that will update its value when the condition is satisfied and the loop breaks. If the variable is updated, it is prime and if variable is not updated, the condition was never satisfied and it is composite. Edited code:
n=int(input())
m=int()
f=0 #new variable
for m in range(1,n):
if n==6*m+1 or n==6*m-1:
f=1 #update the variable when condition satisfied
break #break the loop
else:
continue
if f==1: #updated value when condition satisfied
print("Cannot be determined")
else:
print ("Composite")
I am trying to create a program that prints out a list of numbers starting at 0 and leading up to a number the user inputs (represented by the variable "number"). I am required to use "while" loops to solve this problem (I already have a functional "for" loop version of the assignment). The program should mark anything in that list divisible by 3 with the word "Fizz," divisible by 5 with the word "Buzz," and anything divisible by both with "FizzBuzz" while also including unlabeled numbers outside of those specifications.
Every time I run this program, it ignores the conditions and just prints the word "FizzBuzz" however many times is represented by the number inputted. (I typically use 15 because it has at least one example of each condition, so that means I get 15 "FizzBuzz"s in a row).
To find out why it was doing that, I used print(i) instead of the rest of the program under the first conditional and it gave me 15 counts of the number 0, so there is reason to believe the program is completely ignoring the range I gave it and just outputting copies of i based on the user number input.
Any help would be appreciated!
number = int(input("Enter a Number"))
i = 0
while(i < number + 1):
if number % 3 == 0 and number % 5 == 0:
print("Fizzbuzz")
elif number % 5 == 0:
print("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number)
i += 1
print ("Done!")
You meant to check the divisibility of i, which increments every loop, not of number which doesn't change.
You also meant to print(i) in the else clause.
This is just a small segment of my code but I believe this is the part not working. So the user takes a low and high and finds all the prime number inbetween. But when I run this in IDLE not only is there no response, but there are no errors?! Can somebody please help.
^^^^^^ THIS WAS SOLVED THANKS GUYS ^^^^^^
New Question!
How would I change rangemax to make this print infinitly?
print('Prints all prime numbers between certain numbers.')
rangemin = rangelowdef()
rangemax = rangehighdef()
if rangemax != 'inf':
for num in range(rangemin, rangemax + 1):
if num > 1:
for i in range(1, num):
if num%i == 0:
break
else:
print(num)
num % 1 is always 0. That is because it is an integer (from the range function). So the loop breaks immediately and nothing gets printed.
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?