+ 1
Alternative option for this...
I am doing some of the code coach challenges. In 3 recent ones I have written a for loop to assess a condition and print one of two statements depending on the assessment. The only way I could do it was to have a seperate list or integer that if the for loop was positive I added one to the list or integer. At the end then I would print a statement based on this list or integer being > zero... Here is a sample.. d = 0 for i in list: If num % i != 0: print("not divisible by all") break else: d = d + 1 if d>0: print("divisible by all") I just want the statement printed once....
2 Réponses
+ 4
num = 20
mylist = [2, 4, 5, 10]
mylist2 = [2, 4, 5, 11]
print("divisible by all" if all(num % i == 0 for i in mylist) else "not divisible by all")
print("divisible by all" if all(num % i == 0 for i in mylist2) else "not divisible by all")
0
There are many different ways of solving all these challenges, even in one language, some more regular, some more elegant.
The regular, basic way that would work in all sorts of other languages as well would be using a flag.
A flag is a boolean value that contains the result of your testing.
It's in essence what you did, only more 'telling'.
That goes like this:
flag = True
for i in list:
if num % i != 0:
flag = False
break
if flag:
print('divisible by all')
else:
print('not divisible by all')
In Python, there's a nice way to evade using a flag - an additional way to use the keyword 'else':
for i in list:
if num % i:
print('not divisible by all')
break
else:
print('divisible by all')
This else means: 'If the loop is not broken...'
So if break happens, it will not be executed.
You could also make a function and base the output on that:
def divisibleByAll(n, divs):
for d in divs:
if n % d:
return False
return True