----------------------------------if else------------------------------
1.最基本的if语句:
if name =="Alex":#注意缩进
print("so handsome")#可以结束,没问题.
#继续加条件:
elif name =="oldboy":
print("too old")
else:#代表上面的条件都不成立走这个
print"goodboy!"
2.猜年龄:
oldboy_age = 39
guess_age =int(input("age:"))#str--->int
print(type(guess_age))
if guess_age ==oldboy_age:
print("correct!!")
elif guess_age > oldboy_age:#else if
print("try smaller!!")
else:
print("try bigger!!")
3.猜成绩:
score = int(input("输入你的成绩:"))
if score >100:
print("滚")
elif score == 100:
print("A+")
elif score >=80:
print("B")
elif score >=60:
print("C")
elif score >=40:
print("C-")
else:
print("D")
if----else----只走一个逻辑,从上到下!
-------------------------------for--------------------------------
1.最简单的for循环
for i in range (10):#这句话的意思就是我要去循环这一组数据[0,1,2,3,4,5,6,7,8,9]这组数据中循环,每循环一次就拿出一个值来打印
#range其实就是一组数据 print(i)
#i就相当于一个临
2.猜年龄
2.1 break 猜对了及时跳出循环
2.2 3次结束以后失败了!不能打印最后一句"Welcome to 2 level!"
2.3 只有猜对了,才能打印这句话
2.4怎么退出程序?exit()
2.5 怎么使用for---else,
oldboy_age = 39
for i in range (3):-------------------------------for下面的内容都会循环.
guess_age =int(input("age:"))#str--->int
print(type(guess_age))
if guess_age ==oldboy_age:
print("correct!!")
break-------------------------------------猜对了就跳出循环!
elif guess_age > oldboy_age:#else if
print("try smaller!!")
else:
print("try bigger!!")
else:#如果for循环正常结束,中间没有被break,代表猜错了.上面不成立!
exit("too many attempts!")
print ("welcome to 2 level!")
3.嵌套循环:
3.1简单嵌套:
for i in range (10):
for j in range (10):
print(i,j)
3.2 j >5:
for i in range (10):
for j in range (10):
print(i,j) #先打印后判断,打印出来会有6,除非把这个写在if后面就没有6
if j>5:
break#-------------只是跳出当前循环;
3.3 j<5,不打印,j>5,才打印------continue
for i in range (10):
for j in range (10):
if j<5:----------------大循环走了10次,小循环没走,直接跳出
break ----------------直接跳整个当前层循环,什么都没打印
print(i,j)
不能用break,用continue
for i in range (10):
for j in range (10):
if j<5:
continue
print(i,j)
4.用户登陆:
user = "gaojun"
password ="123abc"
for i in range(3):
user = input('请输入用户名:')
password = input('请输入密码:')
if user == "gaojun" and password =="123abc":
print("欢迎!gaojun!")
break
else:
print("用户或密码错误!")
else:
print("输入次数到达3次,请稍后再试!")
-------------------------while--------------------------
1.最简单的while循环:
count = 0#定义count变量,为了让你看到循环了多少次
while True:#条件为真,True永远为真
print("you are a good boy!",count)
count +=1
2.上面的例子,跳出死循环:
count = 0
while True:
if count = 1000000
print("you are a good boy!",count)
break
count +=1
3.其他办法施行运行100次就退出;
count = 0
while count<100:
print("you are a good boy!",count)
count +=1
4.猜年龄----
4.1输入空值会报错怎么解决?isdigit
4.2怎么限制次数 count<3 count+=1
count = 0
oldboy_age = 56
while count <3:
guess_age =input("gae>>:")
if guess_age.isdigit():
guess_age = int(guess_age)
else:
continue
if guess_age == oldboy_age:
print("猜对了!")
break
elif guess_age >oldboy_age:
print("往小里猜!")
else:
print("往大猜!")
count+=1