用户输入和while循环
- 函数input()让程序暂停运行,等待用户输入一些文本
- 使用 int()来获取数值输入
- 处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:
- while循环结构体
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
- 使用 break 退出循环
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
- 注意避免无限循环,加上判断条件
使用 while 循环来处理列表和字典
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
函数
- 定义函数相比于java的方法来讲,感受是很类似
def greet_user(username):
print("Hello, " + username.title() + "!")
greet_user('jesse')
- 实参和形参
形参:username
实参:jesse - 返回值
def greet_user(username):
return username.title()
print("Hello, " +greet_user('jesse')+ "!")
类
类的定义
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
def roll_over(self):
print(self.name.title() + " rolled over!")
类继承
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
def roll_over(self):
print(self.name.title() + " rolled over!")
class Jinmao(Dog):
def __init__(self, name, age):
super().__init__(name, age)
my_dog = Jinmao('tesla',3)
print(my_dog.sit())
导入类