+ 2

Are def() important ?

Hello I am doing exercise that I found on pynative.com Basic thing, the last one being to take a string and make a new string with all the elements with an odd index. Doing the exercises is fun but each time I look at the solution, they are using def() for their solution. Like today my solution : #Question 3: Accept string from the user and display only those characters which are present at an even index x = input('enter string') d = list(x) y = [] for i,j in enumerate(x): if i%2 != 0: y.append(j) print(f"{''.join(y)}") the official solution def printEveIndexChar(str): for i in range(0, len(str)-1, 2): print("index[",i,"]", str[i] ) inputStr = input("Enter String ") print("Orginal String is ", inputStr) print("Printing only even index chars") printEveIndexChar(inputStr) Why are they using def() all the time. Is this just the way this coder like to proceed, or is it a good habit to take for the future when you do bigger projects?

30th Nov 2019, 6:24 AM
nicolas seespan
nicolas seespan - avatar
3 Respostas
+ 6
In other words, you are asking why to use functions in programming. If you write a simple script, that follows a fixed series of statements that you only execute once, it is ok to do it without functions. This is called imperative style programming. However when you deal with slightly more complex tasks, the benefits of 'procedural' or 'functional' style will be more trivial. This is about code reusability. You may want to repeat the same statements in multiple places of your program, maybe with slightly different parameters. You may want to test your code with different values. Then it makes sense to organize small sensible blocks of your code into self-contained functions (def) which may or may not have arguments and return values. https://en.m.wikipedia.org/wiki/Procedural_programming
30th Nov 2019, 6:36 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Thanks for the input. So in short, make no difference for the code now, but learning to use def is a good exercise for future longer coding project. " all answer must take the form def90" it is
1st Dec 2019, 11:51 AM
nicolas seespan
nicolas seespan - avatar
0
I am in the dictionary part in 'python crash course' So I did a code that check that the same value are present in the key of the dictionary and in the list. Print the value associated to the key who are also in the list, and give me the number of such occurrence. With a def function def test(a,b): i = 0 for t in a: if t in b: ve = a[t] print(f"this is in common {ve} ") i += 1 return i e = { 1 : 'q', 2 : 'd', 45 : 'f', } d = [x for x in range(0,7)] vd = test(e,d) print(vd)
1st Dec 2019, 1:00 PM
nicolas seespan
nicolas seespan - avatar