The Noobs of Python: Ep.4.0 - What's your Function / Define your Function

Heh makes sense, just teasing. ;)

2 Likes

Sorry for my long absence :smiley:
However now I'm back and It's time for another "Super Noobs of Python" post.

Most of @Miguel_Sensacion post is quite easy to understand so i won't be breaking it down however i would like to bring a bit more light to return() function, mainly difference between print() and return()

The print() function writes, i.e., "prints", a string in the console. The return function causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

For example, here's a function utilizing both print() and return:

#defice fun1
def fun1():
    print("this is the 1st Function ")
    return 2

#calling fun1
if __name__ == '__main__':
    print("going to call fun1")
    x = fun1()
    print("called fun1")
    print("fun1 returned ", x)

If you run this as a script (e.g. a .py file) as instead of the Python interpreter, you will get the following output:

going to call fun1
this is the 1st Function
called fun1
fun1 returned  2

Another example:

#defice fahrenheit() function
def fahrenheit(T_in_celsius):
#returns the temperature in degrees Fahrenheit 
	return (T_in_celsius * 9 / 5) + 32


while True:
#ask for imput
	x = input("Please enter temperature in celsius: ")
#if there is no input end print goodbye message and end program
	if x == "":
		print("Goodbye")
		break
	c = float(x)
#call fahrenheit() function for input
	print(c,"C is equal to", fahrenheit(c),"F")

So once its saved and run this will be your output:

pj@LT440S python3 f.py
Please enter temperature in celsius: 23
23.0 C is equal to 73.4 F
Please enter temperature in celsius: 28
28.0 C is equal to 82.4 F
Please enter temperature in celsius: 100
100.0 C is equal to 212.0 F
Please enter temperature in celsius:
Goodbye

The interpreter on the other hand will write return values to the console so you have to be careful not to get confused

Here's another example from the interpreter that demonstrates that:

>>> def fun1():
...     print("this is the 1st Function ")
...     return 2
...
>>> fun1()
this is the 1st Function
2
def fun2(): return 5 * fun1()
>>> fun2()
this is the 1st Function
10

You can see that when fun1() is called from fun2(), 2 isn't written to the console. Instead it is used to calculate the value returned from fun2().

print() is a function that causes a side effect (it writes a string in the console), but program resumes with the next statement. return causes the function to stop executing and hand a value back to the caller.

1 Like

Go for it ! Always welcome to see your comments/additions

posted before finished writing a post :wink:

1 Like

In your example you get a Celsius value as an integer (I assume?), and then divide that by a fraction.

In C/C++ if you divide an integer by a non-whole fraction, then the value of the result of the fraction is truncated to match the typedef of the variable being applied to, which leads to values losing precision.

I understand that 'everything is an object' with python, but I'm curious of how its inter-workings handle this.

Here's an example of a temp conversion using C++ as a reference.

1 Like

@Dynamic_Gravity

User input in python3 is always a string unless you cast it to be an integer or a float.
I have updates comments in my conversion program.

#defice fahrenheit() function
def fahrenheit(T_in_celsius):
#calculates and returns the temperature in degrees Fahrenheit 
	return (T_in_celsius * 9 / 5) + 32

while True:
#ask for imput and assign it to x variable
	x = input("Please enter temperature in celsius: ")
#if there is no input, print goodbye message and end program
	if x == "":
		print("Goodbye")
		break
#cast float class on variable x and assign that new value to variable c
	c = float(x)
#call fahrenheit() function for input
	print(c,"C is equal to", fahrenheit(c),"F")

Also have a look below for further breakdown.

>>> x = input("please enter a number ")
please enter a number 5
>>> y = input("please enter a number ")
please enter a number 3.2
>>> type(x)
<class 'str'>
>>> type(y)
<class 'str'>

as you can see both inputs x and y are strings

>>> a = 5
>>> b = 2.98
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>>

a is an integer and b is a float

>>> c = a + b
>>> c
7.98
>>> type(c)
<class 'float'>
>>>

Here c clearly will be a float since it has a decimal point

>>> a = 5
>>> b = 2.2
>>> c = a * b
>>> print(c)
11.0
>>> type(c)
<class 'float'>
>>>

however here when we multiply float and integer we will get a float in return unless you cast it as a different class. See below:

>>> c = int(c)
>>> print(c)
11
>>> type(c)
<class 'int'>
>>>

best way to is to experiment in the python interpreter and see what values it will return.
See the introduction to The Noobs of Python

Also i have looked at that C++ code but i didn't understand anything ;/

1 Like

Here is another example of defining a functions. This program will roll D4, D6, D8, D10, D12 or D20 dice.
End of the program was with small help of @Miguel_Sensacion.

#!/usr/bin/env python3

#impoer sleep from time library
from time import sleep
#import random library
import random


#D4 Function
def d4():
	while True:

		roll = input("Please press Enter to roll a dice or type exit to end program 	")
		x = random.randrange(1, 5)
		if roll == "exit":
			break
		
		print("You have rolled: ", x, """

			""")


#D6 Function
def d6():
	while True:

		roll = input("Please press Enter to roll a dice or type exit to end program 	")
		x = random.randrange(1, 7)
		if roll == "exit":
			break
		
		print("You have rolled: ", x, """

			""")


#D8 Function
def d8():
	while True:

		roll = input("Please press Enter to roll a dice or type exit to end program 	")
		x = random.randrange(1, 9)
		if roll == "exit":
			break
		
		print("You have rolled: ", x, """

			""")

#D10 Function
def d10():
	while True:

		roll = input("Please press Enter to roll a dice or type exit to end program 	")
		x = random.randrange(1, 11)
		if roll == "exit":
			break
		
		print("You have rolled: ", x, """

			""")

#D12 Function
def d12():
	while True:

		roll = input("Please press Enter to roll a dice or type exit to end program 	")
		x = random.randrange(1, 13)
		if roll == "exit":
			break
		
		print("You have rolled: ", x, """

			""")

#D20 Function
def d20():
	while True:

		roll = input("Please press Enter to roll a dice or type exit to end program 	")
		if len(roll) > 0: 
			prnit("Only exit and empty input are")
		x = random.randrange(1, 21)
		if roll == "exit":
			break
		
		print("You have rolled: ", x, """

			"""

dice_dict = {"d4": d4, "d6": d6, "d8": d8, "d10": d10, "d12": d12, "d20": d20}

#print welcome message
print("""		Welcome to dice rolling simulation.
		You can choose to roll one of the followinf dices
		| D4 | D6 | D8 | D10 | D12 | D20 |

""")

while True:
	dice = input("Which dice you wish to use: ")
	if dice.lower() == "exit":
		break
	elif dice.lower() not in dice_dict:
		print("Incorect input. Please type name of the dice you want to use")
	elif dice.lower() in locals().keys() and callable(locals()[dice]):
		locals()[dice]()	

print("Good bye")
1 Like