Python beginners self ---- cycle

Self-learning record: If you have questions, please help correct me, do not spray.

Calculate 1 + 2 + 3 + 4, we can write the expression directly

print(1+2+3+4)

But if the numbers more, it will be very tired

python cycle, there are two, one is for x in ... cycle, followed by the list or tuple elements inside out iterations, such as

names=('Sam','Max','Leo')
for name in names:
print(name)

This code is executed, and then click Print on the names of each element

So for x in ... cycle each element is assigned to the variable x, and then do indented block of statements

We try and calculate 1-10 integers can be done with a cumulative sum variable

sum = 0
for x in (1,2,3,4,5,6,7,8,9,10):
sum =sum + x
print(sum)

If you want to calculate an integer from 1 to 100 or more and a digital input will be very difficult,

There is a 'range' function in python, can generate a sequence of integers, and then converted by the list 'list' function

print(list(range(100)))

The second loop is the while loop, as long as the conditions are met, the cycle can continue, otherwise exit the loop, such as computing and the odd-numbered less than 100

sum = 0
n = 99

while n > 0:
sum = sum +n
n = n - 2
print(sum)

0 = SUM
n-99 =
the while n-> 0:
BREAK
SUM = SUM + n-
n-n-= - 2
Print (SUM, 'out of the current cycle BREAK')

break out of the current cycle

sum = 2
n = 99
s = 100
while n > 0:

continue out of the current round of cycle, the cycle is not executed behind the current round of operation, directly into the next cycle.

sum = sum +n
n = n - 2
continue
s = 0

print('%d %d %d'%(sum,s,n))

Exercise: 0-100 integer and calculated, but not 50-60 integer calculations.

Method a: an integer of 0-50 and calculation, and then calculates the integer, the sum of both 60-100.

n = 0
sum = 0
res = 0
while (n <=50):
res = (res+ n )
n = n + 1
print(res)
n=60
while (n<=100):
sum = (sum + n)
n = n + 1
sum=sum+res
print(sum)

Method two: an integer of 0-100 and first calculate, by subtracting the integer and 50-60.

n = 0
sum =0
res = 0
while n<=100:
sum = (sum +n)
n = n + 1
print(sum)
print(n)
n = 51
while n >50 and n <60:
res = (res + n)
n = n + 1
print(res)
print(sum - res)

Method three:

n=0
sum=0
res=0
while n<=100:
if n <= 50:
res=(res + n)
n=n+1
elif (n>50 and n<60) :
n=n+1
continue
else :
sum=sum+n
n=n+1
print(res)
print(sum+res)

**

Guess you like

Origin blog.51cto.com/13184683/2440121