第三章 基本语法
第三章 基本语法
相关代码如下
age = 22
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
print("All done!")
name = " "
if not name.strip(): # 移除字符串开头多余内容,默认空格
print("Name is empty")
if 18 <= age < 65:
print("Eligible")
else:
message = "Not eligible"
# python可以写 18 <=age < 65
message = "Eligible" if age >= 18 else "Not eligible"
print(message)
# for x in "Python":
# print(x)
# for x in ['a', 'b', 'c']:
# print(x)
# ctrl + / 可将选中的代码注释
# for x in range(0,10,2): # range()函数遍历数字,包括0,不包括10,每个遍历数字相隔2
# print(x)
print(type(range(5)))
print([1, 2, 3, 4, 5])
# range()函数返回的是range类而不是列表,并且所占用的内存比列表小得多
names = ["AJohn", "Mary"]
for name in names:
if name.startswith("J"): # startwith()函数可用于检验数组等的第一个内容
print("Found")
break
else:
print("Not found")
# for-else语句,在for语句遍历之后无break,则运行else语句
guess = 0
answer = 5
while answer != guess:
guess = int(input("Guess:"))
else:
pass
# while-else语句
输出内容
Adult
All done!
Name is empty
Eligible
Eligible
<class 'range'>
[1, 2, 3, 4, 5]
Not found
Guess: