1.输入输出函数示例
a = 1
b = 2.0
print(a + b) # 加法
print(a - b) # 减法
print(a * b) # 乘法
print(a / b) # 除法
print(a ** b) # 幂
a = int(input('a='))
b = int(input('b='))
print('%d+%d=%d' % (a, b, a + b), '%d-%d=%d' % (a, b, a - b))
print('%d*%d=%d' % (a, b, a * b), '%d/%d=%.2f' % (a, b, a / b))
print('%d//%d=%d' % (a, b, a // b), '%d%%%d=%d' % (a, b, a % b))
print(0.2 + 0.1)
print('%.2f' % (0.2 + 0.1))
- python中求次方时,可以不用使用pow函数,例如求a^b,直接用**便可完成,十分方便。
- 输出时%d,%f与c语言无异,着重注意输出时的格式
- 由于input输入的是str类型,此处强制转换为int型,input函数内的内容,会在执行到此处时打印在控制台上。
2.逻辑运算符
flag0 = 1 == 1
flag1 = 3 > 2
flag2 = 2 < 1
print(flag0, flag1, flag2, flag1 and flag2, flag1 or flag2, not flag0)
注意python中,与或非分别对应and,or,not
3.判断类型
a = 1
b = 2.0
c = 1 + 5j
d = 'hello, world'
e = True
f = False
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>
print(type(d)) # <class 'str'>
print(type(e)) # <class 'bool'>
注意python中含有复数类型complex
无double类型,浮点数为float
字符串为str
4.列表的基本方法
bicycles = ["trek", "cannondale", 'redline', "cannondale", 'specialized', 'suzuki']
print(len(bicycles), bicycles, bicycles[len(bicycles) - 1], bicycles[-len(bicycles)])
print(sorted(bicycles)) # 临时性排序
print(sorted(bicycles, reverse=True)) # 临时性反向排序
bicycles.sort() # 永久性排序
bicycles.sort(reverse=True) # 永久性反向排序
bicycles[0] = 'honda' # 修改列表元素
bicycles.append('trek') # 末端添加元素
bicycles.insert(0, 'yamaha') # 插入元素
del bicycles[0] # 删除元素
pop_bicycles = bicycles.pop() # 默认删除末端元素
pop_bicycles = bicycles.pop(0) # 删除下标为0的元素
bicycles.remove('cannondale') # 删除第一个值为cannondale的元素
bicycles.reverse() # 反转列表
# bicycles.clear() # 清空列表
a = [1, 2, 3, 1, 'nb', bicycles]
b = [4, 5, 6]
print(a.count(1), b.count(4)) # 计算列表中某元素的个数
a.extend(b) # 将b列表加入到a列表后面
print(a)
print(a.index(1)) # 第一个1出现的序号
- 想要获取列表某个元素,可以取到的下标范围是闭区间 [ -len(bicycles) , len(bicycles)-1 ], 例如取倒数第二个元素,bicycles[-2]
- sorted是临时性排序,注意与列表永久性排序的区别:sorted不是列表的方法,直接调用,参数为列表,不对列表本身作排序,返回值是排序后的列表。永久性排序直接对列表本身作排序,是列表的方法。
5.创建数值列表
for value in range(5): #输出值为0-4,range(5)包含范围是0-4
print(value)
list1_4 = list(range(1, 5)) # 列表值为【1,5)
list2_10 = list(range(2, 12, 2)) # 列表值为【2,12)间隔为2的值
print(list1_4, list2_10)
print(min(list1_4), max(list1_4), sum(list1_4)) #可以用min,max,sum计算数值列表的相关值
squares = [value ** 2 for value in range(1, 11)] # 列表解析,列表值为1-10的平方
6.列表切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
player0_2 = players # 其实两者指向一个列表
# 复制给player0_2,三种方式
player0_2 = players[:]
player0_2 = players.copy()
player0_2 = list(players)
print(players[0:3]) # 打印0-2的元素
print(players[:2]) # 打印0-1的元素
print(players[2:]) # 打印2及之后的元素
print(players[-2:]) # 打印倒数第二个及之后的元素
print(players[:-2]) # 打印倒数第二个之前的元素
将一个列表赋值给另外一个列表不能用=,因为用赋值=两者指向的是相同的列表
7.元组
dimensions = (200, 50)
print(dimensions, dimensions[-1]) #元组是特殊的列表,同样可以使用负数下标
for dimension in dimensions:
print(dimension, end=' ')
print('')
dimensions = (100, 200) # 可以对整个元组修改,不能对元组中一个元素修改
# dimensions[0]=5错误
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list) # 列表->元组
t = ('王大锤', 20, True, '云南昆明')
person = list(t) # 将元组转换成列表
8.字符串
message0 = ' *- Hello woRld! *- *'
print("单词首字母大写:" + message0.title())
print("全部变为小写:" + message0.lower())
print("全部变为大写:" + message0.upper())
print("去除末端空格:" + message0.rstrip())
print("去除前端空格:" + message0.lstrip())
print("去除前后端空格:" + message0.strip())
print("去除前后端的*和空格:" + message0.strip(' *'))
print("进行替换:" + message0.replace('Rl', 'rl'))
print("查找*-的位置:", message0.find('*-'))
print("happy " + str(int(23.25)) + "rd birthday") #str将其他类型转换为str类型
message2 = message0.split('*-') # 按*-将其拆分为列表
print(message2)
message3 = '+'.join(message2) # 用+连接列表
print(message3)
# 以三个双引号或单引号开头的字符串可以折行
s3 = """
hello,
world!
"""
#转义符
s1 = '\'hello, world!\'' # 输出的实际上是'hello, world!'
s2 = '\\hello, world!\\' #输出的实际上是\hello, world!\
print(s1, s2)
#字符与整型转换
c = int(input('输入asc码:'))
print('asc码对应的字符是%c' % chr(c)) # 整型->字符,使用chr
c = input('输入字符:')
print('字符对应的编码是%d' % ord(c)) # 字符->整型,使用ord
# 字符串可以和列表元组的转换
message0 = ' *- Hello woRld! *- *'
list0 = list(message0)
print(list0)
tuple0 = tuple(message0)
print(tuple0)
9.字典
alien_3 = (1, 2, 3)
# 一系列键值对,与键相关联的值可以是数字、字符串、列表乃至字典。
alien_0 = {'color': 'green', 'points': 5, 3: 'nb', 'append': alien_3}
for alien in alien_0: # 遍历字典默认遍历键
print(alien_0[alien])
# 添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
# 删除键值对
del alien_0['append']
# 多行写法
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python', # 此处可以加,
}
# 对键进行临时排序,输出
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
# 输出键值
for key, value in favorite_languages.items():
print("\nKey: " + key)
print("Value: " + value)
# 输出键
for key in favorite_languages.keys():
print("Key is " + key)
# 输出值
for value in favorite_languages.values():
print('value is ' + value)
# 输出不重复值
for value in set(favorite_languages.values()):
print('not repeat value is ' + value)
10.函数
def describe_pet(pet_name, animal_type='dog'): # 默认参数必须在最右端
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('willie') # 传给pet_name,位置实参
describe_pet(pet_name='willie') #关键字实参
# 一只名为Harry的仓鼠
describe_pet('harry', 'hamster') #位置实参,修改了默认参数
describe_pet(pet_name='harry', animal_type='hamster') #关键字实参,修改了默认参数
describe_pet(animal_type='hamster', pet_name='harry') #关键字实参不必在乎顺序了
# 传递任意数量的实参
def make_pizza(*toppings): # toppings为列表
"""打印顾客点的所有配料"""
print(toppings)
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# 传递任意数量的关键字实参
def build_profile(first, last, **user_info): # user_info是字典
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
11.类
car.py
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #默认值为0的属性
def read_odometer(self):
print('this car has ' + str(self.odometer_reading) + ' miles on it.')
def update_odometer(self, mileage):
if mileage > self.odometer_reading:
self.odometer_reading = mileage
def increment_odometer(self, miles):
if miles > 0:
self.odometer_reading += miles
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def fill_gas_tank(self):
print("This car need a gas tank!")
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
class ElectricCar(Car): #继承自Car类
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year) # 用父类初始化
self.battery_size = 60
self.battery = Battery(80) # 用实例做属性
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self): # 重写父类方法
"""电动汽车没有油箱"""
print("This car doesn't need a gas tank!")
导入car.py中的类
import car # 导入所有的代码
#想调用Car类的使用方法为car.Car()
import car as cars # 导入并重命名
#想调用Car类的使用方法为cars.Car()
from car import Car,ElectricCar # 从car.py中导入Car类与ElectricCar类
#想调用Car类的使用方法为Car()
from car import ElectricCar as electriccar # 从car.py中导入ElectricCar类,并命名
#想调用ElectricCar类的使用方法为electriccar()
from car import * # 从car.py中导入所有类