Python's range() function and for loop statement

Posted by synking on Sun, 03 Nov 2019 19:34:29 +0100

range( )

Built in python functions
range(stop):0~stop-1
range(start,stop):start~stop-1
range(start,stop,step):start~stop-1 step: step

range(7)
[0, 1, 2, 3, 4, 5, 6]
range(1,5)
[1, 2, 3, 4]
range(1,11,2)
[1, 3, 5, 7, 9]
range(2,11,2)
[2, 4, 6, 8, 10]

FOR loop statement

Syntax for recycling:

for variable in range():
    Code to be executed by loop
else:
    Code to execute at the end of all loops

for... In loop, iterating each element in the list or tuple in turn,

names = ['tony', 'lucy', 'tom']
for name in names:
print (name)
tony
lucy
tom

Calculate the sum of integers of 1 - ­ 10

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

Calculate the sum of integers of 1 - ­ 100

sum = 0
for x in range(101):
sum = sum + x
print (sum)

Find the odd sum of 1-100

sum = 0
for x in range(1,101,2):
sum += x
print(sum)

Find the even sum of 1-100

sum = 0
for i in range(2,101,2):
sum +=i
print(sum)

The user enters a number and finds the factorial of the number: 3! =321

num = int(input('Num:'))
res = 1
for i in range(1,num+1):
res = res * i
print('%d The result of the factorial of is:%d' %(num,res))

User login program, three opportunities (user name = root, password = mima)

1. Enter user name and password
2. Judge whether the user name and password are correct
3. In order to prevent violent cracking, there are only three times of landing. If there are more than three opportunities, an error is reported

 print('welcome back!!')
 for i in range(1,4):
     name=input('Please enter the user name:')
     secret=input('Please input a password:')
     if (name=='root' and secret=='mima'):
         print('successful')
         break
     else:
         print('you only have %d chance' %(3-i))
else:
     print('defeat')

Implementation of command line prompt

import os
#1000 in order to show a near dead cycle
for i in range(1000):
    cmd =input('[jing.station]')
    if cmd:
        if cmd=='exit':
            print('logout')
            break
        else :
            print('run %s' %(cmd))
            #Run shell command
            os.system(cmd)
    else:
        continue

Topics: Python shell