python流程控制跟其他语言一样,主要有if else elif,语法相当简单。
一、if else 学习:
_username = "chenbin"
_password = "chenbin"
username = input("username:")
password = input("password:")
if _username == username and _password == password:
print("Welcome user {name} login...".format(name = username))
else:
print("Invalid username or password")
猜数字小游戏:输入的年龄大于指定的年龄,提示猜大了,反之亦然,在python3里input输入的是str类型的,如果跟int类型相比较,需要类型转换:int(input("age"x))。
age_of_oldbody = 56
gusee_age = int(input("guess age:"))
if age_of_oldbody == gusee_age:
print("yes,you got it...")
elif gusee_age > age_of_oldbody:
print("think smaller...")
else:
print("think bigger!")
二、while循环:
count = 0
while True:
print("count:" + count)
count = count + 1
猜数字小游戏只能猜三次,如果三次内没猜对,直接结束程序;
age_of_oldbody = 56
count = 0
while True:
if count == 3:
break
age = int(input("age:"))
if age_of_oldbody == age:
print("ok!")
break
elif age > age_of_oldbody:
print("bigger!")
else:
print("smaller!")
count+=1
优化后的猜数字小游戏代码:
age_of_oldbody = 56
count = 0
while count < 3:
age = int(input("age:"))
if age_of_oldbody == age:
print("ok!")
break
elif age > age_of_oldbody:
print("bigger!")
else:
print("smaller!")
count+=1
else:
print("fuck off...")
三、for循环实现猜数字小游戏:
age_of_oldbody = 56
for i in range(3):
guess_age = int(input("age:"))
if age_of_oldbody == guess_age:
print("ok!")
break
elif guess_age > age_of_oldbody:
print("bigger!")
else:
print("smaller!")
else:
print("guck off!")
使用for循环打印奇偶数,之前使用别的语言打印奇偶数,判断是否能被2整数打印,现在使用python语言,使用步长直接打印,代码如下:
for i in range(0,10,2):
print("loop i is:",i)
loop i is: 0
loop i is: 2
loop i is: 4
loop i is: 6
loop i is: 8
猜数字小游戏进一步优化,如果在三次之内都没有才对,问是否继续猜,如果继续猜,重置计数器,反之结束程序,代码如下:
count = 0
age_oldbody = 56
while True:
guess_age = int(input("age:"))
if guess_age == age_oldbody:
print("ok!")
break
elif guess_age > age_oldbody:
print("bigger!")
else:
print("smaller!")
count+=1
if count == 3:
continue_confirm = input("do you want to keep guessing..?")
if continue_confirm != 'n':
count = 0
#else:
# print("fuck off!")
四、总结:
python的循环相当简单,根据自己的业务场景选择合适的循环处理,这里说明一下break和continue的区别,break结束循环操作,continue结束本次循环执行下一次循环操作,本篇文字简单明了,仅供初学者学习入门。