1. 猜数字
要求:
- 允许用户最多尝试3次;
- 每尝试3次后,如果还没猜对,询问用户是否还想继续玩,如果回答Y或者y,就继续让其猜3次,以此往复,如果回答N或n,就退出程序;
- 如果猜对了,就直接退出。
count = 0
girlfriend_num = 5
while True:
count += 1
guess_number_of_girlfriends = int(input("Number of girlfriends is: "))
if guess_number_of_girlfriends != girlfriend_num: # 判断猜测次数不等于5就继续猜测
print("猜错了!3次错误将询问是否继续,10次错误直接退出。")
if count % 3 == 0: # 每3次询问一次是否继续,通过余数判断。
print("是否继续,N/Y")
continue_to_guess = input("You want to keep guessing? (N/Y) ").upper() # 回答y或n决定是否继续,".upper()"将字符串中的小写字母转为大写字母,这样用户输入小写或者大写字母程序都可以识别
if continue_to_guess == "Y": # 等于y就继续猜测
continue
elif continue_to_guess == "N": # 等于n就退出
print("不继续猜测,即将退出。")
break
else: # 如果既不等于y也不等于n就退出,并输出输入错误。
print("输入错误,请输入N或者Y")
break
if guess_number_of_girlfriends == girlfriend_num: # 如果等于5输出回答正确,并退出程序。
print("恭喜你,猜对了。")
break
if count == 10: # 如果猜测次数超过指定的数量,输出猜测次数过多,并结束程序。
print("Guess too many times, is about to quit.")
break
2. 登录账号和密码
- 实现输入用户名和密码,当用户名为seventy或mark且密码为123456时,显示登录成功,否则登录失败!
user_one = "seventy".upper()
user_two = "mark".upper()
user_password = "123456"
username = input("Username: ").upper()
password = input("Password: ")
if username == user_one and password == user_password:
print("Login successful!")
elif username == user_two and password == user_password:
print("Login successful!")
else:
print("The user name or password is incorrect.")
- 实现输入用户名和密码,当用户名为seventy或mark且密码为123456时,显示登录成功,否则登录失败,失败是允许重试输入3次。
user_one = "seventy".upper()
user_two = "mark".upper()
user_password = "123456"
count = 0
while True:
count += 1
username = input("Username: ").upper()
password = input("Password: ")
if count <= 3:
if username == user_one and password == user_password:
print("Login successful!")
break
elif username == user_two and password == user_password:
print("Login successful!")
break
elif count == 3:
print("Login failed! Guess too many times, is about to quit.")
break
else:
print("Login failed! The user name or password is incorrect. Please try again.")
3. 使用while循环实现输出1,2,3,4,5, 7,8,9, 11,12
# 使用while循环实现输出1,2,3,4,5, 7,8,9, 11,12
count = 0 # 定义一个变量,初始值从0开始
while count <= 12:
count += 1
while count == 6 or count == 10: # 当遇到6或10跳出本次循环
count += 1
continue
if count == 5 or count == 9: # 当遇到5或9,以", "结尾
print(count, end=", ")
elif count < 12: # 12以内,除5和9,以","结尾
print(count, end=",")
elif count == 12: # 遇到12,无","结尾
print(count, end="")
# 输出结果
1,2,3,4,5, 7,8,9, 11,12
Process finished with exit code 0