python学习笔记

Python Learning Notes

Author:Jerry
Date:2019/8/5
Purpose:Python Drawing/Computing

import turtle
fred = turtle.Turtle()
fred.color("red")
fred.forward(100)
fred.right(135)
fred.forward(140)
fred.right(135)
fred.forward(100)

import turtle
george = turtle.Turtle()
george.color("yellow")
for side in [1, 2, 3, 4]:
    george.forward(100)
    george.right(90)

1.在计算 a and b 时,如果 a 是 False,则根据与运算法则,整个结果必定为 False,因此返回 a;
如果 a 是 True,则整个计算结果必定取决与 b,因此返回 b。
2.在计算 a or b 时,如果 a 是 True,则根据或运算法则,整个计算结果必定为 True,因此返回 a;
如果 a 是 False,则整个计算结果必定取决于 b,因此返回 b。
所以Python解释器在做布尔运算时,只要能提前确定计算结果,它就不会往后算了,直接返回结果。

# Example
a = 'python'
print ('hello,', a or 'world') # a是True,所以Python
b = ''
print ('hello,', b or 'world') # b是False,所以world
hello, python
hello, world
L = ['Adam', 95.5, 'Lisa', 85, 'Bart', 59]
print (L)
print(L[0])
['Adam', 95.5, 'Lisa', 85, 'Bart', 59]
Adam

在一个字符串中,行末的单独一个反斜杠表示字符串在下一行继续,而不是开始一个新的行。
例如:“This is the first sentence.\
This is the second sentence.”
等价于"This is the first sentence. This is the second sentence.

range(10) 0,1,2,3,4,5,6,7,8,9

print('hello,world')
hello,world
print(1+1)
2

ubuntu中

ctrl + shift + = 放大终端窗口的字体显示
ctrl + -缩小终端窗口的字体字体显示

命令对应英文作用
lslist查看当前文件夹内容
pwdprint work directory查看当前所在文件夹
cd[目录名]change directory切换文件夹
touch[文件名]touch如果文件不在,新建文件
mkdir[目录名]make directory创建目录
rm[文件名]remove删除指定的文件名
clearclear清屏
b = '12'
f'xianghong {b}' #格式化字符串
'xianghong 12'
'qiyang'.upper()
'QIYANG'
a = 'hello'
a[0]
'h'
a = ['hello',1,2]
a.append(2) 在末尾加上2
a
['hello', 1, 2, 2]
a = [1,3,4,5]
a.insert(1,2) #在a[1]位置插入2
a
[1, 2, 3, 4, 5]
a = [1,2,3,4]
a.pop() # 删掉最后一项,并返回最后一项
4
a
[1, 2, 3]
len(a) # 返回长度
3
def triangle():
    name = input('your name') # 输入名字
    width =  int(input('输入底线长度'))
    height = int(input('高度')) # input输入的是字符串不能乘除
    result = width*height/2
    print(f'三角形面积:{result}')
   #  print('三角形面积:' + str(width*height/2)) #字符串自能跟字符串相加
    print('hello ' + name)
triangle()
your name 1
输入底线长度 2
高度 2


三角形面积:2.0
hello 1

github查找项目

in:name 名字 stars:>3000 forks:>3000

in:readme 名字 language:python

in:description 名字 pushed:>2019-11-11

len("hello")
5
'apple'[:4]
'appl'
'apple'[2:4]
'pl'
import math
math.pi

3.141592653589793
f"6位数={math.pi:.6}"
'6位数=3.14159'

按ESC键跳到命令模式,然后:

:w 保存文件但不退出vi.

:w file 将修改另外保存到file中,不退出vi.

:w! 强制保存,不推出vi.

:wq 保存文件并退出vi.

:wq! 强制保存文件,并退出vi.

q: 不保存文件,退出vi.

:q! 不保存文件,强制退出vi.

:e! 放弃所有修改,从上次保存文件开始再编辑

在Python交互模式下输入exit()并回车,就退出了Python交互模式,并回到命令行模式

'abc' in 'abcabcabcabcabac' #abc是否在后面的字符串中
True
'abc' not in 'abcabcabcabcabac'
False
'123nihao'.find('nihao') # 子字符串从哪开始一样
3
'nihao nihao nihao nihao nihao'.count('nihao') # nihao 出现几次
5
words = ['my','dog','has','fleas']
" ".join(words)
'my dog has fleas'
" and ".join(words)
'my and dog and has and fleas'
import os
os.listdir("Django Learning") # 显示文件名
['.idea', 'learning', 'README.md']
os.mkdir("test") # 新建文件夹

os.rename(“python/test.py”,“python/test2.py”) # 将文件改名并移动到另一个文件夹

my_story = open("123.txt") # 打开文件,可以写路径
contents = my_story.read() # 读取文件
contents
'RFE RHG TRH YTRJJ UYJ UYJ'
my_story.close()
with open("123.txt") as my_story: # 仅在代码执行阶段打开文件,完毕后关闭
    print(my_story.read())
RFE RHG TRH YTRJJ UYJ UYJ
"rrudacityrr".strip("r") # 前面字符串中删除r
'udacity'
import string
string.punctuation # 输出标点符号
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

终端输入:curl -o google.html ‘https://www.google.com/’
#访问 http://www.google.com 并保存为 google.html

try except

d = {} # 字典,花括号
d["squid"] = "A tentacled molluskof the briny deep"
d["squad"] = "a smallish horde"
d
{'squid': 'A tentacled molluskof the briny deep', 'squad': 'a smallish horde'}
print(d)
d["squid"] = "A tentacled molluskof the briny deep"
d["squad"] = "a smallish horde"
del d["squid"]
print(d)
{'a': 'alpha', 'b': 'bravo', 'c': 'charlie', 'squid': 'A tentacled molluskof the briny deep'}
{'a': 'alpha', 'b': 'bravo', 'c': 'charlie', 'squad': 'a smallish horde'}
words = {'turtle':'reptile','frog':'amphibian'}
words['frog']
'amphibian'
d = {'a': 'alpha', 'b': 'bravo', 'c': 'charlie'}
print(d['e'])
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-12-37738a563e30> in <module>
      1 d = {'a': 'alpha', 'b': 'bravo', 'c': 'charlie'}
----> 2 print(d['e'])


KeyError: 'e'
favorites = {'color': 'purple', 'number': 42, 'animal': 'turtle', 'language': 'python'}
for entry in favorites.keys(): # 显示键
   print(entry)
for entry in favorites.values():# 显示值
   print(entry)
for entry in favorites.items(): # 显示全部
   print(entry)
for key, value in favorites.items():
    print(f"my favorite {key} is {value}")
color
number
animal
language
purple
42
turtle
python
('color', 'purple')
('number', 42)
('animal', 'turtle')
('language', 'python')
my favorite color is purple
my favorite number is 42
my favorite animal is turtle
my favorite language is python
import requests
r = requests.get('https://www.metaweather.com/api/location/2455920')
# 此请求使用 WOEID 获取特定城市的天气。在此示例中,WOEID 是 2455920,
# 对应的是加利福尼亚州的山景城。
d = r.json()
for key in d:
    print(key)
consolidated_weather
time
sun_rise
sun_set
timezone_name
parent
sources
title
location_type
woeid
latt_long
timezone
d['sun_rise']
'2019-11-20T06:52:51.181779-08:00'
d['consolidated_weather']
[{'id': 6196068389748736,
  'weather_state_name': 'Clear',
  'weather_state_abbr': 'c',
  'wind_direction_compass': 'NW',
  'created': '2019-11-21T04:42:40.881539Z',
  'applicable_date': '2019-11-20',
  'min_temp': 11.525,
  'max_temp': 19.14,
  'the_temp': 18.62,
  'wind_speed': 3.362167939234868,
  'wind_direction': 325.5,
  'air_pressure': 999.0,
  'humidity': 40,
  'visibility': 8.551931718762427,
  'predictability': 68},
 {'id': 5475183898918912,
  'weather_state_name': 'Clear',
  'weather_state_abbr': 'c',
  'wind_direction_compass': 'SW',
  'created': '2019-11-21T04:42:43.218801Z',
  'applicable_date': '2019-11-21',
  'min_temp': 9.05,
  'max_temp': 16.18,
  'the_temp': 13.25,
  'wind_speed': 2.3309820647419075,
  'wind_direction': 215.0,
  'air_pressure': 1001.0,
  'humidity': 51,
  'visibility': 9.999726596675416,
  'predictability': 68},
 {'id': 6669259767808000,
  'weather_state_name': 'Clear',
  'weather_state_abbr': 'c',
  'wind_direction_compass': 'NE',
  'created': '2019-11-21T04:42:46.566842Z',
  'applicable_date': '2019-11-22',
  'min_temp': 8.495000000000001,
  'max_temp': 18.84,
  'the_temp': 13.8,
  'wind_speed': 2.037967867652907,
  'wind_direction': 36.99999999999999,
  'air_pressure': 1011.0,
  'humidity': 64,
  'visibility': 9.999726596675416,
  'predictability': 68},
 {'id': 6650187898421248,
  'weather_state_name': 'Clear',
  'weather_state_abbr': 'c',
  'wind_direction_compass': 'N',
  'created': '2019-11-21T04:42:49.243200Z',
  'applicable_date': '2019-11-23',
  'min_temp': 8.93,
  'max_temp': 19.869999999999997,
  'the_temp': 14.85,
  'wind_speed': 1.7846633659428937,
  'wind_direction': 357.5,
  'air_pressure': 1022.0,
  'humidity': 61,
  'visibility': 9.999726596675416,
  'predictability': 68},
 {'id': 4735838296473600,
  'weather_state_name': 'Clear',
  'weather_state_abbr': 'c',
  'wind_direction_compass': 'NNW',
  'created': '2019-11-21T04:42:52.365848Z',
  'applicable_date': '2019-11-24',
  'min_temp': 8.73,
  'max_temp': 20.22,
  'the_temp': 15.62,
  'wind_speed': 1.4369456374771337,
  'wind_direction': 348.0,
  'air_pressure': 1023.0,
  'humidity': 56,
  'visibility': 9.70022568201702,
  'predictability': 68},
 {'id': 6428001287798784,
  'weather_state_name': 'Light Cloud',
  'weather_state_abbr': 'lc',
  'wind_direction_compass': 'NW',
  'created': '2019-11-21T04:42:55.129815Z',
  'applicable_date': '2019-11-25',
  'min_temp': 9.385,
  'max_temp': 19.435,
  'the_temp': 16.35,
  'wind_speed': 2.733014197089,
  'wind_direction': 315.0,
  'air_pressure': 1023.0,
  'humidity': 51,
  'visibility': 9.999726596675416,
  'predictability': 70}]
