千家信息网

python之路-基础篇2

发表于:2024-12-01 作者:千家信息网编辑
千家信息网最后更新 2024年12月01日,10、if else 流程判断举例说明1:import getpass #引用getpass这个模块_username = "kk"_password = "123456"username = in
千家信息网最后更新 2024年12月01日python之路-基础篇2

10、if else 流程判断

举例说明1:

import getpass  #引用getpass这个模块_username = "kk"_password = "123456"username = input("username:")password = getpass.getpass("password") #getpass功能是让密码不直接显示成明文if _username == username and _password == password:    print("Welcome user {name} login...".format(name = username))#print("Welcome user %s login..." % username)else:    print("error")

注:缩进功能:子代码需要缩进

举例说明2:

#猜年龄age_of_oldboy = 65guess_age = int(input("guess age:"))if guess_age == age_of_oldboy:  print("Yes, you got it.")elif guess_age > age_of_oldboy:  print("No, think bigger!")else:  print("No,think smaller!")

11、while循环

举例说明1:

#死循环count = 0while  True:    print ("count",count)  count = count + 1


举例说明2:

age_of_oldboy = 65 count = 0 #设置计数while count < 3:#如果小于3次时循环执行    #if count == 3:    #break    guess_age = int(input("guess age:"))  if guess_age == age_of_oldboy:    print("Yes, you got it.")    break  elif guess_age > age_of_oldboy:    print("No, think bigger!")  else:    print("No,think smaller!")  count += 1else:    print("Funk off")

举例说明3:

#循环猜年龄,结束提示是否继续猜

age_of_oldboy = 65count = 0while count < 3:#       if count == 3:#               break        guess_age = int(input("guess age:"))        if guess_age == age_of_oldboy:                print("Yes, you got it.")                break        elif guess_age > age_of_oldboy:                print("No, think bigger!")        else:                print("No,think smaller!")        count += 1        if count == 3:#猜了三次还没有猜到询问用户是否要继续猜                coutine_confim = input("do you want to keep guessing?:")                if coutine_confim != "n":                        count = 0#else:#这个就用不到了#       print("Funk off")


注:

continue:跳出本次循环,继续到下次循环

break:结束整个循环



12、for循环

举例说明1:

#for循环for i in range(10):    print("loop ", i)


答案:C:\Users\Documents\python>python learn01.pyloop  0loop  1loop  2loop  3loop  4loop  5loop  6loop  7loop  8loop  9


举例说明2:

#循环猜年龄

age_of_oldboy = 65for i in range(3):    guess_age = int(input("guess age:"))    if guess_age == age_of_oldboy:        print("Yes, you got it.")        break    elif guess_age > age_of_oldboy:        print("No, think bigger!")    else:        print("No,think smaller!")else:    print("Funk off")


举例说明3:

for i in range(0,10,2):    print("loop ",i)


举例说明4:

#大循环i执行1次,小循环执行10次for i in range(10):        print('-----------',i)        for j in range(10):                print (j)                if j > 5:#小循环大于5就停止                        break



0