2020.08.23—08.25
python安装时“add python to path”选项是将python的安装路径添加到系统的安装路径之下,这样就可以下windows终端命令下输入python调用,否则你需要先跳转到python的安装路径,然后输入python进行调用。
关于IDE的配置中的编译命令Compile和执行命令Execute后面应该选择python所在文件夹路径。
想创建的三个程序:
建立一个储物网站
创建一个类似TNT的小游戏
制作一个自动买入卖出基金的应用程序
淘宝,京东秒杀抢券的一个应用程序
python中变量名只能是字母,下划线(—),和数字的组合,并且数字不能放在首位;变量名不能含有空格;变量名应该有实际意义并且简短;变量名不能与python关键字和函数名重复;全部大写的变量名一般表示一个常量;
改变字符串大小写的操作(字符串一定用引号括起来)
name = "Zhang lei"
print(name.title())
print(name.upper())
print(name.lower())
first_name = 'zhang'
last_name = 'lei'
full_name = first_name + ' ' +last_name
print('hello, ' + full_name.title() + ' !' )
print('Language:\n\tC\n\tpython\n\tjava')
print('The Language:')
print('\tpython')
language = ' python '
print(language)
print(language.rstrip())
print(language.lstrip())
print(language.strip())
names = ['zhanglei', 'chunjiao', 'dongdong']
print(names[0].title(), names[1])
print(names[-1])
roll = ['zhanglei', 'chunjiao', 'dongdong']
roll.pop(2)
roll.insert(0,'didi')
print(roll)
roll.append('meimei')
print(roll)
del roll[0]
print(roll)
roll.pop(0)
print(roll)
roll.remove('meimei')
print(roll)
roll = ['zhanglei', 'chunjiao', 'dongdong']
print(len(roll))
roll.sort() #按照字母顺序排序,是永久性的,不能恢复到以前位置
print(roll)
roll.sort(reverse = True)#按照字母反向排序,是永久性的,不能恢复到以前位置
print(roll)
roll.reverse()#与之前顺序相反,是永久性的,再次调用这个reserve命令可以恢复以前位置
print(roll)
roll.reverse()
print(roll)
sorted(roll)
print(roll)
print(sorted(roll))#对列表进行临时排序
print(sorted(roll,reverse = True))
animals = ['dog', 'cat', 'panda']
for animal in animals:
print(animal)
print('A', animal, 'would make a great pet\n')
print('Any of these animals would make a great pet')
number = list(range(1, 20, 2))
for even_number in number:
print(even_number)
print('\n')
squares = []
for square in range(1, 11):
squares.append(square**3)
for number_1 in squares:
print(number_1)
squares_1 = [square_1**3 for square_1 in range(1, 11)]
print(squares_1)
numbers = list(range(1, 11))
print(numbers[:2])
print(numbers[-2:])
print(numbers[2:3])
for number in numbers[1:6]:
print(number)
my_favorite = ['pizza', 'cake', 'falafel']
friend_favorite = my_favorite
friend_favorite.append('ice cream')
my_favorite.append('bread')
print(my_favorite)
print(friend_favorite)
friend_favorite1 = my_favorite[:]
friend_favorite1.append('ice cream')
my_favorite.append('bread')
print(my_favorite)
print(friend_favorite1)
numbers =tuple(range(1, 11))
for number in numbers:
print(number)
print(numbers)
l = [1, 2]
l.append(3) #列表可以改动
print(l)
# numbers.append(11)
# print(numbers) 元组不能改动
numbers = tuple(range(1, 5)) #可以对元组变量重新赋值
print(numbers)
l = [1, 2, 3, 4]
a = 1
b = 2
if a == l[0]:
print(a)
if a == l[0] and b > l[2]:
print(b)
else:
print(a)
if a == l[0] or b > l[2]:
print(b)
else:
print(a)
if 1 in l:
print(a)
if 5 not in l:
print(a)
name = []
if name:
print('name is not void')
else:
print('name is void')
number_1 = [1, 2, 3, 4]
number_2 = [2, 3, 4 ,5]
for number in number_2:
if number in number_1:
print(number, '属于两者')
else:
print(number, '只属于number_2')
alien_0 = {
'color': 'green', 'points': '5'}#字典冒号后面加上一个空格
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25 #为字典添加键值对
print(alien_0)
#
# alien_1 = {}
# alien_1['meimei'] = 1
# alien_1['gege'] = 2 #创建一个空字典
# print(alien_1)
alien_0['speed'] = 'fast'
del alien_0['color'], alien_0['points']#删除字典中的键值对
print(alien_0)
print('original x_position:', alien_0['x_position'])
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
#外星人移动速度很快
x_increment = 3
#新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print('New x_position:', alien_0['x_position'])
user_0 = {
'user_name': 'zhanglei',
'first_name': 'zhang',
'last_name': 'lei',
}
for k,v in user_0.items():#字典名加上方法items(),返回一个键-值对列表
print('\nkey:', k)
print('value:', v)
favorite_language = {
'xiaohua': 'python',
'xiaoyu': 'c',
'xiaofang': 'java',
}
names = ['xiaoyu', 'xiaohua']
for name in favorite_language.keys(): #favorite_languag.key()返回的是字典中的键形成的列表,也可以不加.key(),字典名默认返回也是键
print(name)
if name in names:
print('hi,', name,
', I know your favorite language is',
favorite_language[name], '.\n' #favorite_language[name]中name没有引号,它是一个变量
)
for name_0 in sorted(favorite_language.keys()):#将字典中的键组成的列表排序
print('\n', name_0.title())
for language in sorted(favorite_language.values()):#将字典中的值组成的列表排序
print('\n', language.title())
favorite_language = {
'xiaohua': 'python',
'xiaoyu': 'c',
'xiaofang': 'java',
'xiaolei': 'python',
}
for language in set(sorted(favorite_language.values())): #set(列表名)是剔除列表里面的重复元素
print(language)
#创建一个用于存储外星人的空列表
aliens = []
#创建三十个绿色外星人
for alien_number in range(30):
new_alien = {
'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
#显示前5个外星人
for alien in aliens[:5]:
print(alien)
print('...')
#显示创建了多少外星人
print(len(aliens))
#将前三个绿色外星人颜色改为黄色,分值为10,速度为中等
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 10
alien['speed'] = 'medium'
#显示前5个外星人
for alien in aliens[:5]:
print(alien)
pizza = {
'toppings': ['mushrom', 'extra chess'],
'crust': 'thick',
}
print('you orded a', pizza['crust'] + '-crust pizza' #print中字符串和变量是一定用逗号隔开,并且用逗号隔开会自动加一个空格
'with following toppings:')#字符串和字符串可以不用逗号隔开,但是要想表示两个分开的字符串,需要在其中一个字符串里面加空格,加逗号没用
#用+可以链接字符串与字符串,或者字符串和变量,并且没有空格
for topping in pizza['toppings']:
print(topping)
users = {
'xuyu':{
'first_name': 'xu',
'last_name': 'yu',
'location': 'anqing'
},
'wuhua': {
'first_name': 'wu',
'last_name': 'hua',
'location': 'chizhou'
}
}
for user_name, info in users.items():
print('username:', user_name)
full_name = info['first_name'] + ' ' + info['last_name']
print('\tFullname', full_name)
location = info['location']
print('\tLocation', location)
#input()函数是接受一个参数,这个参数是一个提示用户如何输入的信息,一般是个字符串,也可以是一个变量(事先将字符串赋值给该变量);
# 并且将用户输入的信息存储到一个变量中;并且将用户输入内容解读为字符串;
message = input('Tell me something, and I will repeat it back to you: ')
print(message)
prompt = 'If you tell me who are you, I can personlize the message you see' \
'\nWhat is you first name? '
name = input(prompt)
print('\nHello,', name)
age = input('please tell me your age: ')
if int(age) > 18: #int()函数将数字的字符串表示为数值表示
print('adult')
prompt = 'Tell me something, I will repeat it back to you. (Enter "quit" end the program): '
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
prompt = 'Tell me something, I will repeat it back to you. (Enter "quit" end the program): '
message = ""
active = True #True,Flase 不用加引号
while active:
message = input(prompt)
if message != 'quit':
print(message)
else:
active = False
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue #continue是直接忽略循环中下面的代码,并且回到while循环的开头去;break是不再执行余下代码并且退出整个循环
else:
print(number)
number_0 = [0, 1, 2, 3]
number_1 = []
while len(number_0) > 1:#while条件判别式如果是个列表,会不断运行,直到列表为空
current_number = number_0.pop(1)
number_1.append(current_number)
print(number_1)
responses = {
}
#设置一个标志
polling_active = True
while polling_active:
#做个问卷调查
name = input('please enter 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---RESULTS---')
for name, response in responses.items():
print(name, 'would like to climb', response)
#位置实参,关键字实参
def pet(animal_type, animal_name):
print('I have a', animal_type)
print("My", animal_type + "'s name is", animal_name)
pet('dog', 'xiaomei')#位置实参,注意实参顺序不能写反了
pet(animal_name='xiaomei', animal_type='dog')#关键字实参,注意形参的名字不能写错了,顺序无所谓,因为实参与形参是指定的
#默认值形参
def pet_0(animal_name, animal_type = 'dog'): #定义函数时,给出形参的默认值,这样调用函数时就可以不给出与animal_name对应的实参了
print('I have a', animal_type)#上面有默认值的形参应放在后面
print("My", animal_type + "'s name is", animal_name)
pet_0('xiaoming')
#传递任意数量的同类型实参
def make_pizza(*toppings): #*toppings这个形参是指无论调用函数时传入多少实参,都将他们封装到一个名为toppings的元组之中
for topping in toppings:
print('-', topping)
make_pizza('mushrooms', 'extra chess', 'green peppers')
#如果实参类型不同,比如传递pizza尺寸以及配料
def make_pizza(size, *toppings): #python先匹配位置实参和关键字实参,再将余下的实参都放在最后一个形参中,因此*topping应放在后面
for topping in toppings:
print('-', topping)
print(size)
make_pizza(15, 'mushrooms', 'extra chess', 'green peppers')
#使用任意数量的关键字实参
def build_profile(first, last, **user_info):
profile = {
}
profile['first_name'] = first
profile['last_namae'] = last
for key, value in user_info.items():
profile[key] = value
return (profile)
user_profile = build_profile('zhang', 'lei',
location = 'huabei', field = 'computer')#关键字实参传递给函数的是名称-值对,名称不加引号
print(user_profile)
导入函数的几种方法
import 模块名(模块名就是你编写函数的那个文件名) (可以用 import 模块名 as 新名称 来给模块取别名 )
调用函数时:模块名.函数名
from 模块名 import 函数名 (同上也可以加 as 新名称 为函数取别名)
调用函数时:函数名
class Restaurant():
'''模拟饭店'''
def __init__(self, restaurant_name, cuisine_type):#注意这里是双下划线__
'''初始化属性饭店名和烹饪类型'''
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type #以self为前缀的变量都可供类中所有方法使用
def describe_restaurant(self):
'''描述饭店名字和烹饪类型'''
print('The restaurant name is', self.restaurant_name)
print("The restaurant's cuisine type is", self.cuisine_type)
def open_restaurant(self):
'''参观正在营业,欢迎光临'''
print(self.restaurant_name, 'is now opening')
my_restaurant = Restaurant ('rain', 'boil')#用之前定义的类来创建实例
print(my_restaurant.restaurant_name)#创建实例后再调用类中属性restaurant_name,和cuisine_type就不加self了,换成实例名
print(my_restaurant.cuisine_type)
my_restaurant.describe_restaurant() #调用类中的方法
my_restaurant.open_restaurant()
xiaohua_restaurant = Restaurant('huazi', 'steam')
print('\n' + xiaohua_restaurant.restaurant_name)
print(xiaohua_restaurant.cuisine_type)
xiaohua_restaurant.describe_restaurant()
xiaohua_restaurant.open_restaurant()
class Car():
'''模拟汽车'''
def __init__(self, make, model, year):
'''初始化描述汽车的属性'''
self.make = make
self.model = model #类中的每个属性必须有初始值
self.year = year
self.odometer_reading = 0 #如果某个属性有初始值,在__init__内部定义即可,并且无需包含为他提供初始值的形参
def get_descriptive(self):
'''返回整洁的汽车描述信息'''
long_name = self.year + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
'''打印出汽车目前里程'''
print(self.odometer_reading)
def update_odometer(self, mileage):
'''将里程表读数设为指定值'''
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer")
my_car = Car('audi', 'a4', '2016')
print(my_car.get_descriptive())
my_car.read_odometer()
my_car.odometer_reading = 23#用实例直接调用类中属性来修改它的值
my_car.read_odometer()
my_car.update_odometer(25)#通过重新定义一个方法来修改属性值
my_car.read_odometer()
class Car():
'''模拟汽车'''
def __init__(self, make, model, year):
'''初始化描述汽车的属性'''
self.make = make
self.model = model #类中的每个属性必须有初始值
self.year = year
self.odometer_reading = 0 #如果某个属性有初始值,在__init__内部定义即可,并且无需包含为他提供初始值的形参
def get_descriptive(self):
'''返回整洁的汽车描述信息'''
long_name = self.year + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
'''打印出汽车目前里程'''
print(self.odometer_reading)
def update_odometer(self, mileage):
'''将里程表读数设为指定值'''
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer")
my_car = Car('audi', 'a4', '2016')
print(my_car.get_descriptive())
my_car.read_odometer()
my_car.odometer_reading = 23#用实例直接调用类中属性来修改它的值
my_car.read_odometer()
my_car.update_odometer(25)#通过重新定义一个方法来修改属性值
my_car.read_odometer()
class Battery():
'''描述电池'''
def __init__(self, battery_size=70): #battery_size这个形参是可选的,如果没有为它提供一个下实参,它就默认为70
'''初始化电池属性'''
self.battery_size = battery_size #不能省略,因为这是对属性的初始化,battery_size=70,只是提供默认值,不是初始化
def describe_battery(self):
'''用来描述电池容量'''
print("The car have a", str(self.battery_size) + "-kwh battery")
class ElectricCar(Car):
'''
模拟电瓶车,先继承父类
'''
def __init__(self, make, model, year):
'''初始化父类的属性'''
super().__init__(make, model, year) #让这个子类包含父类所有属性和方法
self.battery = Battery() #初始化电车特有属性,创建了一个新的实例(关于Battery类的)
# 并把他赋值于battery属性,Battery()括号里面没有参数,是因为之前Battery类中属性已经默认为70
my_electric_car = ElectricCar('yadi', 'S', '2020')
print(my_electric_car.get_descriptive())
my_electric_car.battery.describe_battery()
with open('pi_digits.txt') as file_object: #open()函数接受文件名,返回一个表示文件的对象;关键字with在不需要访问文件时将其关闭
contents = file_object.read() #方法read()读取用来读取文件全部内容,并且将内容以字符串形式返回
print(contents.rstrip()) #方法rstrip()用来删除字符串末尾空白
with open('.idea/filename.txt') as file_objict:#相对路径是指这个要查找的文件是放在该程序所在文件夹下的另一个文件夹之中,本例是.idea
contents = file_objict.read()
print(contents)
filename ='pi_digits.txt'
'''逐行读取'''
with open(filename) as file_object: #将一个表示文件及其内容的对象存储到file_object变量中
for line in file_object:
print(line.rstrip())
'''创建一个包含文件各行内容的列表'''
with open(filename) as file_object:
lines = file_object.readlines() #方法readlines()从文件中读取每一行将其存储在一个列表中,本例将该列表存储在变量lines中
pi_string = ''
for line in lines: #open()返回的这个表示文件的对像只能在with代码块中使用
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
'''将新内容覆盖原有内容,只读模式,会清除原有内容'''
filename = 'test.text'
with open(filename, 'w') as file_object:
#open()中形参'w'是以写入模式打开文件,注意如果该文件不存在,python会在程序当前目录下创建该文件
# 如果已经存在,python将在返回文件对象前清空该文件,意思就是将新内容覆盖原有内容;'r+'读取和写入模式 'r'读取模式 'a'附加模式
file_object.write('thank you\n') #方法write()将字符串写入文件中
'''附加新内容到文件,而不是覆盖原有文件(附加模式)'''
with open(filename, 'a') as file_object:
file_object.write('I really love you') #将新内容附加到文件末尾
active = True
while active:
name = input('please enter your name (if you want quit please enter "q"): ')
if name == 'q':
break
else:
filename = 'guest_book.text'
record = 'hello, ' + name.title()
print(record)
with open(filename, 'a') as file_object:
file_object.write(record + '\n')
a = input('Give me a divisor: ')
b = input('Give me a dividend: ')
try:
c = int(a) / int(b) #input()让用户输入的是字符串形式,因此要转换为整数来运算
except ZeroDivisionError:
print('零不能被除') #可以用pass来跳过这个信息,不让用户看到
else:
print(c)
'''导入json模块,用json.dump(),json.load()处理程序与文件之间的数据关系'''
import json
numbers = [0, 1, 2, 3, 4, 5]
filename = 'numbers.json' #文件存储数据为json格式
with open(filename, 'w') as fl_obj:
json.dump(numbers, fl_obj) #利用json.dump()将python中的数据结构写入到一个文件中
with open(filename) as fl_obj:
numbers0 = json.load(fl_obj)#jaon.load()读取文件中的内容将其把存到numbers0变量之中
print(numbers0)
import json
#如果以前存储了用户名就加载它,否则就提示用户输入用户名并存储它
filename = 'user_name.json'
try:
with open(filename) as fl_obj:
name = json.load(fl_obj)
except FileNotFoundError:
name = input('please enter your name: ')
with open(filename, 'w') as fl_obj:
json.dump(name, fl_obj)
print('we will remember you when you come back:', name)
else:
print('welcome back:', name)
import json
def get_stored_name():
'''如果用户存在就读取之前存在的用户名'''
filename = 'user_name.json'
try:
with open(filename) as fl_obj:
name = json.load(fl_obj)
except FileNotFoundError:
return None
else:
return name
def new_name():
'''如果是新用户,则保存该用户名到文件中'''
filename = 'user_name.json'
name = input('please enter your name: ')
with open(filename, 'w') as fl_obj:
json.dump(name, fl_obj)
return name
def greet_user():
'''问候用户,并指出名字'''
name = get_stored_name()
if name:
print('welcome back:', name)
else:
name = new_name()
print('we well welcome you when you come back', name)
greet_user()
文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99
文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效
文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是
文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件
文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件
文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码
文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware
文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停
文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待
文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析
文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code
文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象