文章目录
一、函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其赋给一个变量。
# input函数使用
message = input("tell me something,and i will repeat it back to you\n")
print(message)
name = input("please enter your name:\n")
print(f"hello {name}")
使用int()获取数值输入
# 使用int()来获取数值输入
age = input("how old are you?")
print(f"I'm {age} years old")
# 这里的年龄类型是字符型
# 如果要与数字进行计算需要int()来转换
print(int(age)+3)
求模运算
number = input("enter a number,and I'll tell you if it's even odd:\n")
number = int(number)
if number % 2 ==0:
print(f"\nthe number {number} is even")
else:
print(f"\nthe number {number} is odd")
二、while循环简介
for循环是针对集合中的每个元素都执行一个代码块,while循环则不断运行,知道指定的条件不满足为止。
使用while循环
current_number = 1
while current_number<=5:
print(current_number)
current_number+=1
让用户选择何时退出
prompt = "\ntell me something,and i will repeat it back to you:"
prompt+="\nenter 'quit' to end the program.\n"
message = ""
while message!='quit':
message = input(prompt)
print(message)
break和continue
# break语句
prompt = "\nplease enter the name of a city you have visited:"
prompt+="\nenter 'quit' when you are finished.\n"
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd love to go to {city.title()}!")
# continue语句,输出奇数
current_number = 0
while current_number<10:
current_number +=1
if current_number%2==0:
continue
print(current_number)
三使用while循环处理列表和字典
列表之间移动数据
unconfirmed_users = ['alice','brain','candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"verifying user:{current_user.title()}")
confirmed_users.append(current_user)
print("\nthe following users have been confirmed")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
删除特定值
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
使用用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
name = input("\nwhat is your name")
response = input("which mountain would you like to climb someday")
responses[name] = response
repeat = input("would you like to let another person respond?(yes/no)")
if repeat == 'no':
polling_active = False
print("\n---Poll Results---")
for name,response in responses.items():
print(f"{name} would like to climb {response}")
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。