I've been working through a few exercises Python based to test my knowledge and I'm stuck on a task which I have got running but am not using the correct loops and statements.
My program needs to use two while loops and two continue statements to print odd numbers from 1 to 10. Then it will print even numbers in reverse from 8 down to 1.
I've gotten the odd to work and I'm using a step based range to do the even, not sure if there's a better way to do this?
But I'm unsure as to how I will include the two while loops and the two continue statements in my program for it to work and print into the console the same outcome as of now.
Furthermore, I'd like for my program to do include a break statement which will not print numbers higher than 6.
I'm just a bit confused on where to add this. I've been viewing many tutorials online but can't seem to find the right examples relevant.
All help and advice or where I can learn more knowledge is greatly appreciated!
Thank you for reading this!
for i in range(1,11):
if(i%2!=0):
print(i)
for i in range(8, 1, -2):
print(i)
This is one way to do it with two while loops and two continue statements:
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
print(n)
while n > 1:
n -= 1
if n % 2 == 1:
continue
print(n)
This outputs:
1
3
5
7
9
8
6
4
2
And to avoid printing numbers higher than 6 by adding a break statement:
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
if n > 6:
break
print(n)
while n > 1:
n -= 1
if n % 2 == 1:
continue
print(n)
This outputs:
1
3
5
6
4
2
Related
I am trying to practice writing these loops, and I had an exercise which asked me to print numbers from 0 to 20 that aren't divisible by 3 or 5.
For the while loop, I wrote this code:
#solution with while
i = 0
while i < 21:
i += 1
if i % 3 == 0 or i % 5 == 0:
continue
print(i)
Whereas, for the for...in loop, I struggled because I found out that I needed to use and instead of or here.
The code is as follows:
#solution with for
for k in range(21):
if k % 3 != 0 and k % 5 != 0:
print(k)
Why did I have to change the logical operator?
In my head, the first rows of the two codes do the same thing, iterate a number from 0 to 20. So the condition, after these, should be equal for both the iterations used.
Can anyone explain to me what am I missing here?
This isn't a loop type problem, the issue is in using different equality operators in your conditions - != instead of ==.
After changing or to and, the result stays the same because you've accidentally used De Morgan's second law (negation of disjunction):
Now, let's look at the code.
In the while loop:
the program doesn't print i:
if it's divisible by 3 (but not necessarily by 5)
or
if it's divisible by 5 (but not necessarily by 3).
In other words:
the program prints i:
if it's not divisible by 3
and
if it's not divisible by 5.
Noe, let's check, what says the condition in the for...in loop:
the program prints k:
if it's not divisible by 3
and
if it's not divisible by 5.
Looks like the same condition, doesn't it?
As you noticed, in the In other words: paragraph, we've naturally used the negation of disjunction.
To sum up, both programs for i / k lower than 21 print:
0
1
2
4
7
8
11
13
14
16
17
19
If you still aren't sure, try to replace the conditions between loops:
i = 0
while i < 21:
i += 1
if i % 3 != 0 and i % 5 != 0:
print(i)
for k in range(21):
if k % 3 == 0 or k % 5 == 0:
continue
print(k)
In while loop.
if i % 3 == 0 or i % 5 == 0: # this means when i is evenly divided by 3 or 5 then don't do anything.
continue
print(i) # means only print i when i is not evenly divided by 3 and 5
And in the for loop
if k % 3 != 0 and k % 5 != 0: # here this means print i when k is not evenly divided by 3 and 5. Which same as while loop
print(k)
You just reverse order and nothing. You can use the same method in both way and you will get the same result.
While loop
i = 0
while i < 21:
i += 1
if i % 3 != 0 and i % 5 != 0:
print(i)
For Loop
for a in range(21):
if a % 3 != 0 and a % 5 != 0:
print(a)
Because you have also changed the conditions for the results in the while loop you have used ==, but in for loop you have used != if you modify the code you will get the same output by or operator in both
for k in range(21):
if k % 3 == 0 or k % 5 == 0:
continue
print(k)
The two loop types are totally equivalent. You had to use and instead of or, and != instead of ==, because you reversed the logic.
In the first case, you are saying "if the number is divisible then skip it, else print it" while in the second one_ "if the number is not divisible then print (else do nothing)"_.
This question already has answers here:
how to stop a for loop
(9 answers)
Closed 2 years ago.
As I am getting more and more comfortable with writing scripts in Python I wrote a script that finds prime numbers by trying to divide each number in a range in each number (kinda like Brute Force haha).
It works but I wanted to make the process faster and more efficient.
My code:
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
j = j + 1
if count == 1:
print(i)
count = 0
Explanation:
I check and store in count how many time does a number can be divided.
If by the end of the check count equals 1 that means that the number is prime (gets divided only by itself).
What I want now is to stop the process of checking how many times the number can get divided when the "count" variable exceed 1 (2 or more). How do I do that?
I wanted to do something with try and except but didn't know what...
Add an extra condition in here, and break out of the loop if the count is greater than one. Put this inside the while loop:
if i % j == 0:
count += 1
if count > 1:
break
As mentioned in the comments, it's cleaner to just use count as part of the loop condition. Here's an improved version:
for i in range(2, 1000):
j = 2
count = 0
while j <= i and count < 2:
if i % j == 0:
count += 1
j += 1
if count == 1:
print(i)
Of course, there are faster ways to find if a number is prime - in particular, in the inner loop you should not iterate until 1000, not even until i is reached, just until the sqrt(i), but I'll leave that as an improvement for you to make ;)
You can try using break. What break does is that it skips the remaining part of the loop and jumps to the statement following the loop.
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
break
j = j + 1 ### line 8
if count == 1:
print(i)
count = 0
In this code, when python encounters break, it skips the remaining part of the loop (that is, the remaining loop is not executed) and jumps straight to the next statement, which is line 8
Its all wrong, first you have to understand the algorithm to check for prime, basically a number is prime if it can't be fully divided by any number between 2 to (number//2)-1
Now in your question, you couldn't use break anywhere, bcz you first searching for all divisible and then checking prime, better I'm adding a sample code to your problem which is more feasible to find primes
Code
number = int(input("Enter A Number"))
for i in range(2,number//2+1): #See range arguments
if(number%i==0):
print("Not A Prime")
break #Break loop when condition reached
I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."
Here is what I came up with so far:
while num in range(22,101,2):
print(num)
Use either for with range(), or use while and explicitly increment the number. For example:
>>> i = 2
>>> while i <=10: # Using while
... print(i)
... i += 2
...
2
4
6
8
10
>>> for i in range(2, 11, 2): # Using for
... print(i)
...
2
4
6
8
10
This is what I'd try:
i=2
while i <= 100:
if ( i % 2==0):
print (i, end=', ')
i+=1
Your code has several problems:
Substituting while for a statement with for syntax. while takes a bool, not an iterable.
Using incorrect values for range: you will start at 22.
With minimal changes, this should work:
for num in range(2, 101, 2):
print(num)
Note that I used 101 for the upper limit of range because it is exclusive. If I put 100 it would stop at 98.
If you need to use a while loop:
n = 2
while n <= 100:
print (n)
n += 2
Here is how to use the while loop
while [condition]:
logic here
using while in range is incorrect.
num = 0
while num <=100:
if num % 2 == 0:
print(num)
num += 1
Using a for while write a function that shall display only even numbers from 1 to 20. Make sure your function is called printer
I've been learning python for about a week now, and I tried my hand at creating the binary search function:
def bin_srch(a, b, c, d):
l_c = map(int, c.split(" "))
l_d = map(int, d.split(" "))
for n in l_d:
if n <= l_c[a/2]:
for j in l_c[0:(a/2)+1]:
if j == n:
print l_c.index(j)+1,
elif n not in l_c[0:(a/2)+1]:
print -1,
elif n > l_c[a/2]:
for j in l_c[a/2:a]:
if j == n:
print l_c.index(j)+1,
elif n not in l_c[a/2:a]:
print -1,
However, when I test the function with some input:
bin_srch(5,6,
"10 30 50 60 70",
"60 10 50 10 5")
yields 4 1 3 1 -1 -1 -1 instead of 4 1 3 1 -1. Can anybody explain this?
While I don't really understand what you're code is supposed to be doing, I'm pretty sure I know the problem:
for j in l_c[0:(a/2)+1]:
if j == n:
print l_c.index(j)+1,
elif n not in l_c[0:(a/2)+1]:
print -1,
So, for each value, if it's a match, print the match (and keep looking); otherwise, check it against of the same values you're already looping over (and are going to continue to loop over) and if it's not found, print -1. So, if something isn't a match, you're going to print -1 multiple times.
What you probably want is:
for j in l_c[0:(a/2)+1]:
if j == n:
print l_c.index(j)+1,
break
else:
print -1,
At least this gives the desired output for this example. Why?
Well, the break means that as soon as you find a match, you stop going through the inner loop. The else—notice that it's attached to the for, not the if—runs if you finished the loop without ever break-ing. So, instead of checking for a match 3 times and printing -1 each time, you just check for a match 3 times and print -1 at the end, if you never found one.
(Actually, it looks like you could replace this whole loop with a list.index call, but I'll leave that up to you.)
Of course you have to make the same fix in the elif branch of your top-level if, because you have the same problem there.
Also, as a side note, if you write if n <= l_c[a/2]:, you don't need elif n > l_c[a/2]: Just use else; you already know that it's not true that n <= l_c[a/2] or you wouldn't have gotten here, therefore it must be true that n < l_c[a/2], so you don't need to check it.
I am attempting to find the 1000 prime number and am trying to do it without cheating memorization or other code. Can you please tell me whether I am on the right track with my code or completely off base?
primes = []
num = 3
while (len(primes)) < 1000:
if num / 2 == 0:
num = num + 1
else:
x = num - 1
for z in range(2,x):
if num % z == 0 :
num = num + 1
else:
primes.append(num)
num = num + 1
print primes[1000]
You've got a few problems (num / 2 == 0 should be num % 2 == 0)1, but really, using continue and break would really help. e.g.
for z in range(2,x): # xrange would be a performance win on python2.x
if num % z == 0 :
num = num + 1
else:
primes.append(num)
num = num + 1
In this loop, you could find yourself incrementing num a whole bunch of times. in reality, you only want to increment it once (to move on to the next number). So here you'd want to break after you increment it. Also, the else statement would need to be on the for loop:
for z in range(2, x):
if num % z == 0:
break # exit the for loop, don't execute `else` clause.
else:
# only executes if `break` was never encountered.
primes.append(num)
# This happens no matter what and should only happen once
# Might as well pull it out of the loop.
num += 1
1the checking for divisibility by 2 is sort of useless here -- It's the first iteration of your loop. If you used xrange (for python2.x) and break as I've described, then this optimization (likely) isn't worth it.
Aside: You don't really need to run the loop from 2 to N - 1, you can actually get away with running the loop from 2 to int(math.sqrt(N)) which makes this lots more efficient :-) although still not the best you can do... The Sieve of Eratosthenes is another algorithm for doing this more efficiently and there's probably even better methods than that (though I'm not an expert in this area)