Python exercise question 023: 2 years older than the next student, python023
[Python exercise question 023]Five people sat together and asked how old is the fifth person? He said he is two years older than 4th. Asked about the age of 4th People, he said he was two years older than 3rd people. Ask the third person, and say that the person is two years older than 2nd. Ask 2nd people, saying they are two years older than the first. Finally, I asked the first person that he was 10 years old. How old is the fifth person?
-----------------------------------------------------
This is really ...... Can it be calculated by mental computing? Well, we should train recursive functions again. These questions are not clear about recursive functions recently. However, it seems that I have understood the method of recursive functions. The code for this question is as follows:
Def f (n): if n = 1: return 10 else: return f (n-1) + 2 print (f (5 ))
The output result is as follows:
18
In fact, it is not hard to understand that the first person is 2 years older than the last one. In the function expression, f (n) = f (n-1) + 2. Well, I seem to be able to understand recursion, yeah ~
Follow the rules and write non-recursive code:
A = 10for I in range (4): a + = 2 print ()
Now, it seems familiar with the for loop. The question is indeed effective ~~~
++
Source: getting started with programming languages: 100 typical examples [Python]