⑤python 用户密码密文、 if else流程判断、while循环、for循环

一、用户密码密文

import getpass  
username = input("username:")
password = getpass.getpass("password:")
print(username,password)

getpass在pycharm中无法使用,在命令行窗口中进入python环境可以使用

C:Userspeng>python3
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import getpass
>>> username = input("username:")
username:peng
>>> password = getpass.getpass("password:")
password:
>>> print(username,password)
peng 123456
>>>

二、if else基础程序举例:

实例1:判断用户名密码是否正确

_username = 'peng'
_password = '123456'

username = input("username:")
password = input("password:")
print(username,password)

if _username==username and _password==password:
    print("Welcome user {name} login...".format(name=username))
else:
    print("Invalid username or password!")

实例2:猜年龄

age_of_oldboy = 56
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy :
    print("yes, you got it.")
    guess_age = int(input("guess age:"))
elif guess_age > age_of_oldboy: #如果情况大于两种

print("think smaller...")
else: print("think bigger!")

三、while循环

#最简单的while循环程序举例
count = 0
while True:
    print("count:",count)
    count = count+1 #相当于count +=1

实例1:猜年龄

#猜不对一直猜,猜对停止
age_of_oldboy = 56
while True:
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy :
print("yes, you got it.")
break #猜对停止
guess_age = int(input("guess age:"))
elif guess_age > age_of_oldboy:
print("think smaller...")
else:
print("think bigger!")

实例2:猜年龄,猜错3次,提示是否继续,猜对停止

age_of_oldboy = 56
count =0
while count <3 :
    guess_age = int(input("guess age:"))

    if guess_age == age_of_oldboy :
        print("yes, you got it.")
        break
        guess_age = int(input("guess age:"))
    elif guess_age > age_of_oldboy:
        print("think smaller...")
    else:
        print("think bigger!")
        count +=1
    if count == 3:
        continue_confirm = input("do you want to keep guessing..?")
        if continue_confirm !='n':
            count = 0

四、for循环

实例1:最简单的for循环程序

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

相当于

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

i,临时变量

range(num),相当于定义了【0,num】的数字

实例2:隔一个数字打一个:

for i in range(0,10,2): #2为步长
    print("loop",i)

实例2:猜年龄

age_of_oldboy = 56

for i in range(3):
    guess_age = int(input("guess age:"))
    if guess_age == age_of_oldboy:
        print("you got it!")
        break
    elif guess_age < age_of_oldboy:
        print("think bigger...")
    else:
        print("think smaller...")

else:
    print("you have tried too many times...")
原文地址:https://www.cnblogs.com/pengp/p/6561549.html