Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strike>I think that, since you are declaring the <code>isPrime</code> global variable after the definition of <code>primeTest()</code>, the Python interpreter treats the isPrime within the function as a local variable.</strike></p> <p>I was mistaken.. you have to declare it as <code>global isPrime</code> from within the function. Order of declaration (function or variable first) doesn't matter. Something like this:</p> <pre><code>def primeTest(): global isPrime isPrime = False isPrime = True print isPrime # returns True primeTest() print isPrime # returns False </code></pre> <p>Note that you cannot write <code>global isPrime = False</code>; it must be two statements.</p> <p>Anyway, it is rather bad practice to be changing global variables like that. <strike>Why don't you pass <code>isPrime</code> as an argument to <code>primeTest()</code>?</strike></p> <p><b>Edit:</b></p> <p>Okay, my answer was <em>still</em> too hasty. Simply passing isPrime as an argument doesn't work, because boolean values are immutable types. The best way to handle your current problem is to have <code>isPrime</code> as a return value:</p> <pre><code>def primeTest(testnum): ... do your calculations here, set a variable ret_val to True or False ... return ret_val </code></pre> <p>Now you can do <code>isPrime = primeTest(10)</code> to find out if any number is a prime.</p> <p>However, if you pass your function a mutable type (like a list), you can modify it from within the function. <a href="https://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference">This post covers it quite well.</a> But you needn't concern yourself with that just yet.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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