1.案例

1.猜数字3次,检验是否与提前设置的secret_number一致

guess_count = 0
guess_limit = 3
secret_number = 9 while guess_count < guess_limit: guess = int ( input ( 'Guess: ')) guess_count += 1 if guess ==secret_number: print(' You won ! 'break else: print (' Sorry, you failed! ')

2.对汽车输入一些指令(无需分辨大小写):

start——Car started...

stop——Car stopped.

help

且根据汽车当前状态提醒用户不要重复操作

command = ""
started = False#用布尔值判断当前状态
while Ture:
         command = input (">").lower()#小写化,输入的大小写不影响
          if command == “start”:
             if started:
                 print(“Car is already started!”)
             else:
                    started = Ture
                    print("Car started...")
           elif command == "stop"
                 if not started:
                    print("Car is already stopped!")
                 print("Car stopped.")
            elif command == “help”:
                 print'''
start - to start the car
stop - to stop the car
quit - to quit
'''elif command == "quit"
                  break
            else:
                   print("Sorry I don't understand that!")

3.用for循环求和

prices = [10,20,30]

prices = [10, 20 ,30]
total_prices = 0
for item in prices:
     total_prices += item
print(“total_prices: ” total_prices)
12-20 10:20
查看更多