17个常见的Python运行时错误,你中招了没?

深交所 vs 上交所:Level-2实时数据推送规则详解与策略适配指南 本文深度解析沪深Level-2实时数据推送规则的关键差异,包括逐笔成交、逐笔委托和10档行情接口的处理逻辑。针对高频交易策略,详细对比上交所与深交所在数据推送机制、时间戳处理及委托队列解析等方面的差异,并提供具体的策略适配方案和性能优化建议,帮助量化投资者提升跨市场交易稳定性。 阅读详情

对于刚入门的Pythoner在学习过程中运行代码是或多或少会遇到一些错误,刚开始可能看起来比较费劲。随着代码量的积累,熟能生巧当遇到一些运行时错误时能够很快的定位问题原题。下面整理了常见的17个错误,希望能够帮助到大家。

1、

忘记在if,for,def,elif,else,class等声明末尾加 :

会导致“ SyntaxError : invalid syntax ”如下:

if spam == 42
  print('Hello!')

2、

使用= 而不是 ==

也会导致“ SyntaxError: invalid syntax ”

= 是赋值操作符而 == 是等于比较操作。该错误发生在如下代码中:

if spam = 42:
  print('Hello!')

3、

错误的使用缩进量导致

“ IndentationError: unexpected indent ”、

“ IndentationError: unindent does not match any outer indetation level ”

以及“ IndentationError: expected an indented block ”

记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。该错误发生在如下代码中:

print('Hello!')
  print('Howdy!')

或者:

if spam == 42:
  print('Hello!')
print('Howdy!')

4、

在 for 循环语句中忘记调用 len()

导致“ TypeError: 'list' object cannot be interpreted as an integer ”

通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。

该错误发生在如下代码中:

spam = ['cat', 'dog', 'mouse']
for i in range(spam):
  print(spam[i])

5、

尝试修改string的值

导致“ TypeError: 'str' object does not support item assignment ”

string是一种不可变的数据类型,该错误发生在如下代码中:

spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)

而正确做法是:

spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)

6、

尝试连接非字符串值与字符串

导致 “ TypeError: Can't convert 'int' object to str implicitly ”

该错误发生在如下代码中:

numEggs = 12
print('I have ' + numEggs + ' eggs.')

而正确做法是:

numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')

numEggs = 12
print('I have %s eggs.' % (numEggs))

7、

在字符串首尾忘记加引号

导致“ SyntaxError: EOL while scanning string literal ”

该错误发生在如下代码中:

