New course! Every coder should learn Generative AI!
Try a free lesson+ 1
[Solved] def function not printing the output using the fstrings !! Why??
I recently learnt about def function. I made a code on def function but then I realised that I can make def codes using f strings also. But when I tried, it always shows either error or undesired output. Please help. https://code.sololearn.com/cTMXF2Pds8W7/?ref=app
6 Answers
+ 6
Function returns none by default .
print(f'The sum of a and b is {add("all","of you")}')
Use double quotes to differentiate it from single quotes .
+ 8
∆BH∆Y , i would not recommend to print from the function. add() function should only calculate and then return the result. this could be like:
# Defining a function add
def add(a,b):
return a + b # <<<<<<<<
#print(a+b)
# Calling the function add normally: 1st case
print(add(4,7)) # <<<<<<<<
# Calling the function add using f strings: 2nd case
print (f'The sum of a and b is {add(4,7)}')
# Calling the function add usin fstrings, now; concatenation: 3rd case
print(f'The sum of a and b is {add("all ","of you")}')
+ 4
∆BH∆Y
"""add(4,7)
# Calling the function add using f strings: 2nd case
print (f'The sum of a and b is {add(4,7)}')
"""
In the first ,add(4, 7) you aren't printing the actual function but in second one you are doing so .
+ 4
Thank you Abhay Cyan Lothar Mir Abir Hossain
Because when I learnt about return it was not clear to my mind that what is the difference between the use of print and return in def...after asking the question and after all your answers, my doubt is totally clear...thanks again 😃
The tip by @Abhay was also useful
print(f'The sum of a and b is {add("all","of you")}')
Use double quotes to differentiate it from single quotes .
+ 3
# input
print(print('hello world'))
# output
hello world
None
# double print function creates a None always. I guess print(print('hello world')) should produce -->
hello world
None
None ( not sure, we can try it )
So print(add(4,7)) -->
print(print(4+7)) -->
11
None
+ 1
Thank you Abhay