目录
- 1.第一个python程序
- 2.用pycharm编写程序
* - 2.1标准化输出字符串
- 2.2 强制类型转换
- 3.条件判断语句
* - 3.1 知识点
- 3.2举例
- 4.循环控制语句
* - 3.1 知识点
- 3.2 举例
- 5. 字符串
* - 5.1 知识点
- 5.2 转义字符
- 5.3 字符串切片
- 5.4 字符串拼接
- 6.列表
* - 6.1 知识点
- 6.2 列子
- 7.元组
* - 8.字典
- 9. 集合
- 10.小结
- 保存数据到Excel
- 保存数据到SQLit
- flask框架
1.第一个python程序
用win+R打开DOM命令窗口,输入以下代码:
python hello.py
提示我 name 'hello'is not defined
2.用pycharm编写程序
print("hello,world")
print("hello")
2.1标准化输出字符串
print("标准话输出语句:")
a = 10
print("a的值是",a)
age = 18
print("我的年龄为%d"%age)
print("我的国籍是%s,我的名字是%s"%("中国","小张"))
print("www","baidu","com")
print("www","baidu","com",sep=".")
print("hello word",end="")
print("hello world",end="\t")
print("python")
password = input("请输入密码:")
print("您刚才输入的密码是",password)
2.2 强制类型转换
a = input("请输入一个数字:")
print(type(a))
'''
输出结果:
请输入一个数字:1
您刚才输入的数字是1
'''
print("您刚才输入的数字是%s"%a)
a = int(input("请输入一个数字:"))
b = 100 + a
print(b)
'''
请输入一个数字:1
101 #b的值为1+101,字符1转化为了数字1
'''
3.条件判断语句
3.1 知识点
if 条件:
代码块
elif 条件:
代码块
else:
代码块
注意: 1.python中缩进表示一个层级,同一函数体 2.if条件语句后的条件不用加() 3.if 、elif、else后面有冒号:
3.2举例
import random
while True:
x = input("请输入数字0-2中的一个数字:")
if x != '0' and x != '1' and x != '2':
print("不要输入0或1或2之外的数字或字符,请输入0或者1或者2")
else:
x = int(x)
if x == 0:
print("你的输入为:%s(%d)"%("剪刀", x))
elif x == 1:
print("你的输入为:%s(%d)"%("石头", x))
elif x == 2:
print("你的输入为:%s(%d)"%("布", x))
y = random.randint(0,2)
print("随机生成的数字为:",y)
'''
遍历出所有赢的情况:
石头大于剪刀、布大于石头、剪刀大于布、平局
那么剩下的就是输的情况
'''
if x == 1 and y ==0:
print("你赢了")
elif x == 2 and y == 1:
print("你赢了")
elif x == 0 and y == 2:
print("你赢了")
elif x == y:
print("平局")
else:
print("O(∩_∩)O哈哈~,你输了")
思路:首先输入的值有三种情况,①0或者1或者2②除了0且1且2之外的所有数字③字符串,排除掉后两种情况后,就是正确的输入。其次,input返回的是字符串,所以Ⅰ在判断时0,1,2是字符串,要写成'0','1','2',逻辑关系是且,都不能是这三个字符才满足①或②要有强制类型转换,把接收到的值转换为整型;Ⅱ遍历出所有赢的情况:石头大于剪刀、布大于石头、剪刀大于布、平局,那么剩下的就是输的情况
4.循环控制语句
; 3.1 知识点
for i in sequence:
statements(s)
- sequence可以是数字也可以是字符串
- 内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。
3.2 举例
for i in range(1 , 11 , 1):
for j in range(1 , i+1 , 1):
print("%d*%d=%d"%(i , j , i*j), end="\t")
print("\n")
i = 1
while i 10:
j = 1
while j i:
print("%d*%d=%d" % (i, j, i * j), end="\t")
j = j + 1
i = i + 1
print("\n")
5. 字符串
5.1 知识点
内容摘自菜鸟教程
python字符串
字符串是 Python 中最常用的数据类型。
我们可以使用引号('或")来创建字符串。
Python 中三引号可以将复杂的字符串进行赋值。
Python 三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。
三引号的语法是一对连续的单引号或双引号(通常是成对的)。
[En]
The syntax of three quotes is a pair of consecutive single or double quotes (usually in pairs).
word = "aaa"
sentence = "aaaaa"
paragraph = \'''
hahahahah
hahhahah
ha
'''
print(word)
print(sentence)
print(paragraph)
5.2 转义字符
str_name = 'I\'m a student'
str_name1="I'm a student"
my_str = "Jason says \"I like you\""
print(str_name)
print(str_name1)
print(my_str)
5.3 字符串切片
str = "chengdu"
print(str)
print(str[0])
print(str[0:6])
print(str[0:6:2])
print(str[5:])
print(str[:5])
5.4 字符串拼接
print(str + "你好")
print("hello\nworld")
print(r"hello\nchengdu")
附:
方法描述byte.decode(encoding='utf-8',errors='strict'python3中没有decode方法,但我们可是使用bytes对象的decode()方法来解码给定的bytes对象,这个bytes对象可以由str.encode()来编码返回encode(encoding='UTF-8',errors='strict')以encoding指定的编码格式编码字符串,如果出错报一个ValueError的异常,除非errors指定的是'ignore'或者'replace'isalnum()如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回Falseisalpha()如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回Falseisdigit()如果字符串只包含数字则返回True,否则返回Falseisnumeric()如果字符串只包含数字字符,则返回True,否则返回False
join(seq)
以指定字符串作为分隔符,将seq中所有元素(的字符串表示)合并为一个新的字符串len(string)返回字符串长度Istrip()截掉字符串左边的空格或者指定字符rstrip删除字符串末尾的空格
split(str="",num=string.count(str),num=string.count(str)
以str为分隔符截取字符串,如果num有指定值,则仅截取num+1个子字符串
isdigit()和isnumeric()的区别?[待补充]
6.列表
6.1 知识点
列表可拼接
print list1 + list2
可重复输出
print list * 2
6.2 列子
products =[[0,"iphone",6888],[1,"MacPro",14800],[2,"小米6",2499],[3,"Coffe",31],[4,"Book",60],[5,"Nike",699]]
shopping=[]
while True:
x = input("输入一个商品编号:")
if x == 'q':
break
else:
for product in products:
if product[0] == int(x):
shopping.append(product)
print(shopping,end="\t")
print("\n")
enumerate()
函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
7.元组
tup1 =()
tup2 = (50)
tup3 = (50,)
tup4 = (50,60,70)
print(type(tup1))
print(type(tup2))
print(type(tup3))
print(type(tup4))
tup1 = ("abc","def",200,2020,333,444,555,666)
print(tup1[0])
print(tup1[-1])
print(tup1[1:5])
tup1 = (12,34,56)
tup2 =("abc","def")
tup = tup1+tup2
print(tup)
tup1 = (12,34,56)
print(tup1)
del tup1
print("删除后")
print(tup1)
tup1 = (12,34,56)
tup1[0] =100
8.字典
'''
dict = {"name" : "吴彦祖","age":50}
print(dict["name"])
print(dict["age"])
#访问了不存在的键
#print(dict["gender"])
print(dict.get("name","20"))
print(dict.get("gender","m"))
'''
info = {"name":"吴彦祖","age":18}
'''
print("删除前")
print(info["name"])
del info["name"]
print("删除后")
print(info["name"])
print(info)
del info
'''
'''
print("清空前%s"%info)
info.clear()
print(info)
'''
'''
info = {"name":"吴彦祖","age":18}
info["age"]=20
print(info["age"])
'''
info = {"id":1,"name":"吴彦祖" ,"age":18}
'''
print(info.keys())#返回列表
print(info.values())
print(info.items())#返回元组
for key in info.keys():
print(key)
for value in info.values():
print(value)
'''
'''
for key,value in info.items():
print("key=%s,value=%s"%(key,value))
'''
'''
mylists = ["a","b","c","d","e"]
for i,mylist in enumerate(mylists):
print(i,mylist)
'''
9. 集合
s = set([1,2,3])
print(s)
s = set([1,1,2,2,3,4])
print(s)
10.小结
可变与不可变是指能不能进行改操作,列表可以改,元组不能改。
[以前我没有那么深刻的理解,现在我理解得那么深,没有问题,我从哪里掉下来,我从哪里站起来]
[En]
[I didn't have such a deep understanding before, but now I understand so deeply, there is no problem, where did I fall, where did I get up]
; 保存数据到Excel
首先课程讲述了,如何,从网页上爬取的数据保存到excel表中。【运用saveData()函数】
保存数据到SQLit
通过建立数据库,连接数据库
conn = sqlite3.connect(dbpath)
cur = conn.cursor()
cur.execute(sql)
sqlite 数据库的创建
每次创建的时候就要创建表,所以要删除
导入数据库得过程。
运用py charm,内置sqlite数据库【存在数据库的创建问题】,进行表的增删改查【在spider.py中 saveData2DB()】
flask框架
一、路由
@app.route("/index")
def hello():
return "你好"
if _ _name_ _=='_ _main_ _':
app.run(debug = True)
使用debug模式:可以进行实时的更新
Original: https://blog.csdn.net/qq_45426640/article/details/123720647
Author: .Katherine௰
Title: 毕设学习笔记
相关阅读
Title: RuntimeError: element 0 of tensors does not require grad and does not have a grad_
今天在跑代码的过程中,因为要训练一个模型然后在测试阶段使用PGD来生成相应的adv_image来测试这个模型,结果运行到测试阶段出现下面的问题。
报错如下:
RuntimeError: element 0 of tensors does not require grad and does not have a grad_
我的代码如下:
def validate_roubst(val_loader, model, criterion, epoch, args, log=None, tf_writer=None, flag='roubst_val'):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
model.eval()
all_preds = []
all_targets = []
with torch.no_grad():
end = time.time()
for i, (input, target) in enumerate(val_loader):
if args.gpu is not None:
print('............')
input = input.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
attack_method = PGD(model, args.device)
adv_example = attack_method.generate(input, target, epsilon = 8/255, num_steps = 20, step_size = 0.01, clip_max = 1.0, clip_min = 0.0, print_process = False, bound = 'linf')
output = model(adv_example)
loss = criterion(output, target)
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), input.size(0))
top1.update(acc1[0], input.size(0))
top5.update(acc5[0], input.size(0))
batch_time.update(time.time() - end)
end = time.time()
_, pred = torch.max(output, 1)
all_preds.extend(pred.cpu().numpy())
all_targets.extend(target.cpu().numpy())
if i % args.print_freq == 0:
output = ('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
print(output)
cf = confusion_matrix(all_targets, all_preds).astype(float)
cls_cnt = cf.sum(axis=1)
cls_hit = np.diag(cf)
cls_acc = cls_hit / cls_cnt
output = ('{flag} Results: Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f} Loss {loss.avg:.5f}'
.format(flag=flag, top1=top1, top5=top5, loss=losses))
out_cls_acc = '%s Class Accuracy: %s'%(flag,(np.array2string(cls_acc, separator=',', formatter={'float_kind':lambda x: "%.3f" % x})))
print(output)
print(out_cls_acc)
if log is not None:
log.write(output + '\n')
log.write(out_cls_acc + '\n')
log.flush()
tf_writer.add_scalar('loss/test_'+ flag, losses.avg, epoch)
tf_writer.add_scalar('acc/test_' + flag + '_top1', top1.avg, epoch)
tf_writer.add_scalar('acc/test_' + flag + '_top5', top5.avg, epoch)
tf_writer.add_scalars('acc/test_' + flag + '_cls_acc', {str(i):x for i, x in enumerate(cls_acc)}, epoch)
return top1.avg
出了问题当然要找到解决方案:
2.1 方案1
大多数人是说要加这一句:
loss.requires_grad_(True) #加入此句就行了
具体做法就是:
loss = criterion(output, target)
loss.requires_grad_(True) # 加入此句在这个位置
...
loss.backward()
但是经过本人尝试,还是没有什么用,因为我在train阶段不会 出现错误,只有在test阶段就报错。
2.2 方案2
回到本质,或者从错误报告的角度来看,错误提示大致意味着元素不需要渐变。
[En]
To return to the essence, or from the point of view of error reporting, the error hint roughly means that the element does not require a gradient.
然后我仔细瞅了瞅我那段代码,发现了一个可疑之处: with torch.no_grad()
最后仔细查看了这个东西的一些使用规则(参考文献1):
with torch.no_grad()则主要是 用于停止autograd模块的工作,以起到加速和节省显存的作用,具体行为就是停止gradient计算,从而节省了GPU算力和显存,但是并不会影响dropout和batchnorm层的行为。
看到我上面加粗的字体了吧,原来使用with torch.no_grad()就不会自动求梯度了,因为我们使用PGD生成adv_image需要求梯度,所以加上with torch.no_grad()就导致了我们无法求梯度,最终出现了下面的错误。
故解决方案为:
将 with torch.no_grad() 去掉
Original: https://blog.csdn.net/wyf2017/article/details/123156380
Author: 流年若逝
Title: RuntimeError: element 0 of tensors does not require grad and does not have a grad_

SLAM学习笔记(一)Lio-sam安装与运行 ubuntu18.04+ros melodic

CTF盲水印详解

今天,我们用爱把“李焕英”带回了 2021……

MMCV之Runner介绍

gazebo+rviz中配置UR+robotiq_gripper夹爪,最详细操作过程

anaconda安装tensorflow

轻量级车道线检测

stm32的语音识别_STM32,让AI触手可及

2022年3月语音合成(TTS)和语音识别(ASR)论文月报

神经网络之BERT深度剖析

ubuntu18安装tensorflow和tensorforce

智慧高速公路车路协同系统框架及要求

什么是LIDAR(激光雷达),如何标注激光点云数据?

在Win10系统中安装tensorflow-gpu开发环境
![[算法整理]可能是最全的无监督/自监督单目深度估计方法汇总 - Part1:视频序列篇](https://www.itcode1024.com/wp-content/themes/begin/prune.php?src=https://www.itcode1024.com/wp-content/themes/begin/img/loading.png&w=280&h=210&a=&zc=1)