Is there a way to use a for loop to automate a function? e.g
if i write..
def foo (a number):
return (a number)
for i in range(10):
print(foo('1{}').format(str(i))
Comes out with AttributeError: 'NoneType' object has no attribute 'format'
Well, I am changing this because it didn't really answer your question, but its a lot simpler than you are trying to make it. Really all it is, is a function that is called and updated by a loop. So, let's try that:
def foo(num):
print(num)
num = 0
for i in range(1,10,1):
foo(num + i)
So, what I've done here is taken your script and changed it. To start with, "a number" as a parameter will cause syntax errors while trying to define them. So I changed it to "num".
Then, I've used a simple print statement to print out the number that is coming in. This could be removed if you just wanted a loop with it cycling it through numbers. And of course changing "foo(num + i)" to "print(num + i)".
The "num = 0" sets a variable so we can use it later.
Regards,
Jerry
Related
I will provide the code for a portion. It doesn't continue after using commands within a while block. I think it is the code block text = get_audio().lower() that is giving me the error.
def process_text():
pass
if __name__ == "__main__":
assistant_speaks('''Hello, I am a Virtual Assistant.
I am here to make your life easier. You can command me to perform
various tasks such as calculating sums or opening applications.
Please tell me who you are.''')
name = 'are'
name = get_audio()
assistant_speaks("Hello, " + name + '.')
while 1:
assistant_speaks("What can i do for you?" + name + '.')
text = get_audio().lower()
if text == 0:
continue
if "exit" in str(text) or "bye" in str(text) or "sleep" in str(text):
assistant_speaks("Ok bye, " + name + '.')
break
# calling process text to process the query
process_text()
def process_text():
try:
if 'search' in input or 'play' in input:
# a basic web crawler using selenium
search_web(input)
return
elif "who are you" in input or "define yourself" in input:
speak = '''Hello, I am a virtual assistant.
I am here to make your life easier. You can command me to perform
various tasks such as calculating sums or opening applications.'''
assistant_speaks(speak)
return
Basically, it doesn't answer any questions when I ask the elifs. Past the try:
Does anyone have any ideas?
There are at least three mistakes you should correct in order to get the behavior you want from your program:
Replace input with text inside the try block. In Python, input is a built-in function, not a string. You already assigned the user's answer to the variable text, so why not use that one? :)
Define your process_text function before you call it. Practically, you should move the line where you call process_text() somewhere after the definition of that function.
There are also a couple of indentation errors, and the most important happens when you call the process_text() function: you should un-indent that line back one level, otherwise it will be executed inside the if "exit" in ... block.
You should also define process_text before the while loop, because you just need to define it once.
I am trying to run the seq2seq translate example present on Tensorflow website and getting following error. I am using tensorflow-gpu==1.1.0
ValueError: Attempt to reuse RNNCell
with a different variable scope than its first use.
First use of cell was with scope
'embedding_attention_seq2seq/embedding_attention_decoder/attention_decoder/gru_cell',
this attempt is with scope 'embedding_attention_seq2seq/rnn/gru_cell'.
Please create a new instance of the cell if you would like it to use a
different set of weights. If before you were using:
MultiRNNCell([GRUCell(...)] * num_layers), change to:
MultiRNNCell([GRUCell(...) for _ in range(num_layers)]). If before
you were using the same cell instance as both the forward and reverse
cell of a bidirectional RNN, simply create two instances (one for
forward, one for reverse). In May 2017, we will start transitioning
this cell's behavior to use existing stored weights, if any, when it
is called with scope=None (which can lead to silent model degradation,
so this error will remain until then.)
On github people were suggesting to change the add the reuse argument to cell as follows :
def single_cell():
return tf.contrib.rnn.GRUCell(size, reuse = tf.get_variable_scope().reuse)
if use_lstm:
def single_cell():
return tf.contrib.rnn.BasicLSTMCell(size, reuse = tf.get_variable_scope().reuse)
cell = single_cell()
if num_layers > 1:
cell = tf.contrib.rnn.MultiRNNCell([single_cell() for _ in range(num_layers)])
But still I am getting the same error. What's the issue and how to resolve it ?
Any help is highly appreciated.
P.S: A similar post was there on stackoverflow,but that solution didn't work for me and since the version of TF is different, I created a new post.
In my app i need to allow the user to add their own math formulas, can use operators and call variables. There is anyway to validate if a user write wrong a variable or a unknown variable to show an error?
I have and example here, you have some scope variables in the top of the controller. A minor difference, if I insert an invalid variable in the example it shows null, but in my code appears in blank.
Any suggestions?
Well honestly, if you weren't lazily throwing this stuff in eval, you could easily parse it yourself I recon.
How about removing all whitespaces, and interating over every single character?
I mean as long as there are no variables like aa or ab, you can just check like.
for (var i = 0; i < answer.length ; i++) {
if (!isvalidParamOrOperator(answer[i])) {
//can show error at position i+1;
return false;
}
}
with isValidParamOrOperator being something like
function(str) {
return "1234567890ab".indexOf(str);
}
Of course it becomes a little bit more complicated at longer params, but you'd be able to create something that splits on all operators like + - spaces & numbers. And then you'll have a list of all params which you can check. which should probably be checked on an array instead of my current suggestion, but this shouldn't be hard after you implement something like this.
So I'm just starting to learn Eiffel. One of the first exercises in the book I'm using says to make a function that does base^exp without using ^. I've copied my code below.
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
create power(2;3)
printf("2 to the power of 3 is " + answer)
end
power(base : REAL; exp : INTEGER) : REAL
-- computers base raised to the bower of exp without using ^
local
remain : INTEGER
do
remain := exp
if remain = 0 then
result := 1
else
from
until
remain = 0
loop
result := result * result
remain := remain -1
end
end
end
end
How do I use this? Do I need it on the same level as feature{NONE}'s make? I know how I'm calling it is wrong, and I can't find anything in the chapter I just read, or online on how to pass parameters into it or how to use it's results.
There are several issues with the original code:
create is used to create an object, but you are not going to create anything, but to get a result of a computation of the function power by calling it. Therefore the keyword create is not needed.
You are using an entity answer to report the result of evaluation on a screen. However it is not declared anywhere. I believe the proper place would be a local variable declaration section.
The entity answer is not initialized to the result of the function power. This is usually done by an assignment instruction.
Feature arguments are separated by a comma, not by a semicolon.
From the original code it's unclear what is the type of the variable answer. Assuming it matches the type of the function power, before adding it to a string, it needs to be converted to a string. This is done by calling the feature out.
The standard feature for printing a string to a console is print, not printf.
Combining the critical points above, we get
make
-- Run application.
local
answer: REAL
do
answer := power(2, 3)
print ("2 to the power of 3 is " + answer.out)
end
After that the code can be compiled. Now less critical points:
It is a good style to put features to a dedicated feature clauses, so I would add a line like feature -- Basic operations before the feature power.
The implementation of the feature power has at least two problems. I'm not going to detail them here, but would give two hints instead:
by default numeric Result is initialized to 0, this needs to be taken into account for operations that use it without first assigning any other value
even though an argument base is passed to the function power it remains unused in the original version of the code
def copy_file(from_file,to_file):
content = open(from_file).read()
target = open(to_file,'w').write(content)
print open(to_file).read()
def user_input(f1):
f1 = raw_input("Enter the source file : ")
user_input(f1)
user_input(f2)
copy_file(user_input(f1),user_input(f2))
What is the mistake in this ? I tried it with argv and it was working.
You're not calling the function user_input (by using ()). (fixed in question by OP).
Also, you need to return a string from user_input. currently you're trying to set a variable f1 which is local to the function user_input. While this is possible using global - I do not recommend this (this beats keeping your code DRY).
It's possible to do something similar with objects by changing their states. String is an object - but since strings are immutable, and you can't have the function change their state - this approach of expecting a function to change the string it's given is also doomed to fail.
def user_input():
return raw_input("Enter the source file :").strip()
copy_file(user_input(),user_input())
You can see user_input does very little, it's actually redundant if you assume user input is valid.