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.
Related
I have a class for data entry that requires a lot of input from the user. I use it to semi-automate the process of putting stuff in the db where it is possible.
My instinct is to put it in my model classes, and write tests on it, but it would be an insane amount of work, and I have a lot of raw_input() functions and logic loops that I don't know how to test or what to do with.
Should I keep this module separate or try to include it in the model classes?
def define(self, word=False, word_pk=False):
'''Defining a word, there may be language specific elements to edit in here'''
try:
if word_pk:
word = Word.objects.get(id=word_pk)
else:
word = Word.objects.get(language__name=self.language_ISO, name=word)
except:
return "Word lookup failed for word=%s word_pk=%s\n" % (word, word_pk)
print "\n\tThe Word is: '%s'...\n" % (word)
wiktionary_list = word.wiktionary_lookup(self.wiktionary_prefix, self.driver)
wn_tuple = word.wn_lookup()
while choice("Would you like to add a/another definition for '%s'?: " % word):
#Ask the user if they want to use the wn output for definitions, make them select which ones
if choice("Would you like to choose a wordnet definition?: "):
chosen_defs = ask_input("Which ones? (choose all that apply with a space between numbers): ")
chosen_defs = [int(i) for i in (chosen_defs.split())]
#Wornet only gives part of speech and definition information so I need to split that here.
for i in chosen_defs:
#Print_n_save function will return False if it exits successfully, so there is an option to repeat this loop if the user makes a mistake somewhere
repeat = True
while repeat:
tup = wn_tuple[i]
print "\n(%s) - %s\n" % (tup[0], tup[1])
audio_tup = self.add_audio(word)
picture_tup = self.add_picture(word)
new_definition = Definition()
new_definition.word=word
new_definition.part_speech= tup[0]
new_definition.definition=tup[1]
new_definition.def_source="Wordnet"
new_definition.add_pronunciation()
new_definition.word_audio=audio_tup[0]
new_definition.audio_source=audio_tup[1]
new_definition.picture=picture_tup[0]
new_definition.pic_source=picture_tup[1]
repeat = self.print_n_save(new_definition)
elif choice("Would you like to choose a wiktionary definition?: "):
choose_defs = ask_input("Which ones would you like to choose? (Numbers separated by spaces): ")
chosen_defs = [int(i) for i in choose_defs.split()]
for i in chosen_defs:
#Print_n_save function will return False if it exits successfully, so there is an option to repeat this loop if the user makes a mistake somewhere
repeat = True
while repeat:
print "\n%s\n" % (wiktionary_list[i])
audio_tup = self.add_audio(word)
picture_tup = self.add_picture(word)
new_definition = Definition()
new_definition.word=word
new_definition.get_pos()
new_definition.definition=wiktionary_list[i]
new_definition.def_source="Wiktionary"
new_definition.add_pronunciation()
new_definition.word_audio=audio_tup[0]
new_definition.audio_source=audio_tup[1]
new_definition.picture=picture_tup[0]
new_definition.pic_source=picture_tup[1]
repeat = self.print_n_save(new_definition)
else:
#Print_n_save function will return False if it exits successfully, so there is an option to repeat this loop if the user makes a mistake somewhere
repeat = True
while repeat:
#Asking for definition, inputting raw from some internet source
definition = ask_input("What is the definition?: ")
definition_source = ask_input("What is the source of the definition?: ")
audio_tup = self.add_audio(word)
picture_tup = self.add_picture(word)
new_definition = Definition()
new_definition.word=word
new_definition.get_pos()
new_definition.definition=definition
new_definition.def_source=definition_source
new_definition.add_pronunciation()
new_definition.word_audio=audio_tup[0]
new_definition.audio_source=audio_tup[1]
new_definition.picture=picture_tup[0]
new_definition.pic_source=picture_tup[1]
repeat = self.print_n_save(new_definition)
Don't try to force a raw python function into a single box.
What you should have done (a long long time ago), is separate it out into separate functions so it would be easier to test and figure things out.
Since you're asking for user input, websites do that through forms, so you're going to need a form - or a form wizard/set/whatever.
That form is going to need at least one view to handle it, so you might need to write that too, or use a generic view.
Who knows, the model might even need to do something post processing (I didn't really read the code)
I would put this into management/commands. Just wrap your functions into a BaseCommand class and you are good to go. And here is how to make testing.
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?!?!?"
I'm a beginner programmer, learning in Python, but I was pretty sure I had a decent grasp of how to make most things run, until I came across this. As i was attempting to run a piece of code with an if..then statement nested inside, Python decided to throw me a curve ball by not running the if...then statements. When I try to run the program, all it does is continually run the one line of code I have inside the while loop, coming before the if...then statement.
Here's the code:
def deg_or_rad():
global deg_rad
deg_rad = False
while deg_rad == False:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower
if query == "deg" or \
query == "degrees":
deg_rad = "deg"
print "Cool! I like degrees."
elif query == "rad" or \
query == "radians":
deg_rad = "rad"
print "Cool! I like radians."
else:
"Umm... I'm confused..."
I've tried a few other variables for the while loop, such as:
def deg_or_rad():
global deg_rad
deg_rad = False
while_variable = True
while while_variable == True:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower
if query == "deg" or \
query == "degrees":
deg_rad = "deg"
print "Cool! I like degrees."
while_variable = False
elif query == "rad" or \
query == "radians":
deg_rad = "rad"
print "Cool! I like radians."
while_variable = False
else:
"Umm... I'm confused..."
Anyone have any ideas? I'm really confused by this point.
First, in this line:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower
you're not calling the .lower() method, because there are no (). You're just setting query equal to the lower method of strings, so you're always taking the else branch.
Second, in this line:
"Umm... I'm confused..."
You're not printing anything, you just made a string. So even though that branch is being taken, you're not doing anything you can see.
This is a combination of two things that make it seem like nothing is happening.
To lower a string, you do s.lower(), not s.lower. s.lower is a method.
What you're doing is you're assigning that method to query. So, none of the ifs will ever match. This means the else branch is executed. But, you don't print "Umm... I'm confused...", you just have the string itself there. This leads to you not getting any output.
couple of things
lower is a function call, you should use it like lower()
You are not printing the string in the else: statement. So it appears like nothing is happening even though you are getting here. This is because that function itself will not match your previous conditions (the results of the function may)
Don't say while_variable == True or deg_rad == False just use while_variable or not deg_rad respectively. (This isn't really part of the problem, just bad style.)
You could trying printing things to try and debug where your function is deviating from expected behavior to try and narrow it down. For instance if you put in a debug print just after you capture query input you could see that it wasn't what you were hoping for.
example:
def deg_or_rad():
global deg_rad
deg_rad = False
while not deg_rad:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower()
if query in ("deg", "degrees"):
deg_rad = "deg"
print "Cool! I like degrees."
elif query in ("rad", "radians"):
deg_rad = "rad"
print "Cool! I like radians."
else:
print "Umm... I'm confused..."
raw_input("Are you working in 'degrees' or 'radians'? > ").lower
You haven't called the lower method, so at this point query is always going to be a bound method object (something along the lines of <built-in method lower of str object at 0x1001a0030>).
Furthermore, in your else clause you have not used print, so the string is created then thrown away without being displayed.
Thus you get the raw_input, then nothing.
As I know, "continue" will jump back to the top of the loop. But in my case it's not jumping back, continue don't like me :(
for cases in files:
if ('python' in cases.split()):
execute_python_scripts(cases.split())
elif run_test_case(cases.split()):
continue
else:
logger("I am here")
break
In my case run_test_case() gives 1, 2, 3, 4 etc... But it always performs first(1) and jump to the else part. So I am getting the "I am here" message. It should not work like this. As I am using "continue", it should jump to the for loop.
Following is the run_test_case():
def run_test_case(job):
for x in job:
num_of_cases = num_of_cases - 1
test_type = x.split('/')
logger(log_file,"Currently "+ x +"hai!!")
if test_type[0] == 'volume':
backdoor = test_type[1].split("_")
if backdoor[0] == 'backdoor':
return get_all_nas_logs()
else:
if perform_volume_operations(x,num_of_cases) == False:
return False
else:
logger(log_file,"wrong ha!!")
Why is it always going to the else part, without jumping back to the for loop? Thanks in advance.
Here elif run_test_case(cases.split()): you are calling the run_test_case method, that will run your code to evaluate the result for the elif condition.
It only enters the block delimited by elif (in your case, continue), if the result of that method evaluates to True, otherwise it will jump to the else clause.
The problem is probably in your run_test_case code, that is never returning True, and so you'll never get the behavior that you're expecting.
It's hard to say without knowing exactly what you want to accomplish, but I'd say that you're missing a return True in the end of that code, meaning, if everything executes correctly right until the end, you want it to return True... but I'm only guessing here, you need to think about what that method is supposed to do.
In python an if or elif clause is evaluated for not only the True and False constants, but more generally for True-like and False-like values. None, for instance, is a false-like value, a non-empty string is a true-like value, etc.
Check this from the documentation on values that are considered true or false:
http://docs.python.org/library/stdtypes.html
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 :-)