could anybody please help explain how the results of the python program in the following picture are calculated? especially the 45.. I maybe too dumb to comprehend but please help me.
I really appreciate the help, thank you very much!
CodePudding user response:
As suggested by @user2512443, its just a summation of numbers upto 10. In order to understand how the output is calculated, you just have to understand and dry run it with the input. Go step by step, and try to figure out what is happening in your code. For example: In your code:
x=1
sum=0
while x<10:
sum = sum x
x = x 1
If you go sequentially, x=1 and sum=0. Then you go to the loop which says that until x is less than 10, do these statements. So what will happen is:
1) 1st iteration:
sum = sum x -> sum = 0 1 =1
x = x 1 -> x = 1 1 = 2
2) 2nd Iteration:
sum = sum x -> sum = 1 2 = 3 (Here, we take new value of sum)
x = x 1 -> x = 2 1 = 3
and so on..
CodePudding user response:
To start with, the first block of code sums all the numbers from 1 to 9.
Process:
#to start with, a number variable is assigned to x, and to sum
x=1 #This holds our counter
sum=0 #this holds the result
#Then, a loop is run through while x is less than 10.
while x<10:
sum =x #the variable x is added to sum
x =1 #x is incremented
Then, the next block of code assigns a variable Tries a loop and then outputs the two variables sum
and product
;
#Assign product to be 1
product=1
##NOTE: this loop will not happen because x is already above or equal to ten
while x<10:
#If this loop was valid, this would multiply all numbers from 1-9
product= product*x
#If this loop was valid, increment x
x =1
The loop will not happen because x=10
, which means that unless you reassign x
to be 0
, the while loop won't happen, and product
will always equal 1
.
Finally:
#output both values of sum and product
print(sum, product)
If this was your own code, try this instead for more correct output.
#to start with, a number variable is assigned to x, and to sum
x=1 #This holds our counter
sum=0 #this holds the result
#Then, a loop is run through while x is less than 10.
while x<10:
#show working
print(sum," ",x,"=",sum x)
sum =x #the variable x is added to sum
x =1 #x is incremented
#Assign product to be 1
product=1
#NOTE: x is reassigned for a working while loop next time
x=1
#loop while x is less than 10
while x<10:
print(product,"×",x,"=",product*x)
#multiply product by x
product= product*x
#increment x
x =1
#output both values of sum and product
print(sum, product)
Ta-da