Python learning while loop exercises

Since the rise of Python in China in the past two years, it has attracted the attention of many friends in the IT industry, and the number of friends who started to learn Python has gradually increased. However, when I was studying, I found that the first place in the loop began to silently test the logical thinking. Let’s do a few more practice questions to sort out and review it.

 

1.  Use while loop to output 1 2 3 4 5 6 8 9 10

method one:

count=1

while count <= 10:

  if count == 7:

     count+=1

     continue

  print(count)

     count+=1

    

Method Two:

count=1

while count <= 10:

  if count != 7:

      print(count)

  count+=1

    

 

2.  Find the sum of all numbers from 1 to 100 

sum=0

count=1

while count <= 100:

  sum+=count

  count+=1

print(sum)

 

 

3.  Output  all odd numbers from 1-100

count=1

while count <= 100:

  if count%2 != 0:

      print(count)

  count+=1

 

 

4.  Output  all even numbers within 1-100

count=1

while count <= 100:

  if count%2 == 0:

      print(count)

  count+=1

 

 

5.  Find the sum of all numbers 1-2+3-4+5 ... 99

sum=0

count=1

while count <= 99:

  if count%2 == 0:

     sum-=count

  else:

     sum+=count

  count+=1

print(sum)

 

 

6.  User login (three chances to retry) 

count=0

while count < 3:

  name=input('请输入用户名:')

  password=input('请输入密码:')

  if name == 'oldboy' and password == '123':

      print('login success')

      break

  else:

      print('用户名或者密码错误')

      count+=1

 

 

7:猜年龄游戏

要求:

允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出

age_of_oldboy=65

count=0

while count < 3:

  guess=int(input('>>: '))

  if guess == age_of_oldboy:

      print('you got it')

      break

  count+=1

 

 

8:猜年龄游戏升级版 

要求:

  允许用户最多尝试3次

  每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序。如何猜对了,就直接退出。

age_of_oldboy=73

count=0

while True:

  if count == 3:

      choice=input('继续(Y/N?)>>: ')

      if choice == 'Y' or choice == 'y':

          count=0

      else:

          break

 

  guess=int(input('>>: '))

  if guess == age_of_oldboy:

      print('you got it')

      break

  count+=1

 

 

初次做练习题的时候,也是感觉逻辑上转不过来,但是经过一步一步的梳理,看步骤之后再加之理解的话,有种柳暗花明的感觉啊。学习开始总是艰难的,尤其是没有接触过IT这个行业的朋友,但是,坚持是个很可怕的东西,每天坚持2到3小时,并且要讲究效率,学习效果也是不错的。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326121881&siteId=291194637
Recommended