Python Programming Practice-SWAPPING

Created with Sketch.

Python Programming Practice-SWAPPING

Example 1 This program will add up the numbers from 1 to 100. The way this works is that each time we encounter a new number, we add it to our running total, s .

s = 0
for i in range (1,101):
s = s + i
print ( ' The sum is ' , s)


Example 2 This program that will ask the user for 10 numbers and then computes their average.

s = 0for i in range (10):num = eval ( input ( ' Enter a number: ' ))
 s = s + num
print ( ' The average is ' , s/10)


Example 3 A common use for summing is keeping score in a game. Near the beginning of the game we would set the score variable equal to 0. Then when we want to add to the score we would do something like below:

score = score + 10


Quite often we will want to swap the values of two variables, x and y . It would be tempting to try the following:

x = y y = x

But this will not work. Suppose x is 3 and y is 5. The first line will set x to 5, which is good, but then the second line will set y to 5 also because x is now 5. The trick is to use a third variable to save the value of x :

hold = x x = y

y = hold

In many programming languages, this is the usual way to swap variables. Python, however, pro- vides a nice shortcut:

x,y = y,x

We will learn later exactly why this works. For now, feel free to use whichever method you prefer. The latter method, however, has the advantage of being shorter and easier to understand.

Leave a Reply

Your email address will not be published. Required fields are marked *