This is my 2nd noob question for today... so bear with me. So this is supposed to loop through 'nothing' and 'persp' while still renaming/printing After:[u’concrete_file1’] because of the continue; statement, but I just get empty brackets. I ran the same function without this:
if not (maya.cmds.ls(texture) and
maya.cmds.nodeType(texture)=='file'):
continue;
And without 'nothing' and 'persp' and it worked fine so I'm assuming the problem is in there somewhere, but after fiddling with it for a while I still don't know what it is... This'll probably be some super simplistic answer but I'm on day 2 of learning this stuff so ¯\_(ツ)_/¯
def process_all_textures(**kwargs):
pre = kwargs.setdefault('prefix');
if (isinstance(pre, str) or
isinstance(pre, unicode)):
if not pre[-1] == '_':
pre += '_';
else: pre = '';
textures = kwargs.setdefault('texture_nodes');
new_texture_names = [];
if (isinstance(textures, list) or
isinstance(textures, tuple)):
for texture in textures:
if not (maya.cmds.ls(texture) and
maya.cmds.nodeType(texture)=='file'):
continue;
new_texture_names.append(
maya.cmds.rename(
texture,
'%s%s'%(pre, texture)
)
);
return new_texture_names;
else:
maya.cmds.error('No texture nodes specified');
#Should skip over the 2 invalid objects ('nothing' & 'persp')
#because of the continue statement...
new_textures= [
'nothing',
'persp',
maya.cmds.shadingNode('file', asTexture=True)
];
print ('Before: %s'%new_textures);
new_textures = process_all_textures(
texture_nodes = new_textures,
prefix = 'concrete_'
);
print ('After: %s'%new_textures);
Before: ['nothing', 'persp', u'file1']
After: []
Also I'm just using the Maya Script Editor to write all this, is there a better editor that might be easier?
Include an else to make the statements after continue; run when if not (maya.cmds.ls(texture) and maya.cmds.nodeType(texture)=='file'): is not true.
What happens here, is that there is only that one condition. Whenever that is true, it evaluates continue; and skips the rest of the statements. However, whenever that is not true, it also skips new_texture_names.append(maya.cmds.rename(texture, '%s%s'%(pre, texture))); because that is inside the if condition.
Related
I am trying to write an if, elif else clause, so that depending on the German word ending, we can see is it should go with der, die or das.
Here is my code:
word = input ("Enter word: ")
if (word.endswith('er' 'ismus')):
print ("der")
elif (word.endswith('falt' 'heit' 'keit' 'schaft' 'ung')):
print ("die")
else (word.endswith('chen' 'lein')):
print ("das")
I have also tried using suffix with square brackets but everything goes grey when I do that and so I can assume it won't work. And clearly true and false are not adequate responses for what I need. Is there anything else I can try?
Thanks in advance!
The endswith method really only checks if the word ends with one thing, but you can do something like:
def word_ends_with_one_of(word, options):
for option in options:
if word.endswith(option):
return True
return False
Then call that with:
suffix_die = ['falt', 'heit', 'keit', 'schaft', 'ung']
suffix_der = ['er', 'ismus']
suffix_das = ['chen', 'lein']
if word_ends_with_one_of(word, suffix_die):
print ("die")
elif word_ends_with_one_of(word, suffix_der):
print ("der")
elif word_ends_with_one_of(word, suffix_das):
print ("das")
As an aside, your else clause is currently problematic, it should not have a condition attached to it (unless it's a typo and you meant to have an elif instead).
Now, even though that you be a useful function to have for other purposes, you may want to consider a more application focused method since you'll be introducing a function anyway. By that, I mean something more closely suited to your specific needs, such as:
def definite_article_for(word):
# Could also use word_ends_with_one_of() in here.
if word.endswith('er'): return 'der'
if word.endswith('ismus'): return 'der'
if word.endswith('falt'): return 'die'
:
if word.endswith('lein'): return 'das'
return None
}
Then use article = definite_article_for(my_word) to get the article you want.
Current assignment is building a basic text adventure. I'm having trouble with the following code. The current assignment uses only functions, and that is the way the rules of the assignment state it must be done.
def make_selections(response):
repeat = True
while repeat == True:
selection = raw_input('-> ')
for i, v in enumerate(response):
i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
if selection == i:
print v[1]
else:
print "There's an error man, what are you doing?!?!?"
firstResponse = 'You chose option one.'
secondResponse = 'You chose option two.'
thirdResponse = 'You chose option three.'
responses = [(0, firstResponse), (1, secondResponse),( 0, thirdResponse)]
make_selections(responses)
My intention in that code is to make it so if the user selects a 1, it will return firstResponse, if the user selects 2 it will return secondResponse, etc.
I am basically just bug testing the code to make sure it produces the appropriate response, hence the "Error man..." string, but for some reason it just loops through the error message without printing the appropriate response string. Why is this?
I know that this code is enumerating the list of tuples and I can call them properly, as I can change the code to the following and get the expected output:
for i, v in enumerate(response):
i += 1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
print i, v
Also, two quick asides before anyone asks:
I know there is currently no way to get out of this while loop. I'm just making sure each part of my code works before I move on to the next part. Which brings me to the point of the tuples.
When I get the code working, a 0 will produce the response message and loop again, asking the user to make a different selection, whereas a 1 will produce the appropriate response, break out of the loop, and move on to the next 'room' in the story... this way I can have as many 'rooms' for as long of a story as I want, the player does not have to 'die' each time they make an incorrect selection, and each 'room' can have any arbitrary amount of options and possible responses to choose from and I don't need to keep writing separate loops for each room.
There are a few problems here.
First, there's no good reason to iterate through all the numbers just to see if one of them matches selection; you already know that will be true if 1 <= selection <= len(response), and you can then just do response[selection-1] to get the v. (If you know anything about dicts, you might be able to see an even more convenient way to write this whole thing… but if not, don't worry about it.)
But if you really want to do this exhaustive search, you shouldn't print out There is an error man after any mismatch, because then you're always going to print it at least twice. Instead, you want to only print it if all of them failed to match. You can do this by keeping track of a "matched" flag, or by using a break and an else: clause on your for loop, whichever seems simpler, but you have to do something. See break and continue Statements, and else Clauses on Loops in the tutorial for more details.
But the biggest problem is that raw_input returns a string, and there's no way a string is ever going to be equal to a number. For example, try '1' == 1 in your interactive interpreter, and it'll say False. So, what you need to do is convert the user's input into a number so you can compare it. You can do that like this:
try:
selection = int(selection)
except ValueError:
print "That's not a number!"
continue
Seems like this is a job for dictionaries in python. Not sure if your assignment allows this, but here's my code:
def make_selections(response):
selection = raw_input('-> ')
print response.get(selection, err_msg)
resp_dict = {
'1':'You chose option one.',
'2':'You chose option two.',
'3':'You chose option three.'
}
err_msg = 'Sorry, you must pick one of these choices: %s'%sorted(resp_dict.keys())
make_selections(resp_dict)
The problem is that you are comparing a string to an integer. Selection is raw input, so it comes in as a str. Convert it to an int and it will evaluate as you expect.
You can check the type of a variable by using type(var). For example, print type(selection) after you take the input will return type 'str'.
def make_selections(response):
repeat = True
while repeat == True:
selection = raw_input('-> ')
for i, v in enumerate(response):
i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
if int(selection) == i:
print v[1]
else:
print "There's an error man, what are you doing?!?!?"
Are:
if statement:
if statement:
the same as
if statement:
elif statment:
and
if statement:
else statement:
the same?
If not, what's the difference?
No, they are not the same.
if statement:
if statement:
If the first statement is true, its code will execute. Also, if the second statement is true, its code will execute.
if statement:
elif statment:
The second block will only execute here if the first one did not, and the second check is true.
if statement:
else:
The first statement will execute if it is true, while the second will execute if the first is false.
The first one is different
if True:
print 'high' #printed
if True:
print 'low' #printed
than the second
if True:
print 'high' #printed
elif True:
print 'low' #not printed
and the third is invalid syntax
See tutorial.
Statement like if , else and else if are used in almost all programming languages to take a decision by the machine or software like Chrome ,Firefox and some other software....
if will be written initially in the if statement code.
else if will be executed if code if is not true.
else will be executed if none of them are true.
Below example will gives you more understanding about it.
if( something is true ){ // execute this code; }
else if( if previous condition is not true){ // then execute this code;}
else { //if none of the above are true finally execute this code. }
you can use number of else if statements between if and else, like example shown above also in the below. And remember "if" statement should start with if and ends with else
here I declared if code in two different ways.
below examples written in JavaScript ( concept apply same with Python )
Remember :
`elif` in (python) --same as-- `else if` in ( Java Script ).
print() in (python) --and-- document.write() in ( Java Script ).
Example 1:
var a=10; // declared variable with value `10`
if(a==20){ document.write("Twenty"); }
//above code is false because "a" value is not 20
else if(a==10){ document.write("Ten"); }
//above is true output comes as "Ten" a==10 //true
else if(a==10){ document.write("Forty"); }
// above also true because "a" is equal to 10 but it won't print in console
else{ document.write("None of them are correct!"); } //also not printed.
In the code above we declared var a=10 and else if a==10 is true in 2 cases, but "Ten" will be printed in console. And rest of the code will not be executed (or) run.
we can do it another way, we declare it with all if statements like below.
Example 2:
var a = 10;
if(a==10){ document.write('ten'); } // it will be printed because condition is `true`;
if(a==20){ document.write('twenty') } // not printed `false`
if(a==10){ document.write("hundred") } // this also `true` therefore printed in console.
else{ //document.write("none")} // not printed because `false`
Difference explained here.
in the " 1st example " we write code with if and else if statements , where code was terminated, because condition is true at-least one time. And rest of the code will not be executed even the condition is true.
In the "2nd example" we write code with all if statements, the code was executed in all cases and prints all true conditions in console, but in the 1st example it was not printed.
if statement:
if statement:
It is like individual conditions; each if statement is checked one after another.
The same as:
if statement:
elif statment:
It is like: the first if condition failed then check the next after the condition.
And:
if statement:
else statement:
It is like: Check the first if condition, and then execute the else block.
no, not the same.
if statement:
if statement:
second if executes whether first if executed or not.
if statement:
elif statment:
elif only executes if first if passes the statement to it. you can have any number of elif statements.
if statement:
else statement:
this is nearly same as if and elif statement. if first if condition doesn't satisfy the requirements, then it passes to the else which can be happen if the conditions not satisfied.
They are not the same. if executes if the condition is True, elif executes if the if is false and the elif is true, and else executes if the if is false.
Example:
if True:
print('This will be printed') #This will be printed
if True:
print('This will also be printed') #This will also be printed
if True:
print('This will be printed') #This will be printed
elif True:
print('This will not be printed')
if False:
print('This will not be printed')
else:
print('This will be printed') #This will be printed
I have the following code:
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
classEnd = dataList.index(breaks[i+1])
classList = dataList[classStart:classEnd+1]
classMean = sum(classList)/len(classList)
print classMean
preSDCM = 0.0
for j in range(0,len(classList)):
sqDev2 = (classList[j] - classMean)**2
preSDCM += sqDev2
SDCM += preSDCM
return (SDAM - SDCM)/SDAM
I would like to convert this code to VB.NET.
But I am not sure where the if-elseif-statement ends.
Does it end after "classStart += 1"?
I feel it a bit difficult to see where the for-next-loops end as well in Python.
The code is taken from http://danieljlewis.org/files/2010/06/Jenks.pdf
Thank you.
Yes. Python uses indentation to mark blocks. Both the if and the for end there.
In Python, where your indented block ends, that is exactly where your block will end. So, for example, consider a bit simpler code:
myName = 'Jhon'
if myName == 'Jhon':
print(myName * 5)
else:
print('Hello')
Now, when you run this code (make sure to run it from a separate module, not from the interactive prompt), it will print 'Jhon' five times (note that Python will treat the objects exactly as they are specified, it won't even bother to try to convert the variable myName's value to a number for multiplication) and that's it. This is because the code block inside of the if block is only executed. Note that if the else keyword was put anywhere but just below the if statement or if you had mixed the use of tabs and spaces, Python would raise an error.
Now, in your code,
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
See, where the indent of for's block of code starts? One tab, so, everything indented one tab after the for statement, will be inside of the for block. Now, obviously, the if statement is inside of the for statement, so it's inside the for statement. Now, let's move to next line, classStart = 0 -- this is indented two tabs from the for statement and one tab from the if statement; so it's inside the if statement and inside the for block. Next line, you have an else keyword indented just one tab from the for statement but not two tabs, so it's inside the for statement, and not inside the if statement.
Consider putting curly-braces like these if you have coded in another language(s) before:
for i in range(0,numClass)
{
if breaks[i] == 0
{
classStart = 0
}
else
{
classStart = dataList.index(breaks[i])
classStart += 1
}
}
The simple differences are that you are not required to put parenthesis for your expressions, unless, you want to force operator precedence rule and you don't need those curly braces, instead, just indent them equally.
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
# end if
That is right. In Python, the indentation delimitates your condition block, differently from e.g., Matlab, where you would have to insert an "end" to mark the block's end. I like both ways though!
For a given code:
pattern = r'(?:some_pattern)'
def find(seq):
ret = []
while True :
m= pattern_re.match(seq)
if not m :
break
myseq= m.group(2)
assert len(myseq)%3 == 0
assert len(myseq) > 6
ret.append(myseq)
pos = m.end()
return ret
sequence = 'some sequence'
my_seq = find(sequence)
this returns ret in which only first assert function is taken and not the second . Any solution for it ?
the question simply is how to make code consider both the assert function
For starters, why are you using assert?
As soon as the first assert fails an AssertionError is raised and execution of the program stops.
You should be using normal conditionals. Besides that, there is so much wrong with or unusualy with this code I seriously suggest you to read the Python tutorial at http://docs.python.org/tutorial/
Pointers:
print statement after return
usage of assert instead of conditionals
the unnecessary while loop
no proper indenting
Furthermore you pasted an example that plainly does not execute since the indenting is wrong and the function called on the last line does not exist in your code. Please be more precise if you want help :-)