0

Python Functions Doubt

I was just wondering that can we make a function that takes two arguments. One is a parameter for a while loop the other is the function such as print("woo hoo"). I tried this out but couldn't find the answer. Please help me if you know anything Here is my attempt: def my_loop(para,func): while para: func my_loop(0==0,print("woo hoo")) When I attempted this It only repeated it once whereas it should've been forever(almost). How to correct this. Also, can we do such thing with conditionals Also, can we do something so it comes like this or something like this: my_loop(True): print("woo hoo")

20th Aug 2020, 2:03 PM
Kunsh-Tyagi
Kunsh-Tyagi - avatar
4 ответов
+ 8
This code should do the job: def my_loop(para,func): while para: func() def my_print(): print('woo hoo') my_loop(True,my_print)
20th Aug 2020, 2:23 PM
Lothar
Lothar - avatar
+ 5
Yes, you can get it to run, but it looks very weird. So it is not recommended to do things this way, because the code has a bad readability and maintaining such a code is a nightmare. def my_loop(para,func,word): while para: func(word) def my_print(txt): print('woo hoo') print(txt) my_loop(True,my_print,'hello') You should prefer understandable codes. Please read the Zen of Python by Tim Peters by using: import this from the condole.
20th Aug 2020, 5:21 PM
Lothar
Lothar - avatar
+ 2
There are 2 things that I find wrong in this code: 1. You are passing print("woo hoo") which evaluates to None to the my_loop function. Instead of passing print("woo hoo") for the func argument you have to pass a function. I recommend using a lambda function. 2. You are not calling the func inside the while loop. In order to call it you must write func() instead of func. The solution would look something like this: # defining the my_loop function def my_loop(para, func): while para: func() # calling the my_loop function my_loop(0==0, lambda:print("woo hoo"))
21st Aug 2020, 11:15 AM
Ali Shah Jindani
Ali Shah Jindani - avatar
0
@Lothar is it possible that my_print takes parameters cause it isn't working for me
20th Aug 2020, 4:00 PM
Kunsh-Tyagi
Kunsh-Tyagi - avatar