Return inside if condition - python

def hi (n):
if n<=5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
1) In the above code i have declared a function hi() which takes an input n
2)I want to iterate inside the if condition until n is less than 5,totally execute the print statement 4 times
3)But it is not working after execution of one time inside the condition
4)I am thinking i have given return statement for if condition but the function is totally being exit
5)(i am thinking i am returning the n value to the if condition and it checks the condition and it will iterate ) if wrong correct me

Not sure exactly what you want to achieve, but based on the info you have provided:
def hi (n):
while (n < 5):
print("we are inside hi")
n -= 1
Briefly speaking, using return inside a function means to return the value that is followed or return None if there is no value. In addition, the execution of the function is terminated just after the return statement is executed.
You can use the return statement, but if you want to iterate it is not correct because your function will terminate its execution. Also remember that once you execute the iteration of the loop, there won't be more statements to execute inside your function which means an implicit return statement will be executed which returns None, and again function ends execution.

You need a loop for this. Try this instead
for _ in range(4):
print("we are inside hi")

Of course, you need a loop to make iteration. If you just want to print the statement 4 times, simply make a range of loop.
def hi ():
for n in range(4):
print(n+1," we are inside hi")
hi()

you can use this:
def hi (n):
while n <= 5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
you need a loop to iterate and return statement will exit from the function call.

Related

Is there a way to take conditions for for loop as an input in python? I am having trouble with this code

I recently had an idea of doing sigma(Σ) using python
So, I wrote this code.
def sigma(i,target,condition='i'):
if condition=='i':
a=0
for f in range(i,target+1): #the loop sums all the numbers from i to the target given
a+=f
print(a)
'''if user enters a condition than,
every number will follow condition and then be added to each other'''
else:
lis=list()
condition for i in range(i,target+1):
lis.append(i)
print(sum(lis))
but the code I wrote above just gives me a wrong output as it takes the variable condition as type 'string'.
The problem is actully to take the argument condition not as a string
for example, let's say user entered:
sigma(1,100,condition='i'*2)
so the code should run for loop like this:
i*2 for i in range(i, target+1)
but it runs like this:
'ii' for i in range(i, target+1)
For what I can understand, you should pass an anonymous function as argument to accomplish what you are looking for.
Consider that this is not a valid syntax: i*2 for i in range(i, target+1), so I consider it as a pseudo code explained by your comment.
You should change your method in this way:
def sigma(i, target, condition='i'):
if condition=='i':
a=0
for f in range(i,target+1):
a+=f
print(a)
else:
lis=list()
for i in range(i, target+1):
lis.append(i)
print(condition(sum(lis)))
So that if you call sigma(1,100,'i') #=> 5050 you fall in the true part of the statement.
For the false part of the statement you need to call the method passing a lambda expression as parameter:
sigma(1,100, lambda i: 2*i) #=> 10100
It happens that the argument condition when passed as lambda works as if it was defined as:
def condition(i):
return 2 * i
I would like to point out that the sum of the first n natural numbers is given by a math formula, so you don't need a loop:
n * (n + 1) // 2
Also should be better to return a value than to print.
I'd rewrite the method:
def sigma_2(i, target, condition=None):
sum_i_to_target = (target*(target+1)-(i-1)*i)//2
if condition is not None:
return condition(sum_i_to_target)
else: # need to check that condition is a lambda function
return sum_i_to_target
So call this way:
sigma_2(2, 20) #=> 209
sigma_2(2, 20, lambda i: 2*i) #=> 418
You've initialized i from what I can see from your code as a string.
If you would like for the compiler to read it as int then initialize i as int.
For example:
i=1

generators, python, infinite loop

