Lesson 11
写代码当时候,避免不了的就是循环结构,如果到flag条件,则执行,如果到跳转条件,则跳转到另一个块继续执行。关键词:if,else,then。下面举一个if-then的例子[ipython 不能运行整个代码文件,所以没有输入输出的实验效果,建议在]:
# collect string / test length
input = raw_input("Please enter a test string: ")
if len(input)<6: #注意冒号和缩紧
print("Your string is really short.")
print("please enter a string with at least 6 characters")
将代码保存为python 文件if_then.py,使用命令行执行:
>>> python if_then.py
> Please enter a test string:ace # for example
Your string is too short.
Please enter a string with at least 6 characters.
> Please enter a test string:mission # this will return true, so no if.
下面我们开始一段新的代码:
# Prompt user to enter number / test if even or odd
input = raw_input("Please enter an integer:")
number = int(input)
if number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
将代码保存为python 文件if_then_2.py,使用命令行执行:
>>> python if_then_2.py
> Please enter an integer: 17
Your number is odd.
>>> python if_then_2.py
> Please enter an integer: 50
Yout number is even.
下面我们做一个小实验:三角形的判断。
# Scalene triangle: All sides have different lengths.
# Isosceles triangle: Two sides have the same length.
# Equilateral triangle: All sides are equal.
a = int(raw_input("The length of side a = "))
b = int(raw_input("The length of side b = "))
c = int(raw_input("The length of side c = "))
if a != b and b != c and a != c:
print("This is a scalene triangle.")
elif a == b and b == c: # elif = else if
print("This is an equilateral triangle.")
else:
print("This is an isosceles triangle.")
将代码保存为python 文件if_then_3.py,使用命令行执行:
>>> python if_then_3.py
> The length of side a = 3
> The length of side b = 4
> The length of side c = 5
This is a scalene triangle.
这个实验就是已知三条边的长度,判断三角型的类型:等边三角形,等腰三角形。if/then/else的这种循环结构,需要在实际使用中慢慢掌握。
Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-