Python语法基础03(输入与while)

用户输入

使用input()函数可以获取输入,同时应说清楚所期待的输入内容

#使用函数input时,要说清楚期望的输入
car=input("Please input your favourite car.\nAnd i will repeat:")
print(f"your favourite car is {car}")

##  也可以吧提示赋给变量
message="your favourite is :"
f_car=input(message)
print(f"ur favourite car is {f_car}")

效果:
在这里插入图片描述

使用int()可以将字符串转换为数值

#用int()获取数值输入
height = input("please tel me ur height(cm):")
height=int(height)
if height>100:
    print("please give me 100元")
else:
    print("is free")

效果:
在这里插入图片描述

使用while循环时要注意设置好跳出循环的条件,break可以立刻跳出循环

# break可以立刻退出循环 ,while()中设置跳出循环的条件
prompt="Please tell me your favourite car,and i will repeat it"
prompt+="\nenter 'quit to end the program':"
flag =True
while(flag):
    message=input(prompt)
    if message=="quit":
        flag=False
    elif message =="cadillac":
        break
    else:
        print(message)


效果:
在这里插入图片描述

continue可以直接返回循环开头

#使用continue可以返回循环开头
#打印1-10中的奇数
number=0
while number<10:
   number+=1
   if(number%2==1):
       print(number)
   else:
       continue

效果:
在这里插入图片描述

使用while处理列表与字典

在列表间移动元素

#在列表之间移动元素

flow_car=['bmw','aodi','benz']
cant_afford_car=[]

while flow_car:
    car=flow_car.pop()
    cant_afford_car.append(car)

print("the car which i cant afford is :")
for car in cant_afford_car:
    print(car)

效果:
在这里插入图片描述

删除列表中所有特定元素

#删除特定值的所有元素
cadillac_sires=['ct4','ct5','ct6','ct6','ct6','gt4','xt5']
while "ct6" in cadillac_sires:
    cadillac_sires.remove("ct6")

print(cadillac_sires)

效果:
在这里插入图片描述

使用用户输入来填充字典

#使用用户输入来补充字典
peoplesFavouriteCars={}
flag =True
while flag:
    name=input("what is ur name?")
    car=input("what is ur favourite car")
    peoplesFavouriteCars[name]=car
    message=input("do u want to continue this interview ? please anwser no to end")
    if message=="no":
        flag=False
print(peoplesFavouriteCars)

效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值