This question already has answers here:
Why does python use 'else' after for and while loops?
(24 answers)
Closed 1 year ago.
I would like to understand why the following python code to find all prime numbers less than n works:
def prime(n):
for q in range(2,n):
for i in range(2,q):
if q%i==0:
print(q, "is not a prime")
break
else:
print(q, "is a prime")
My problem is that I thought the else: should be aligned under the if: but it isn't in this code. I think the problem is that I do not understand well enough what the "break" does.
In Python, for loops can also have an else: block (see for_stmt in the parser grammar). The else block of a for loop is entered if the loop runs to completion without hitting any break statement.
In your case, the break is conditional upon q % i == 0, so the else block here means that no number in range(2, q) has satisfied this condition, i.e. that q has no divisors besides 1 and itself.
Note: this primality test is very similar to a code snippet from the tutorial.
Related
This question already has answers here:
What is a None value?
(9 answers)
Closed 28 days ago.
I am attempting a practice question on Coursera where the code seems to be throwing me off even though the logic seems fine to me. I am a beginner trying to get my hand on the language but I am running into logical errors.
def is_positive(number):
if number > 0:
return "True"
else:
return "None"
number=-1
print(is_positive(number))
From your comment, I assume that you want to return the values True and None, rather than the strings "True", and "None". To do this, simply remove the quotation marks surrounding the string.
def is_positive(number):
if number > 0:
return True
else:
return None
number=-1
print(is_positive(number))
n = int(input())
print( True if n > 0 else False)
I think this is what you're looking for
This question already has answers here:
Is the shortcircuit behaviour of Python's any/all explicit? [duplicate]
(4 answers)
Closed 9 months ago.
Will python's all function exit as soon as it finds a False in the iterable? Or will it continue checking the rest?
For example, if i is not divisible by 20, will the below code continue checking if it is divisible by 19 and 18 and so on?
def min_divisible(target_n):
'''
Returns the smallest number that is divisible by all integers between 1 and n
'''
i = target_n
while not all((i%j == 0) for j in range(target_n,2,-1)):
i+=target_n
return f'{i:,}'
print(min_divisible(20))
all will stop the iteration as soon as it encounters a "falsey" object. You can see this with a simple example:
def produce_numbers():
for k in range(10):
yield k
print(k)
all(k < 3 for k in produce_numbers())
This prints
0
1
2
This is spelled out in Python's documentation. It states that the following is a functionally equivalent definition of all:
def all(iterable):
for element in iterable:
if not element:
return False
return True
This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 2 years ago.
Okay, so here is a piece of code. The function of the code is to take a value and determine whether or not it is odd or even.
def isEvenOrOdd(num):
return 'odd' if num % 2 else 'even'
Now my question lies in why this works. The way I am currently looking at this, is that --
num%2 returns a value. If num is 3, then num%2 = 1.
Why would the value of '1' satisfy the 'if' condition?
I assumed this was a matter of 1 and 0, but I tried the same code with %4, and if 3 is returned, it still satisfies the if statement.
I understand this may be a basic question for some, so my apologies for perhaps being slow in understanding this. Thank you!
Thank you for your help ! I actually understand it now
The reason has to do with the "truthy-ness" of objects in Python. Every object in Python, even if it's not a boolean value, is considered "truthy" or "falsy". In this case, an integer is considered "truthy" if and only if it is not zero.
Therefore, if the number is odd, its modulus will be 1 which is considered true. Otherwise, the modulus will be 0 which is considered false.
If you switch the modulus to 4, the result will be truthy iff the remainder is not zero (i.e., if the number isn't a multiple of 4).
in python the, some data types has a true value or a false value, it doesn't have to be a boolean.
for example
test = None
if test:
print("working")
else:
print("Not working")
you will notice you get an ouput of Not working the reason is for object None is regarded as False same applies for some other data type , for integer, as long as a value is zero (0) it will take it as False
So in your case, if num % 2 return 0 then you will have
'odd' if 0 else 'even' # will will return 'even'
This question already has an answer here:
Why Python recursive function returns None [duplicate]
(1 answer)
Closed 2 years ago.
I'm trying to create a recursive function in Python (as part of an online course) which takes two numbers and returns the highest common denominator between them, however, the function won't return the value.
My code is:
def gcdRecur(a, b):
x = min(a,b)
y = max(a, b)
if x == 0:
return y
else:
gcdRecur(x, y%x)
When I test the function with
gcdRecur(2,12)
or
gcdRecur(6,12)
nothing is returned. I know the function works because if I print y before I return it then the correct denominator is printed to the console, I'm just not sure why the function doesn't output y.
It's probably something obvious but as I'm new to Python I'm not sure what I'm doing wrong.
Any help would be much appreciated.
You need to return something in both branches:
else:
return gcdRecur(x, y%x)
This question already has answers here:
How to check for palindrome using Python logic
(35 answers)
Closed 7 years ago.
very new to programming and I am trying to solve a few Project Euler problems. I would like to know for a python code which identifies palindrome and non-palindrome. What is the most efficient way to do this? could you please show the code you find most efficient for this problem.
You can do this very simply by just checking if the string that you input is equal to itself reversed (that's what a palindrome is).
def check_palindrome(s):
return s == s[::-1]
[::-1] reverses the string because the -1 tells how many steps to go by and negative will go through the string in reverse.
If you will need to check if integers are palindromes, you can do:
def check_palindrome(s):
return str(s) == str(s)[::-1]
I'm a big fan of simplicity over (potentially false) optimizations. Start with something straight forward, and move on from there:
def is_palindrom(s):
length = len(s)
for i in range(length / 2):
if s[i] != s[length - i - 1]:
return False
return True