d['consolidated_weather'][0]
{'id': 6196068389748736,
 'weather_state_name': 'Clear',
 'weather_state_abbr': 'c',
 'wind_direction_compass': 'NW',
 'created': '2019-11-21T04:42:40.881539Z',
 'applicable_date': '2019-11-20',
 'min_temp': 11.525,
 'max_temp': 19.14,
 'the_temp': 18.62,
 'wind_speed': 3.362167939234868,
 'wind_direction': 325.5,
 'air_pressure': 999.0,
 'humidity': 40,
 'visibility': 8.551931718762427,
 'predictability': 68}
d['consolidated_weather'][0]["min_temp"]
11.525
import requests
yahoo = requests.get("https://www.yahoo.com/")
print(yahoo.text)
#!/usr/bin/env python3

import requests

API_ROOT = 'https://www.metaweather.com'
API_LOCATION = '/api/location/search/?query='
API_WEATHER = '/api/location/'  # + woeid

def fetch_location(query):
    return requests.get(API_ROOT + API_LOCATION + query).json()

def fetch_weather(woeid):
    return requests.get(API_ROOT + API_WEATHER + str(woeid)).json()

def disambiguate_locations(locations):
    print("Ambiguous location! Did you mean:")
    for loc in locations:
        print(f"\t* {loc['title']}")

def display_weather(weather):
    print(f"Weather for {weather['title']}:")
    for entry in weather['consolidated_weather']:
        date = entry['applicable_date']
        high = entry['max_temp']
        low = entry['min_temp']
        state = entry['weather_state_name']
        print(f"{date}\t{state}\thigh {high:2.1f}°C\tlow {low:2.1f}°C")

def weather_dialog():
    try:
        where = ''
        while not where:
            where = input("Where in the world are you? ")
        locations = fetch_location(where)
        if len(locations) == 0:
            print("I don't know where that is.")
        elif len(locations) > 1:
            disambiguate_locations(locations)
        else:
            woeid = locations[0]['woeid']
            display_weather(fetch_weather(woeid))
    except requests.exceptions.ConnectionError:
        print("Couldn't connect to server! Is the network up?")

if __name__ == '__main__':
    while True:
        weather_dialog()

'REMOVAL OF RESIDUAL STRESSES BY LOW-TEMPERATURE ANNEALING TO PREVENT STRESS-CORROSION CRACKING OF CARBON STEELS'.lower()
'removal of residual stresses by low-temperature annealing to prevent stress-corrosion cracking of carbon steels'

str = "GOOD MORNING"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 
GOOD MORNING
good morning
Good morning
Good Morning
file = open("123.txt","rb+")
print("name of file:",file.name)
name of file: 123.txt
text = file.readlines()
print("read line:%s"%(text))

read line:[b'RFE RHG TRH YTRJJ UYJ UYJ']
file.close()
file = open("123.txt","w")
text = file.writelines("123")
print("read line:%s"%(text))
read line:None
file = open("123.txt","rb")
text = file.readlines()
print("read line:%s"%(text))

read line:[b'123']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值