我正在尝试在 python3 中编写一个简单的递归函数。在学习 OO Java 时,我也想编写涉及对象的 Python 代码。下面是我的代码。我提示用户输入一个数字,屏幕应该显示每个小于 5 的整数。
class Recursion:
@staticmethod
def recursive(x):
if (x>5):
print (x)
recursive(x - 1)
def main(self):
x = int(input('Enter a number for recursive addition: '))
recursive(x)
Run Code Online (Sandbox Code Playgroud)
但是,当我在终端上运行它时,它会显示:“NameError: name 'recursive' is not defined”。这是错误的样子:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from Recursion import *
>>> a = Recursion()
>>> a.main()
Enter a number …Run Code Online (Sandbox Code Playgroud) 我在使用以下 Python 代码时遇到问题:
class Methods:
def method1(n):
#method1 code
def method2(N):
#some method2 code
for number in method1(1):
#more method2 code
def main():
m = Methods
for number in m.method2(4):
#conditional code goes here
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我得到
NameError: name 'method1' 未定义。
如何解决此错误?
我一直在关注这个我在网上找到的关于深度学习中的语音分析的教程,它一直给我名字错误。我对python很陌生,所以我不确定如何定义它。但是 train_test_split 是默认的一种分割数据的方法,train_test_split 是导入的。
这是代码:
'''
import numpy as np
import pandas as pd
import os
import seaborn as sns
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('fivethirtyeight')
from tqdm import tqdm
print(os.listdir("../input"))
from keras import Sequential
from keras import optimizers
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential,Model
from keras.layers import LSTM, Dense, Bidirectional, Input,Dropout,BatchNormalization,CuDNNLSTM, GRU, CuDNNGRU, Embedding, GlobalMaxPooling1D, GlobalAveragePooling1D, Flatten
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints
from …Run Code Online (Sandbox Code Playgroud) 严格按照文档中的示例完成此错误.并且你无法在任何地方找到任何关于它的澄清,无论是长篇文档页面,google还是stackoverflow.另外,阅读optparse.py显示OptionGroup在那里,这增加了混乱.
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
>>> from optparse import OptionParser
>>> outputGroup = OptionGroup(parser, 'Output handling')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'OptionGroup' is not defined
Run Code Online (Sandbox Code Playgroud)
我敢打赌,有人发现我的错误不到1分钟.:)
是的,这意味着我知道答案,但是因为这花了我很长时间才发现我想在这里"记录"它.
我一直在阅读和重新阅读IPython文档/教程,我无法弄清楚这段特殊代码的问题.看起来这个函数dimensionless_run对于传递给每个引擎的命名空间是不可见的,但我很困惑,因为函数是在__main__全局命名空间中定义的,并且清晰可见.
wrapper.py:
import math, os
def dimensionless_run(inputs):
output_file = open(inputs['fn'],'w')
...
return output_stats
def parallel_run(inputs):
import math, os ## Removing this line causes a NameError: global name 'math'
## is not defined.
folder = inputs['folder']
zfill_amt = int(math.floor(math.log10(inputs['num_iters'])))
for i in range(inputs['num_iters']):
run_num_str = str(i).zfill(zfill_amt)
if not os.path.exists(folder + '/'):
os.mkdir(folder)
dimensionless_run(inputs)
return
if __name__ == "__main__":
inputs = [input1,input2,...]
client = Client()
lbview = client.load_balanced_view()
lbview.block = True
for x in sorted(globals().items()):
print x
lbview.map(parallel_run,inputs) …Run Code Online (Sandbox Code Playgroud) 我正在尝试设置Action Mailer,以便在我的开发环境中为Devise发送重置密码电子邮件.我在启动本地服务器时收到以下错误:未定义的局部变量或方法`"smtp",在我的代码中引用"address:"smtp.gmail.com""行.这是我在development.rb文件中添加的Action Mailer代码:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: “smtp.gmail.com”,
port: 587,
domain: ENV["GMAIL_DOMAIN"],
authentication: “plain”,
enable_starttls_auto: true,
user_name: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]
}
Run Code Online (Sandbox Code Playgroud)
我在根目录中的.env文件中设置了环境变量.谢谢!
这是我在SO的第一个问题:)
我对RoR很新,我尝试了解PINGOWebApp,你可以在这里找到https://github.com/PingoUPB/PINGOWebApp.他们在app/services /(例如number_question.rb,text_question.rb)中的不同类型的问题中指定了他们的"问题"模型(app/models/question.rb),所有问题都继承自app/services/generic_question.rb:
class GenericQuestion < Delegator
def initialize(question)
super
@question = question
end
def __getobj__ # required
@question
end
def __setobj__(obj)
@question = obj # change delegation object
end
def to_model
@question.to_model
end
def has_settings?
false
end
def add_setting(key, value)
@question.settings ||= {}
@question.settings[key.to_s] = value.to_s
end
def self.model_name
Question.model_name
end
def self.reflect_on_association arg
Question.reflect_on_association arg
end
alias_method :question, :__getobj__ # reader for survey
end
Run Code Online (Sandbox Code Playgroud)
这是我的第一个问题:
1)由于没有服务生成器,他们必须手动创建app/service /中的所有ruby文件,不是吗?或者还有其他什么方式?
2)我分叉了项目并手动添加了另一个服务,名为dragdrop_question.rb,并将其集成到question_controller.rb中:
class QuestionsController < ApplicationController
...
def new
@question_single …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个简单的脚本,该脚本将从命令行获取文件名并将该文件转换为另一种格式。下面是我开始使用的一小段简单的代码片段,但我不断收到此错误:
NameError: name 'file_name' is not defined
这是代码,我在使用 python 2.7.10 的 Mac 上。
#!/usr/bin/env python
import sys
import argparse
parser = argparse.ArgumentParser(description='Convert Hex Files')
parser.add_argument('-f', dest=file_name, help='Please Enter the Path to Your File.', type=string)
parser.add_argument('-n', dest=line_length, help='Enter The Desired Line Length.', type=int)
args = parser.parse_args()
print args.file_name
print args.line_length
Run Code Online (Sandbox Code Playgroud) 我需要在特殊情况下捕获NameError.但我不想捕获NameError的所有SubClasses.有没有办法实现这个目标?
# This shall be catched
begin
String::NotExistend.new
rescue NameError
puts 'Will do something with this error'
end
# This shall not be catched
begin
# Will raise a NoMethodError but I don't want this Error to be catched
String.myattribute = 'value'
rescue NameError
puts 'Should never be called'
end
Run Code Online (Sandbox Code Playgroud) NameError Traceback (最近一次调用最后一次) C:\Users\VAISHN~1\AppData\Local\Temp/ipykernel_6520/2922578464.py in 3 'kernel': ['rbf']} 4 ----> 5 optimization_params=GridSearchCV ( 6 SVC(), 7 param_grid,
NameError:名称“GridSearchCV”未定义
这是我的代码:
param_grid={'C': [0.5,1,10,100],
'gamma': ['scale',1,0.1,0.001,0.0001],
'kernel': ['rbf']}
optimal_params=GridSearchCV(
SVC(),
param_grid,
cv=5,
scoring='accuracy',
verbose=0
)
optimal_params.fit(X_train_scaled,y_train)
print(optimal_params.best_params_)
Run Code Online (Sandbox Code Playgroud) nameerror ×10
python ×7
actionmailer ×1
argparse ×1
controller ×1
devise ×1
email ×1
function ×1
gridsearchcv ×1
ipython ×1
oop ×1
optparse ×1
python-3.x ×1
recursion ×1
rescue ×1
ruby ×1
service ×1
svm ×1