逻辑判断的短路原则:
条件1 and 条件2,如果条件1为假则表达式为假,第二个条件不会去计算。
条件1 or 条件2,如果条件1为真则表达式为真,第二个条件不会去计算。
循环语句:
1 while 条件: 2 3 print(“any”) 4 5 print(“any”)
在python中存在这样的用法:
while 条件:
,,,,,,,,
else :
,,,,,,,,
else只会在while循环正常结束后才会执行(break跳出循环,else语句不执行。continue会执行)
循环嵌套:
1 num1 = 0 2 3 while num1 <= 5: 4 print(num1,end="_") 5 num2 = 0 6 while num2 <= 7: 7 print(num2,end="-") 8 num2 + =1 9 num1 + =1 10 print(end=" ")
例子循环输出1到100:
1 num = 1 2 3 while num<=10: 4 5 print ("num") 6 7 num + = 1
例子:输出1到100之间的偶数
1 num = 2 2 3 while num<=100: 4 5 if num %2 = 0: 6 7 print ("num") 8 9 num + = 2
猜年龄:
1 age = 50 2 user_input_age = int(input("age=")) 3 flag = 1 4 while flag != 0: 5 if user_input_age == age: 6 print("yes") 7 flag = 0 8 elif user_input_age > age: 9 print("is bigger") 10 user_input_age = int(input("age=")) 11 else: 12 print("is smaller") 13 user_input_age = int(input("age=")) 14 print("end")
改进:(利用break语句)
1 age = 50 2 user_input_age = int(input("age=")) 3 flag = 1 4 while flag == 1: 5 if user_input_age == age: 6 print("yes") 7 break 8 elif user_input_age > age: 9 print("is bigger") 10 user_input_age = int(input("age=")) 11 else: 12 print("is smaller") 13 user_input_age = int(input("age=")) 14 print("end")
如何让三行输出语句输出在一行:
print("hellow world",end="_")
输出:
hellow world_
#print是默认换行,加上end意思是本语句以end="x"中的x结尾
print() 等价于 print(end=" ")
例题:输出长宽指定的矩形
1 Height = int(input("Height:"))#用户输入高度 2 3 width = int(input(""))#用户输入宽度 4 5 num_height = 1 6 7 while num_height <= Height: 8 9 num_width = 1 10 11 while num_width <= 12 13 print("#",end=" ") 14 15 num_width +=1 16 17 print() 18 19 num_height += 1
输出99乘法表:
1 first = 1 2 while first <=9: 3 sec = 1 4 while sec<= first: 5 print(str(sec)+"*"+str(first)+"="+str(sec*first),end=" ")) 6 sec +=1 7 print() 8 first += 1