1. Using while loop output 1 2 3 4 5 6 8 9 10
# !/usr/bin/env python # -*-encoding:utf-8-*- = 1 while n <=: if n = = 7: pass# instead of continue, because will skip this cycle, n can not +1,n forever ==7, never skip this cycle. Else: print(n) + = 1 # Print (' WSS ', n)
View Code
# !/usr/bin/env python # -*-encoding:utf-8-*- = 0 while n <= 9: + = 1 if n = = 7: pass
# Change to continue can, because although jumped out of this cycle, but the next time the loop n can be +1 Else: Print(n)
View Code2. For all numbers of 1-100
# !/usr/bin/env python # -*-encoding:utf-8-*- #S is the sum of all previous numbers while n <=: + = 1 + = N # print (s) #输出每次循环的总和 print# output final sum
View Code
# !/usr/bin/env python # -*-encoding:utf-8-*- = 0 for in range (1,101): # print (n) s + = N Print (s)
View Code3. All odd numbers in output 1-100
# !/usr/bin/env python # -*-encoding:utf-8-*- = 0 while n <= :+ = 1 if n% 2 = =1 : Print(n)
View Code
# !/usr/bin/env python # -*-encoding:utf-8-*- for in range (1,101,2): print(n)
View Code4. All even numbers in output 1-100
# !/usr/bin/env python # -*-encoding:utf-8-*- = 0 while n <= :+ = 1 if n% 2 = = 0 : Print(n)
View Code
# !/usr/bin/env python # -*-encoding:utf-8-*- for in range (2,101,2): print(n)
View Code5, Beg 1-2+3-4+5 ... 99 of all numbers of the and
# !/usr/bin/env python # -*-encoding:utf-8-*- = 0;s = 0 while n <= 98: + = 1 if n% 2 = = 0: -=
N
else
: +
= n
#
print (s) #输出每次循环运算的结果
print
#
Output final result of Operation
View Code
# !/usr/bin/env python # -*-encoding:utf-8-*- = 0 for in range (1,100): # print (n) if n% 2 = = 0 :-= nelse: + = N Print(s)
View Code6. User Login (three chance retry)
#!/usr/bin/env python#-*-Encoding:utf8-*-ImportGetpasscount=0 whileCount < 3: User= Input ('Please enter user name:') PWD= Getpass.getpass ('Please enter your password:') ifuser = ='WSS' andPWD = ='123': Print('Welcome to login') Print('..........') Break Else: Print('incorrect user name or password') Count+ = 1
View Code
#!/usr/bin/env python#-*-encoding:utf-8-*-ImportGetpassusername='WSS'Password='123'Flag=0deflogin (): User= Input ('Username:') passwd= Getpass.getpass ('Password:') returnUser,password whileFlag<3: user,passwd=Login ()ifUsername = = User andPassword = =passwd:Print('Hello,jason') Break Else: Flag+ = 1Print('Error,input again')
View Code
Python exercises (basic knowledge exercises (i))