print(Hello!')

print('Hello!)

myName = 'Al'
print('My name is ' + myName + . How are you?')

8、

变量或者函数名拼写错误

导致“ NameError: name 'fooba' is not defined ”

该错误发生在如下代码中:

foobar = 'Al'
print('My name is ' + fooba)

spam = ruond(4.2)

spam = Round(4.2)

9、

方法名拼写错误

导致 “ AttributeError: 'str' object has no attribute 'lowerr' ”

该错误发生在如下代码中:

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()

10、

引用超过list最大索引

导致“ IndexError: list index out of range ”

该错误发生在如下代码中:

spam = ['cat', 'dog', 'mouse']
print(spam[6])

11、

使用不存在的字典键值

导致“ KeyError:‘spam’ ”

该错误发生在如下代码中:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

12、

尝试使用Python关键字作为变量名

导致“ SyntaxError:invalid syntax ”

Python关键不能用作变量名,该错误发生在如下代码中:

class = 'algebra'

Python3的关键字有:and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13、

在一个定义新变量中使用增值操作符

导致“ NameError: name 'foobar' is not defined ”

不要在声明变量时使用0或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着spam需要指定一个有效的初始值。

该错误发生在如下代码中:

spam = 0
spam += 42
eggs += 42

14、

在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)

导致“ UnboundLocalError: local variable 'foobar' referenced before assignment ”

在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。

这意味着你不能在定义它之前把它当全局变量在函数中使用。

该错误发生在如下代码中:

someVar = 42
def myFunction():
  print(someVar)
  someVar = 100
myFunction()

15、

尝试使用 range()创建整数列表

导致“ TypeError: 'range' object does not support item assignment ”

有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值。

该错误发生在如下代码中:

spam = range(10)
spam[4] = -1

正确写法:

spam = list(range(10))
spam[4] = -1

(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)

16、

不存在 ++ 或者 -- 自增自减操作符。

导致“ SyntaxError: invalid syntax ”

如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。

该错误发生在如下代码中:

spam = 1
spam++

正确写法:

spam = 1
spam += 1

17、

忘记为方法的第一个参数添加self参数

导致“ TypeError: myMethod() takes no arguments (1 given) ”

该错误发生在如下代码中:

class Foo():
  def myMethod():
      print('Hello!')
a = Foo()
a.myMethod()

Pixel 5 Root, 安装Xposed框架, 解锁5G教程 Pixel 5 5G手机root 教程 前几天买的手机终于到货了,现在又开始折腾了,经过我的努力,现在已经拥有root权限了。 阅读详情

相关推荐

手把手教你用Qwen-7B打造医疗大模型:从数据准备到RLHF全流程实战

本文是一篇基于Qwen-7B-Chat模型构建医疗领域大模型的实战全流程指南。文章详细拆解了从数据准备、环境搭建,到增量预训练、监督微调(SFT)以及偏好对齐(DPO)的核心技术步骤,并分享了部署与持续优化的实践经验。通过LoRA等高效微调技术,帮助开发者掌握将通用大模型改造为专业领域专家的完整方法论。

weixin_29191761的博客 132

pythonista3使用教程-Pythonista中文文档:使用Pythonista

使用Pythonista此页面概述了Pythonista的用户界面,还包含一些有用的提示和技巧,可帮助你充分利用它。Pythonista分为三个面板:脚本库,代码编辑器和交互式控制台,其中还包含文档查看器。你可以左右滑动手势在这些面板之间切换。脚本库脚本库显示你编写的所有脚本以及作为示例包含的脚本。你可以将它们作为文件名列表或代码片段预览进行查看。可以通过点击...按钮更改查看模式。要创建新脚本,...

weixin_37988176的博客 1万+

pythonista检测内容自动点击_Pythonista中文教程:100行代码实现一款远程键盘

前言最近在逛AppStore的时候看到了一个挺有意思的app叫“远程输入法”,意在使用电脑上使用键盘给iOS设备进行远程输入。出于好奇就买下来玩了玩,功能确实不错,但是总觉得少了些我想要的东西,还不够完美。那为什么不自己DIY一款远程输入法呢,正好可以学习使用Pythonista 3.3版本新添加的键盘功能!正文我们的实现思路模仿“远程输入法”设计如下:通过在Pythonista上运行服务器,从P...

weixin_32027887的博客 2409

使用Dify搭建音频文件转文本工作流

使用Dify搭建音频文件转文本工作流

zyx_bx的博客 5640

沧小海深入剖析xilinx的GTP/GTX核,掌握高速串行收发机制——第六章 接收端结构及功能说明

总目录在这哦~ https://blog.csdn.net/z123canghai/article/details/107700878 第六章 接收端结构及功能说明 子目录 6.1 RX的模拟前端 6.2 RX的OOB信号 6.3 RX的均衡器 6.4 RX的CDR 时钟数据恢复 6.5 RX时钟输出结构 6.6 RX 的极性控制 6.7 RX 的PRBS 6.8 Rx字节、字的对齐功能 6.9 Rx接收弹性缓冲区 6.10 Rx的时钟纠正 6.11 Rx接收通道绑定 6...

滄海的博客 1万+

pythonista_什么是点子? 新Pythonista指南

pythonistaWhat is pip? pip is the standard package manager for Pyhon. It allows you to install and manage additional packages that are not part of the Python standard library. This tutorial is an intr...

cumei1658的博客 1737

Android 10.0 SystemUI 屏蔽状态栏消息推送弹出的悬浮通知

在状态栏中,有一些通知类似 消息推送 弹出的 悬浮通知,弹出30秒之后会消失掉 要想屏蔽掉这些通知,首选知道这些通知是怎么产生的 通知类型 NotificationContentInflater.java 详细的介绍各种通知的类型 frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java /** * The defau

安卓兼职framework和app工程师的博客 1545

如何像Python高手(Pythonista)一样编程

  最近在网上看到一篇介绍Pythonic编程的文章:Code Like a Pythonista: Idiomatic Python,其实作者在2006的PyCon会议后就写了这篇文章,写这篇文章的主要原因是作者发现很多有经验的Pythoner写出的代码不够Pythonic。我觉得这篇文章很不错,所以将它用中文写了下来(不是逐字的翻译,中间加了一些自己的理解),分享给大家。另:由于本人...

aozhilu9748的博客 1294

总结个人关于雷达样式的见解(脉内脉间调制)

概述 雷达有各种各样的脉内脉间调制样式,对于雷达的设计者来说,不外乎三个目的: 1、增加雷达性能,如提高测距精度,增大侦察距离等; 2、雷达的工作机制决定雷达必须采用此种样式的调制,如有些SAR雷达为保证径向测距精度,需要使用脉内宽带调制信号; 3、降低雷达被电子战装备截获的概率,也就是LPI设计。 对于雷达对抗方,则只会观察到信号存在脉内及脉间的调制。对于一般的雷达信号,通常只采用脉内调制,脉间频率调制,脉间PRI调制。 脉间调制类型 1、PD雷达的脉间特征 雷达进行脉间调制的主要是PRI..

年糕的博客 3万+

[QMT量化交易小白入门]-三十五、如何将聚宽策略信号转为QMT实盘交易

Flask是一个轻量级的Web应用框架,它提供了简单而灵活的方式来构建Web应用程序。在本案例中,将使用Flask来搭建一个本地服务,用于监听来自jq2qmt.py脚本的交易信号,并根据信号执行相应的下单操作。

木头大左的博客 2702

Python 常见的17个错误分析

对于刚入门的Pythoner在学习过程中运行代码是或多或少会遇到一些错误,刚开始可能看起来比较费劲。随着代码量的积累,熟能生巧当遇到一些运行时错误时能够很快的定位问题原题。下面整理了常见的17个错误,希望能够帮助到大家 1、 忘记在if,for,def,elif,else,class等声明末尾加 : 会导致“SyntaxError :invalid syntax”如下: if spam == 42...

python学习者的博客 876

基于未来出行解决方案的场景实例:城市空中交通(UAM)的飞行路径规划与避障

本文介绍了使用Simulink进行城市空中交通(UAM)飞行路径规划与避障的仿真方法。主要内容包括:1)UAM系统架构与核心挑战;2)详细建模步骤,从城市3D环境构建到飞行器动力学模拟;3)全局路径规划(A*/RRT*)和局部避障(DWA/APF)算法实现;4)多机协同与冲突解决;5)关键场景仿真与性能评估;6)高级功能拓展方向。通过Simulink的数字孪生系统,可有效验证UAM在复杂城市环境中的可行性,为未来立体交通发展提供技术支撑。

