自学 python 的第三天

  Good midnight!!!

  直接进入正餐吧(大晚上的, 好饿啊!), 以后就不嘘寒问暖的了.

  昨天结尾时写到了 breakcontinue 的两个终止循环.只写了 break 的例子.

  接下来写下 continue 的例子.

 一.

  1.用循环输出1, 2, 3, 4, 5, 6, 8, 9

     1`

count = 1
while count < 10:
    if count != 7:
        print(count)
    count += 1

    如下打印结果:

1
2
3
4
5
6
8
9

   2` continue 的方法

count = 1
while count < 10:
    if count == 7:
        count += 1   #或者 count = 8, 就不用写 continue 了
        continue
    print(count)
    count += 1

  2.计算 1- 2+ 3- 4+ 5- 6+......+99 = ?

sum = 0
count = 1
while count < 100:
    if count % 2 == 0:        #偶数
        sum = sum - count
    else:
        sum = sum + count     #奇数
    count += 1
print(sum)

    打印结果: -50

  3.用户登入:

count = 1
while count <= 3:
    username = input("Enter your name:")   #输入你的名字
    password = input("Enter your password:")   #输入你的密码
  if username == 'Jason' and
password == '123': print("Hello,sir!\nNice to meet you!") break else: print("Login failed!") print("You've got %d more chances!" % (3 - count)) #只有三次机会 count += 1 #计数 else: print("Who are you?\nI need to confirm with Mr. Jason!") #三次错误跳出函数

  4.请输入广告:

ad = input("Please enter advertisement:")
if '' in ad or '国家' in ad or '第一' in ad or '稀缺' in ad:   #有不合法的字,则不打印
    print("Illegal Or Illegally")
else:
    print("Illegal")

  5.猜字游戏:

    1`

n = 88
while True: num = input("You guess:") if int(num) > n: print("Can you guess what big!") elif int(num) < n: print("Can you guess what small!") else: print("You got it!") break

    2`优化版(限次数)

count = 1
n = 88
while count <= 3:
    num = input("You guess:")
    if int(num) > n:
        print("Can you guess what big!")
    elif int(num) < n:
        print("Can you guess what small!")
    else:
        print("You got it!")
        break
    #没猜对
    print("You've guessed it %d times!" % count)   # %d : 数字占位符
count += 1 else: print("You are so stupid!\nBey!")

    知识点:

       %d : 数字占位符

       %s : 字符串的占位符,也可以为任何内容(数字)

  6.用户无限输入, 但输入 out 则退出

while True:
    P = input("Please start to spray:")
    if P == 'Out':
        break
    if "Json" in P:     #"in"在xxx中出现了xxx
        print("Your input is illegal and cannot be exported!")
        continue       #停止本次循环,执行下一次循环
    print("The spray is:"+P)

   二.

  1.逻辑运算

      and : 并且的意思, and 左右两边的值必须为真,其运算结果才为真

     or : 或者的意思, or 左右两边有一个(全部)为真(假),其结果为真(假).

      not : 非真既假,非假既真

明天见!!!......2018-10-26............

猜你喜欢

转载自www.cnblogs.com/Zhi-Yan/p/9856132.html