OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Condition in a function to stop it when called in a loop? [closed]

  • Thread starter Thread starter Saeed
  • Start date Start date
S

Saeed

Guest
Please consider this simple function:

Code:
def my_func(x):
    if x > 5:
        print(x)
    else:
        quit()

    print('this should be printed only if x > 5')

Then if we call this function in a loop:

Code:
for i in [2, 3, 4, 5, 6, 7]:
    my_func(i)

Expected output:

Code:
6
this should be printed only if x > 5
7
this should be printed only if x > 5

But quit actually disconnects the Kernel.

I know that the following function will work but I do not want to have the second print up there:

Code:
def my_func(x):
    if x > 5: 
        print(x)
        print('this should be printed only if x > 5')
    else:
        pass

Lastly, I know that if I put the loop inside the function, I can use continue or break but I prefer to keep the function simple and instead put the function call in a loop. So, what needs to change in the first function to achieve the expected output?
<p>Please consider this simple function:</p>
<pre><code>def my_func(x):
if x > 5:
print(x)
else:
quit()

print('this should be printed only if x > 5')
</code></pre>
<p>Then if we call this function in a loop:</p>
<pre><code>for i in [2, 3, 4, 5, 6, 7]:
my_func(i)
</code></pre>
<p><strong>Expected output:</strong></p>
<pre class="lang-none prettyprint-override"><code>6
this should be printed only if x > 5
7
this should be printed only if x > 5
</code></pre>
<p>But <code>quit</code> actually disconnects the Kernel.</p>
<p>I know that the following function will work but I do not want to have the second print up there:</p>
<pre><code>def my_func(x):
if x > 5:
print(x)
print('this should be printed only if x > 5')
else:
pass
</code></pre>
<p>Lastly, I know that if I put the loop inside the function, I can use <code>continue</code> or <code>break</code> but I prefer to keep the function simple and instead put the function call in a loop.
So, what needs to change in the first function to achieve the expected output?</p>
 

Latest posts

Top