xiaoheshang_123的博客 260

oj平台运行时错误_17个常见的Python运行时错误,你中招了没?

来源:开源中国链接:https://www.oschina.net/question/89964_62779对于刚入门的Pythoner在学习过程中运行代码是或多或少会遇到一些错误,刚开始可能看起来比较费劲。随着代码量的积累,熟能生巧当遇到一些运行时错误时能够很快的定位问题原题。下面整理了常见的17个错误,希望能够帮助到大家。1、忘记在if,for,def,elif,else,cl...

weixin_39795479的博客 898

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

17个新手常见的Python运行时错误

对初学者来说,想要弄懂Python的某些错误信息还是有困难的,下面罗列了一些常见的运行时错误:1.忘记在if, elif, else, for, while, class, def 语句末尾添加冒号(:),从而导致:“SyntaxError: invalid syntax”错误错误发生在如下类似代码里:if spam == 42 print('Hello!')2.使用=号,而不是==号,从而

追梦者的部落格 8386

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

17个新手常见Python运行时错误

原文地址:http://www.oschina.net/question/89964_62779    http://inventwithpython.com/blog/2012/07/09/16-common-python-runtime-errors/ 当初学 Python 时,想要弄懂 Python 的错误信息的含义可能有点复杂。这里列出了常见的的一些让你程序 crash 的运行

qiuyepiaoling的专栏 1万+
上一篇: Python之可迭代对象、迭代器、生成器
下一篇: 【Python机器学习实战】聚类算法——层次聚类(HAC)和DBSCAN
Python_xiaowu
博客等级 码龄5年 3096粉丝 178原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址