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

Whats your Function/ Define your Function
Functions are used to group a set of instructions and logic that performs a specific
task. So, we should make functions perform one specific task and choose a name that
gives us a hint about that. Functions are defined using a def statement.
The word def is followed by the name of the function with an optional list of
parameters in parentheses, and the line ends with a colon, which indicates that the next
lines must be indented as a block or suite of instructions.
Let’s start with a function that takes no parameters:

def welcome():
	print('Welcome to the Level1Techs Forum')
	print('This is the Developers section of the forum')
	print('Here we will cover all things Python !')

welcome()

In the previous example, we have the def statement, which defines a function named welcome(). The code in the block that follows the def statement is the body of the function. This code is executed when the function is called, not when the function is first defined. The welcome() line following the code is a function call. When the program execution reaches the welcome() function call, it simply jumps to the top line where it is defined and execute the function. Functions also can compute a result value and let us specify parameters that serve as function inputs and may differ each time the code is run.

Coding an operation as a function makes it a generally useful tool, which we can use in a
variety of contexts. More fundamentally, functions are the alternative to programming by
cutting and pasting rather than having multiple redundant copies of an operation’s code,
we can factor it into a single function. In so doing, we reduce our future work radically.
A major purpose of functions is to group code that gets executed multiple times.
Without a function defined, you would have to copy and paste this code each time.

Q: This is propably the longest start to any of the coversations we've had. Why so serious?
A: There are many facets to functions. Functions are a nearly universal program-structuring device.
You may have come across them before in other languages, where they may have been called
subroutines or procedures. Functions serve two primary development roles:
1. Maximizing code reuse and minimizing redundancy
2. Procedural decomposition

Q: Can we cover most of this in code? Some of these post are getting long and boring...
A: I guess it's time to actually start posting code and having you get your hands dirty.
This will also mark the inaguration of the Code_Warrior Corner

Here is a sample of def() you might find ineresting, Open up your favorite text editor
(hopefully one with a linter if possible) and follow this one called Classic Quotes:

from random import choice

def Quotes(Classic_Quote):
	if Classic_Quote == 'a':
		return 'Luke I am your Father !!!'
	elif Classic_Quote == 'b':
		return 'When nine hundred years old you reach, look as good you will not'
	elif Classic_Quote == 'c':
		return  'Truly wonderful, the mind of a child is.'
	elif Classic_Quote == 'd':
		return 'That is why you fail.'
	elif Classic_Quote == 'e':
		return 'A Jedi uses the Force for knowledge and defense, never for attack.'
	elif Classic_Quote == 'f':
		return 'Adventure. Excitement. A Jedi craves not these things.'
	elif Classic_Quote == 'g':
		return	'Judge me by my size, do you?'
	elif Classic_Quote == 'h':
		return 'Fear is the path to the dark side…fear leads to anger…anger leads to hate…hate leads to suffering'
	elif Classic_Quote == 'i':
		return 'Wars not make one great.'
	elif Classic_Quote == 'j':
		return 'Luminous beings are we…not this crude matter.'
	elif Classic_Quote == 'e':
		return 'Do. Or do not. There is no try.'
	elif Classic_Quote == 'e':
		return 'Never tell me the odds!'


ran = choice('abcdefghijkl')
txt = Quotes(ran)
print(txt)

There are sure to be questions on this post, I know many of you want to get to what we are all here for and that is CODE ! So post your simple functions in the comments section and let's start a code challenge to use your function in another program! Even better use all that you've learned in this short course and post it as well !

Code up Code_Warriors !!!

6 Likes

Am still not sure if i should be happy or sad bout the fact that Python does not have a switch. I mean elif works.

1 Like

IIRC the reason switches are a thing is so that what you've written can be compiled/interpretted more efficiently than an if/elif because it's assumed that the order of the cases is irrelevant to you - whereas with an if/elif the order is presumed to be of significance.
Python's primary objective isn't exactly to be efficient and anything that you could write with a switch/case can easily be substituted for some if/elifs anyway so it's a bit of a fruitless effort to implement switches in python.

1 Like

Like everything in Python.
But yeah it makes sense.

Just like the array/list thing. I just added the similar information.

1 Like

You could, I suppose, argue that the if/elifs are a bit cumbersome to read (and probably type, too).
I'd go for that because I'm a lazy twerp.
I'd probably write something more along the lines of this to save myself and my keyboard the effort.

from random import choice

