Note that there are some explanatory texts on larger screens.

plurals
  1. POMaking a nested for loop (Python 3.x)
    primarykey
    data
    text
    <p>So what I am trying to do is make this "Triangle" in python with for loops:</p> <p><img src="https://www.mathsisfun.com/images/pascals-triangle-n-choose-k.gif" alt="Pascal"></p> <p>But with the text like so:</p> <pre><code>0|0 1|01 2|012 3|0123 4|01234 </code></pre> <p>What the output that I currently have is:</p> <pre><code>0|01234 1|01234 2|01234 3|01234 4|01234 </code></pre> <p>And here is the code for the output:</p> <pre><code>def pascal(n): answer = "" for rows in range(n): answer = str(rows) + "|" for col in range(n): answer = answer + str(col) print(answer) pascal(5) </code></pre> <p>My question is, how the heck do I make the ouput do this?(Im stumped as to what im supposed to do):</p> <pre><code>0|0 1|01 2|012 3|0123 4|01234 </code></pre> <p><br></p> <hr> <p>If anyone would like to see what the hell I was trying to accomplish, heres my solution</p> <p>Soooooooo, this blue triangle:</p> <p><img src="https://www.mathsisfun.com/images/pascals-triangle-n-choose-k.gif" alt="Pascal"></p> <p>turns into the pascal triangle, by "n choose k":</p> <p><img src="https://www.mathsisfun.com/data/images/binomial-n-choose-k.png" alt="formula"></p> <p>I was trying to figure out the for loops so I can have the basic setup done(which is the blue triangle), which you guys helped with :)</p> <p>So the code that I came up with to get the n choose k is this:</p> <pre><code>def factorial(n): answer = 1 for number in range(2, n+1): answer = answer * number return answer def pascal(n): answer = "" for rows in range(n): answer = "" for col in range(rows+1): answer = answer + str( int(factorial(rows) / (factorial(col)*factorial(rows-(col)))) ) print(answer) pascal(10) </code></pre> <p>The factorial() is the exclamation point in the n choose k formula and I made the rest of the formula with this code:</p> <pre><code>factorial(rows) / (factorial(col)*factorial(rows-(col))) </code></pre> <p>So any n that is greater than 0, makes a pascal triangle :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload