>>> age = input("How old are you? ") How old are you? 21 >>> age >= 18 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: str() >= int()
为解决这个问题可以使用 int() 函数,将数字字符串转换为数值:
1 2 3 4 5
>>> age = input("How old are you? ") How old are you? 21 >>> age = int(age) >>> age >= 18 True
下是个实际的应用:
1 2 3 4 5 6 7
height = input("How tall are you, in inches? ") height = int(height)
if height >= 36: print("\nYou're tall enough to ride!") else: print("\nYou'll be able to ride when you're a little older.")
7.1.3 求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:
1 2 3 4 5 6 7 8
>>> 4 % 3 1 >>> 5 % 3 2 >>> 6 % 3 0 >>> 7 % 3 1
偶数都能被2整除,通过这个区判断奇数与偶数:
1 2 3 4 5 6 7
number = input("Enter a number, and I'll tell you if it's even or odd: ") number = int(number)
if number % 2 == 0: print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd.")
prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" while message != 'quit': message = input(prompt) # 防止把 quit 当正常信息打印出来 if message != 'quit': print(message)
7.2.3 使用标志
1 2 3 4 5 6 7 8 9 10 11
prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. "
active = True while active: message = input(prompt)
if message == 'quit': active = False else: print(message)
7.2.4 使用 break 退出循环
1 2 3 4 5 6 7 8 9
prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) " whileTrue: city = input(prompt)
if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")
7.2.5 在循环中使用 continue
1 2 3 4 5 6 7
current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue
print(current_number)
7.2.6 避免无限循环
1 2 3 4 5 6 7 8 9
x = 1 while x <= 5: print(x) x += 1 # 这个循环将没完没了地运行! x = 1 while x <= 5: print(x)
7.3 使用 while 循环来处理列表和字典
在 for 循环中不应修改列表,否则将导致 Python 难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用 while 循环。