python编程基础(六):input 输入 & while 循环处理列表及字典

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunshinefcx/article/details/89642983

一、input() 函数

1、input() 基本用法

 input() 函数让程序暂停运行,等待用户输入一些文本。不管输入的是什么内容,程序通过 input() 得到的始终是 字符串 类型,使用方法如下:

message = input('Tell me something, and I will repeat it to you:')
print(message)


结果:
Tell me something, and I will repeat it to you:hello everyone
hello everyone

注意:在使用 input()  函数的时候,最终的目的是通过提示让用户输入我们想要的内容,因此,我们需要把要求写的清楚一点

Tips: 在 input() 的提示末尾加一个空格,将提示与输入内容分开,让用户知道自己的输入始于何处。

2、input() 多行提示

有时候我们

prompt = "If you tell us who you are, wo can personalize the maeeage you see"
prompt += "\nWhat is your frist name? "  # 用 += 实现连接;在结尾加一个空格

name = input(prompt)
print('\nHello, '+name+"!")


结果:
If you tell us who you are, wo can personalize the maeeage you see
What is your frist name? chen

Hello, chen!

3、获得数值型的输入

不管输入的是啥,最终通过  input()  函数得到的都是字符串类型的变量,加入我们输入 66,想以数值的方式去使用,那我们应该怎实现?

首先,肯定还是用 input 函数来获取,得到的是字符串

随后,我们再用  int()  函数实现强制类型转换即可得到相应的数值类型

height = input('How tall are you, in inches? ')
height = int(height)

if height >= 36:
    print('\nYou are tall enough to ride!')
else:
    print('\nYou will be able to ride when you are a little older.')


结果:
How tall are you, in inches? 71

You are tall enough to ride!

二、while循环处理列表及字典

1、在列表之间移动元素

假设有个列表包含的新注册但是没有通过认证的网站用户,在验证完成之后需要把这个用户移动到其他列表中:

# 首先创建一个待验证的用户列表
# 以及一个存储已验证用户的空列表
unconfirmed_users = ['aaa','bbb','ccc']
confirmed_users = []

# 验证每个用户,直到遍历完
while unconfirmed_users:    # 判断条件直接用列表,当列表变空时,也就是循环条件为 0
    current_user = unconfirmed_users.pop()
    
    print('Verifying user: '+current_user.title())
    confirmed_users.append(current_user)

print('\nThe follwing users have been confirmed: ')
for confirmed_user in confirmed_users:
    print(confirmed_user.title())   



结果:
Verifying user: Ccc
Verifying user: Bbb
Verifying user: Aaa

The follwing users have been confirmed: 
Ccc
Bbb
Aaa

2、删除包含特定值的所有列表元素

在之前学习列表的时候 如果不知道元素的位置,只知道元素的值,想要删除这个元素的时候我们可以使用  remove() 函数来实现

pets = ['dog','cat','dog','glodfish','cat','rabbit','cat']

while 'cat' in pets:
    pets.remove('cat')

print(pets)


结果:
['dog', 'dog', 'glodfish', 'rabbit']

猜你喜欢

转载自blog.csdn.net/sunshinefcx/article/details/89642983