We appreciate your visit to 14 What will be the output of the following code python x 50 def Alpha num1 global x num1 x x 20 num1 Beta num1. This page offers clear insights and highlights the essential aspects of the topic. Our goal is to provide a helpful and engaging learning experience. Explore the content and find the answers you need!

14. What will be the output of the following code?

```python
x = 50

def Alpha(num1):
global x
num1 += x
x += 20
num1 = Beta(num1)
return num1

def Beta(num1):
global x
num1 += x
x += 10
num1 = Gamma(num1)
return num1

def Gamma(num1):
x = 200
num1 += x
return num1

num = 100
num = Alpha(num)
print(num, x)
```

What values will be printed for `num` and `x`?

Answer :

Let's examine the code step by step to understand the output:

  1. We start with x = 50 globally defined, and num = 100.

  2. We call the function Alpha(num) passing num which is 100.

  3. Inside Alpha, num1 is assigned 100, then global x makes x accessible and writable within the function. Now num1 becomes num1 + x = 100 + 50 = 150.

  4. After that, x is incremented by 20, so x = 50 + 20 = 70.

  5. num1 = Beta(num1) is called with num1 = 150.

  6. Within Beta, global x is used again to access x = 70. We have num1 = num1 + x = 150 + 70 = 220.

  7. Here, x is incremented by 10, making x = 70 + 10 = 80.

  8. Then, num1 = Gamma(num1) is called with num1 = 220.

  9. In Gamma, a new local variable x is defined as 200, shadowing the global x. So, num1 = num1 + x = 220 + 200 = 420. The local x does not affect the global x.

  10. Gamma returns 420, Beta returns 420, and finally, Alpha returns 420, so num is now 420.

  11. Finally, we print num, x. num is 420, and the global x is unchanged within Gamma and is 80.

Therefore, the output of the code is 420 80. The step-by-step examination helps us clearly understand how the functions and global variable affect the final result.

Thanks for taking the time to read 14 What will be the output of the following code python x 50 def Alpha num1 global x num1 x x 20 num1 Beta num1. We hope the insights shared have been valuable and enhanced your understanding of the topic. Don�t hesitate to browse our website for more informative and engaging content!

Rewritten by : Barada