学习时间:20200204
学习资源:bilibili链接
布尔量
is_hot = False #布尔量
is_cold = True #布尔量
if is_hot: #is_hot为真时条件成立
print("it's a hot day")
print("drink plent of water")
elif is_cold:
print("it's a cold day")
print("wear warm clothes")
else:
print("it's a lovely day")
运行结果为:
it's a cold day
wear warm clothes
enjoy your day
while循环
基本结构为
while 条件:
语句
即条件满足执行语句。
接下来给出一个程序看看自己能不能看懂。
secret_number = 9
guess_limit = 3
guess_count = 0
while guess_count <guess_limit:
guess = int(input("Guess:"))
guess_count += 1
if guess == secret_number:
print("you win!")
break
else:
print("sorry,you failed!")
综合练习
1.让用户输入一个体重,并让用户选择单位是磅还是千克,最后将用户的体重输出。
weight = int(input("weight: "))
unit = input("(L)bs or (k)g: ")
if unit.upper() == "L":
converted = weight * 0.45
print(f"your weight is {converted} (L)bs")
else:
converted = weight / 0.45
print(f"your weight is {converted} (k)g")
运行结果:
weight: 160
(L)bs or (k)g: l
your weight is 72.0 (L)bs
2.启动,停止车以及退出游戏。
command = ""
started = False
while True:
command = input(">").lower()
if command == "help":
print('''
start--to start the car
stop--to stop the car
quit--to quit the car
''')
elif command == "start":
if started == True:
print("the car already started")
else:
started = True
print("the car started ......")
elif command == "stop":
if not started:
print("the car already stopped")
else:
started = False
print("the car stopped ")
elif command == "quit":
break
else:
print("i don't understand that ")
运行结果:
>stop
the car already stopped
>start
the car started ......
>start
the car already started
>stop
the car stopped
>stop
the car already stopped
>quit
for loop循环
基本结构为
for item in "python":
print(item)
方括号定义列表,遍历的时候一个项目一个项目来。
[“mosh”,“john”,“sarah”]
定义数字列表用rang(start,stop,step)函数
嵌套循环
for x in range(4):
for y in range(4):
print(f"({x},{y})")
输出F
numbers = [5,2,5,2,2]
for x_count in numbers:
output = ''
for x in range(x_count):
output += 'x'
print(output)