+ 1

Defining a function question!

Hey! I’m currently learning how to define a function and had a question. If I wanted to make a feet to inches function converter, would it look like this? def feet_to_inches(feet): inches = feet*12 return inches

25th Mar 2018, 3:50 AM
Robbie Jones
Robbie Jones - avatar
3 odpowiedzi
+ 2
That's right, spot on! And to call the function later on (in this case with 3 feet), just do this, and the number of inches should be equal to 36: inches = feet_to_inches(3)
25th Mar 2018, 4:06 AM
DaemonThread
DaemonThread - avatar
+ 1
Looks good! One thing that you can look into as well is to make sure that what is passed to the argument is a number and not a string or something else. If it’s anything other than a number the program will have an error and stop working. This requires some condition checks (if...). Example: feet_to_inches(3) #returns 36 feet_to_inches(‘three’) #error!
25th Mar 2018, 8:42 AM
dCook
dCook - avatar
+ 1
Awesome! Thanks guys! I was having the hardest time last night when calling the function and getting a users input for the defined function. I was using: feet = input(“Enter number of feet :”) print(feet_to_inches(feet)) And every time I entered a number, it would just repeat my input 12 times! I was getting so frustrated as to why it was doing this. Then I realized I needed to convert (feet) to an integer like this and it solved it! print(feet_to_inches(int(feet)))
26th Mar 2018, 1:22 AM
Robbie Jones
Robbie Jones - avatar