def Quotes(Classic_Quote):
        return {"a":"Luke I am your Father !!!",
                "b":"When nine hundred years old you reach, look as good you will not",
                "c":"Truly wonderful, the mind of a child is.",
                "d":"That is why you fail.",
                "e":"A Jedi uses the Force for knowledge and defense, never for attack.",
                "f":"Adventure. Excitement. A Jedi craves not these things.",
                "g":"Judge me by my size, do you?",
                "h":"Fear is the path to the dark side…fear leads to anger…anger leads to hate…hate leads to suffering",
                "i":"Wars not make one great.",
                "j":"Luminous beings are we…not this crude matter.",
                "e":"Do. Or do not. There is no try.",
                "e":"Never tell me the odds!"}.get(Classic_Quote)

ran = choice('abcdefghijkl')
txt = Quotes(ran)
print(txt)

Dictionaries are rad. That function will also return None alike in the original if the quote letter/whatever isn't found (if the key given to the .get() method isn't found in the dictionary, it returns None).

2 Likes

Is indeed an option too, but yeah i think if you have to use too many if statements its best to create a good function.

1 Like

Good stuff there ! I'm a bit all over the place, but that's kind of the intention. Community involvement is what I was looking for, in the early stages what I did shows the Noobs the fundamental aspect, what you did is Next Level stuff. What I like is the fact that you did it and that's great. Thanks for the contribution. And yes Dictionaries are rad ! The Ep.2.2 module is Dictionaries

Something that's been left untouched about functions is how to specify keyword arguments!

To specify a keyword argument, all you have to do is specify your keyword in the parentheses after the name of the function you're declaring, and then give it a default value to take if it's not otherwise specified when your function's called.

e.g. with these quotes, I was mildly upset there were no famous cat quotes! Like the infamous "Meow"! So, I added a cheat to get a meow whenever I want ;p

from random import choice

def Quotes(Classic_Quote,  cheat=False):
    if not cheat:
        return {"a":"Luke I am your Father !!!",
                "b":"When nine hundred years old you reach, look as good you will not",
                "c":"Truly wonderful, the mind of a child is.",
                "d":"That is why you fail.",
                "e":"A Jedi uses the Force for knowledge and defense, never for attack.",
                "f":"Adventure. Excitement. A Jedi craves not these things.",
                "g":"Judge me by my size, do you?",
                "h":"Fear is the path to the dark side…fear leads to anger…anger leads to hate…hate leads to suffering",
                "i":"Wars not make one great.",
                "j":"Luminous beings are we…not this crude matter.",
                "e":"Do. Or do not. There is no try.",
                "e":"Never tell me the odds!"}.get(Classic_Quote)
    else:
        return "MEOW!"
    
ran = choice('abcdefghijkl')

txt = Quotes(ran, cheat=True)
print(txt)

I can call this function without issues omitting the keyword argument as it's optional (it'll just take its default value), like this...

txt = Quotes(ran)
print(txt)

and I can also omit the keyword (this also works for multiple keyword arguments, assuming you know the order they're in at the function's declaration).

txt = Quotes(ran, True)
print(txt)
1 Like

I'm beginning to wonder if anyone's using these guides or this is just a group of people writing snippets that serve no purpose besides self testing, lol.

1 Like

Just realised all of the code in the OP has no syntax highlighting. You can get it by doing


```python

<stick code here>

```
1 Like

...

it's just at the beginning there were people asking for help, like they were actually learning from the guides you're writing, and then it kinda died down.

yeah think its indeed better too scale it down to 1 a week or something. Seeing how many it are now in one week. Else people tend to ignore it for other stuff.

It's sadly how stuff works on this forum and its sad for the great time you spend writing it down.

2 Likes

I think these posts are going to be very long-lived. We can point them toward anyone looking to get familiar with python

5 Likes

Nevermind having a little fun with it.

All these attempts at re-writing the code and no one noticed/fixed the fact that the last 2 aren't k and l but rather e and e again. :)

1 Like

It's the MEOW ! feature... @_Cat

I left it in to show what happens when you do it in a dict, I think @Miguel_Sensacion left it in to show what happens to it in an if/elif - you'll never get the last two instances of "e" with the if/elif, whereas with the dictionary I you'll only ever get the last definition of the key "e".
Forgot to mention ;p

1 Like

I'll do some light Dictionary & Tuples work tomorrow, you are more than welcome if you like to do an Ep 2.3 Tuples?

1 Like

Hey man it's your jam I'd rather just throw in bits and bobs ;)

1 Like