标签:
Python中条件选择语句的关键字为:if 、elif 、else这三个。其基本形式如下:
age_of_cc = 27 age = int(input("guessage:")) if age == age_of_cc: print("Yes,you got it!") elif age > age_of_cc: print("猜大啦!") else: print("猜小啦!")
if语句执行的特点是从上往下判断;
其中elif和else语句块是可选的。对于if和elif只有判断为True时,该分支语句才执行,只有当if和所有的elif的判断都为False时,才执行else分支。注意Python中条件选择语句中判断后面有个冒号。
用法:
while 条件: xxxxxx
while会不停地循环执行隶属于它的语句,直到条件为假(False)
代码示例:
age_of_cc = 27 count =0 while count < 3: age = int(input("guessage:")) if age == age_of_cc: print("Yes,you got it!") break elif age > age_of_cc: print("猜大啦!") else: print("猜小啦!") count += 1 else: if count == 3: print("错误太多次啦!")
代码示例:
i = 1 while i < 10: i += 1 if i%2 > 0: # 非双数时跳过输出 continue print(i) # 输出双数2、4、6、8、10
for循环需要预先设定好循环的次数(n),然后执行隶属于for的语句n次。
代码示例:
for i in range(10): print(i) #输出0 1 2 3 4 5 6 7 8 9
while循环判断语句代码示例:
age_of_cc = 27 count =0 while count < 3: age = int(input("guessage:")) if age == age_of_cc: print("Yes,you got it!") break elif age > age_of_cc: print("猜大啦!") else: print("猜小啦!") count += 1 else: if count == 3: print("错误太多次啦!")
for条件判断代码示例:
age_of_cc = 27 count = 0 for i in range(3): age = int(input("guessage:")) if age == age_of_cc: print("Yes,you got it!") break elif age > age_of_cc: print("猜大啦!") else: print("猜小啦!") count += 1 else: if count == 3: print("错误太多次啦!")
input是输入函数,用户可以输入字符串保存到变量中
代码示例:
name = input("Please input your name")
用print()在括号中加上字符串,就可以向屏幕上输出指定的文字
代码示例:
print("Hello!")
通过上文可以看出,input输入的在python中都会被认为是字符串(见下图),所以我们需要对input的内容进行类型转换:
转换成int示例:
age = int(input("age is:"))
转换回字符串:str()
标签:
原文地址:http://www.cnblogs.com/cocc/p/5700639.html