I want to ask, the code below produces triangles * which are only odd.... but I'm confused... can anyone explain why the modulus can produce odd triangles and also why the else command is needed? (note I don't really understand modulus)
count = 1
while True :
if count % 2 :
print ('*'*count)
count += 1
else:
count +=1
continue
if count > 10 :
break
The expression if (count % 2):
means if the count is odd.
Explanation:
count % 2
will always equal 0 if count is an even number
will always equal 1 if count is an odd number
if count % 2
when count
is odd breaks down to if 1
which is always True
if count % 2
when count
is even breaks down to if 0
which is always False
For your second question the else actually isn't necessary, it could be rewritten like this
count = 1
while True:
if count % 2 :
print ('*'*count)
count += 1
if count > 10 :
break
When you consider a standard equalateral triangle made of *
:
this is what it looks like using only odd numbers..
*
***
*****
*******
*********
***********
*************
this is what it would look like using evens and odds
*
**
***
****
*****
******
*******
Modulus in this case differentiates between odd and even numbers. In your case, as you can see in the printed pyramid, you only have odd values - 1,3,5 etc. You are in the "if" part when you have an even number, and in the else part for the off.
I suggest you put more print statements in the program to see it's behavior in greater detail.
The if check for return value = 1, not zero. If you try to put if(count % 2 == 0) for example, you will notice non odd print.
Your logic could potentially be simplified:
for i in range(1, 12, 2):
print('*' * i)
Explanation:
The range
operator accepts a stop
value (non-inclusive) and a step
value, which defaults to 1. Here we pass step=2
, so we only iterate over the odd numbers in the range.
Out:
*
***
*****
*******
*********
***********
Modulo, or modular division is like grade school integer division where you don't compute a decimal part, but rather just a whole part, and a remainder. Specifically modulo throws out the whole part, and only keeps the remainder. The opposite of that is integer division, which throws out the remainder: 9//2 == 4 #quotient
9%2 == 1 #remainder
while True:
Do this forever (or until break
or an uncaught error)
if (count % 2):
Do this if count is Odd: (count % 2)
will be 1 if odd, and 0 if even. 1 will cast to True, and 0 will cast to False for the if
condition.
print('*'*count)
construct a string by repeating the string "*"
by count
times, and print
it. count += 1
increment the count variable else
do this if count is even (corollary to prior statement)
count += 1
increment the count variable if count > 10:
when count variable is greater than 10
break
exit the while True
loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.