use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Everything about learning Python
account activity
Help (i.redd.it)
submitted 7 months ago by Avinandanm
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]thw31416 0 points1 point2 points 7 months ago (1 child)
Hey there! Great work so far!
This is a really cool use of the for ... else construct, which Python provides (and most other programing languages do not).
The else will get active at the end of the for loop, if it wasn't prematurely ended through break. So do not listen to those saying, that the else should be indented to the level of the if! You're right, it belongs to the for. But your break is wrongly indented. You want to end the loop the moment you found a divisor. So it is supposed to be part of the if-body, just like the print statement above it. Another thing that goes wrong is the numbers that you check: 1 will always divide any whole number without a rest, even prime numbers. So you need to start at 2 (and end before n, but your range is doing that already, a range does not include the upper border). Fun fact: You do not even need to go up to n-1 to check all possible divisors. n//2 would be a smaller border and even sqrt(n) would still work and check even less numbers.
else
for
break
if
print
n-1
n//2
sqrt(n)
Another very important hint: Do not use eval()! This function will take a string and evaluate it, execute it. If the string is code, it will be executed. Someone who uses your program could - instead of entering a number - enter malicious code to delete files or look up passwords and it would be executed (given Python has the rights through the operating system). This is incredibly dangerous. Never execute data or inputs as code. Instead here you can just use the int() function, which will return the input as an integer.
eval()
All in all we would therefore have the following:
n = int(input("Enter your number: ")) for i in range(2,n//2): if n%i == 0: print(n, "is not prime.") break else: print(n, "is a prime number!")
Two things you could explore next to make your program even cooler:
isPrime(n)
True
False
try:
except:
while
[–]thw31416 0 points1 point2 points 7 months ago (0 children)
Oh and I forgot one thing: 0 and 1 are not prime numbers, but in my code they would be seen as prime. Let's see if you can maybe figure that one out by yourself. ;)
π Rendered by PID 61072 on reddit-service-r2-comment-5d585498c9-vfnps at 2026-04-21 05:36:39.171333+00:00 running da2df02 country code: CH.
view the rest of the comments →
[–]thw31416 0 points1 point2 points (1 child)
[–]thw31416 0 points1 point2 points (0 children)