I am trying to produce a list of odd numbers using a generator (just to get a better insight into generators). I wrote the following code but, it doesn't stop running! While I expect the code stops when the condition i>n meets.
Any help is appreciated.
import sys
def odd(n):
i=0
while True:
if i%2==0:
continue
yield i
i+=1
if i>n:
return
# Here we build a generator
g = odd(10)
while True:
try:
print(next(g),end=' ')
except StopIteration:
sys.exit()
When i is even, you don't increment it, so it stays even for every subsequent iteration of the loop and never gets larger than n.
You want to increment i whether or not it is even.
def odd(n):
i=0
while True:
if i%2 != 0: # yield i only if it is odd
yield i
i+=1 # Increment i in either case
if i>n:
return
In my opinion, you have two style issues in your code that make it hard to see the problem:
The use of continue. A simple if statement would make it easier to see which code might not execute and which code will definitely execute. continue is mainly useful when you have nested if statements making things complicated.
You don't utilize the while condition. This assumes that the while loop will have to execute at least once. When writing a loop, you should generally consider what happens if the loop needs to execute 0 times. What if someone passes an argument of -1? What if you change the initial value of i to 1 to save an iteration?
def odd(n):
i = 0
while i <= n:
if i % 2:
yield i
i += 1
# Automatically return and throw StopIteration.

Python function recalls itself after return statement?

The question is rather academic. I came across the following behaviour in python:
This Code:
def dosth():
print("new")
for n in range(0,10):
return False
dosth()
actually gives me 10 prints instead of one. So does the function recursively call itself after the return statement because there is no break?
If I put in a break before the return statement I still get 2 prints instead of only one.
Can someone explain this behaviour
I only see one new printed.
It also appears that you're a missing a colon : at the end of your loop for n in range(0,10).
def dosth():
print("new")
for n in range(0,10):
return False
dosth()
# prints 'new' once...

How do I transfer variables between functions?

I have been attempting to program a calculator using the tkinter module in Python, and I have made 14 functions corresponding to each number and symbol on the calculator. The code below is for the number 1, for example.
The program doesn't return the values as it should, however. I use the values from the previous function in further functions as parameters, but they don't seem to go through and I constantly get result 0.
The variables a and b correspond to two numbers to be used in the calculation and num is a counter for the program to know when to give the number to a and when to give it to b. I have tried inserting a print in this code and a and b was printing correctly but it seems to be a problem with the return.
Any help would be appreciated.
def num1(num,a,b):
if num == 0:
a=a+1
num=num+1
elif num == 1:
b=b+1
return num
return a
return b
Python function only return one value. When you write return a;return b, you only return the first occurrence.
What you need to do , is pack those elements and return them as a tuple:
def num1(num,a,b):
if num == 0:
a=a+1
num=num+1
elif num == 1:
b=b+1
return num, a, b
you need to keep in mind that the first return statement that reaches the work flow causes the end of the current function and returns the value supplied.
the return a; return b lines will never be reached, the execution flow returns to the caller after the first return statement
You can return a list, dictionary,tuple, variable. But a function can't return multiple times. You can try inserting the values in a list and then return the list.

Code skips the loop even though the condition evaluates to true

I cannot get this portion of my program to enter the while loop. After plugging in values for poly, x_0, and epsilon, the program calculates a value for ans using the function evaluate_poly() which works correctly and in my specific instance gives the answer -13.2119. My epsilon value used is 0.0001. Since the abs(ans) is in fact greater than epsilon why is it skipping the loop?
I put a print ans statement right below the x_01 = 0 line to make sure it was calculating correctly before the while loop and also a print epsilon statement to make sure it was taking in my epsilon value correctly (which it does).
def compute_root(poly, x_0, epsilon):
"""uses newton's method to find a root of a polynomial function"""
ans = evaluate_poly(poly, x_0)
x_01 = 0
while abs(ans) > epsilon:
Dpoly = compute_deriv(poly)
Fprime = evaluate_poly(Dpoly, x_01)
return ans
x_01 = x_0 - (ans/Fprime)
print x_01
return x_01
print ans
You put two return statements inside your loop. When the first one is hit, the function exits instantly only. So, not only is the while loop being exited on the first loop, but the print statements are never being reached.
You have return ans inside your loop. So at that point the function will exit, and the print will never be reached.
If ans is really -13.2119 then it does enter the loop, it just doesn't perform everything in it because of the return.
Even if you remove the return ans line inside the loop, there is also return x_01 at its end. So in that case the loop will run at most once, which will make it the same as an if statement.

Categories

Resources