How to structure optional parts of a function? - python-3.x

Apologies for the horrible title, but I do not know the proper wording for it, which is part of the problem.
Currently I am making some functions in python with a general structure like this:
def printfunction(parameter1, parameter2, option1=False,option2=False):
print(f"Stuff that always happens+{parameter1}")
if option1 == False and option2 == False:
print(f"Basic Functionality+{parameter2}")
if option1 == True:
print("Option1")
if option2 == True:
print("Option2"
if option1 == True and option2 == True:
print(f"Option 1 and 2+{parameter2}")
So I would like a function that executes it's basic functionality, but if one or multiple of a set of Boolean keywords are set to True, I want it to execute some other functionality (or the original plus some new) and with only 2 "option" keywords the way I did it above works perfectly fine, but if one wants a lot of options like this, the function gets filled with "if option==False/True" statements, making very messy code.
So my question is: Is there a more efficient way of having a function that can execute multiple options? While sharing the initial parameters and some parts of the function.
Or am I just doing this all wrong and should I use a class with different methods?
Thanks in advance for any reply

Related

how to use ternary operator in mustache template

I have a scenario where I am getting {{isdone}} value with Boolean data.
I want to be printed as "pending" for false value and "Done" for true.
I'm using below code, Which isn't working.
{{isdone}} == false ? "pending" : "Done"
Use the ^ block for else.
You can (now) use the ^ block for an else or false condition. Something like this should work:
{{#isdone}}Done{{/isdone}}{{^isdone}}pending{{/isdone}}
Or as a more readable multi-line block of code:
{{#isdone}}
Done
{{/isdone}}
{{^isdone}}
pending
{{/isdone}}
As long as you have control of your context data, correct way is to pass another variable, that will already contain pending or Done beforehand.
If you don't have control over the data, then maybe moustache isn't good for you as you may need template engine that can have some more logic in it to transform data a bit.
You might want to register a ternary helper for that
Handlebars.registerHelper("ternary", function (condition, trueValue, falseValue, options) {
return condition ? trueValue : falseValue;
});
and then in your templates use it like
{{ternary isdone "Done" "pending"}}

How to check if a certain part of an input is in a list of possible inputs?

Sorry if this has been asked before, I couldn't find the exact answer or a close-enough in other questions.
I want to make a program that checks if any part of a users input is matching to another possible input in a list. And if part of that input was something in a list, that part of the input could be saved as another variable.
correct = ["game","code","text"]
command = input("> ")
if command == "open" + something in correct:
name = thing in correct
doSomething()
So if the command was 'open text', then name would be 'text'.
Is this even possible? Again, sorry if this has already been asked, and sorry if this is rambling and makes no sense.
Assumning you expect the command and its parameters to be separated by a space (or multiple spaces for multiple parameters), you could do this:
correct = ["game","code","text"]
command = input("> ")
subcommands = command.split(" ")
if subcommands[0] == "open" and subcommands[1] in correct:
name = subcommands[1]
doSomething()
This gets more tricky if parameters are supposed to contain spaces themselves, but for simple one-word params, this should do.

Spock label combinations

There | are | so many | Spock | spec examples of how to use its labels, such as:
// when -> then label combo
def "test something"() {
when:
// blah
then:
// blah blah
}
Such label combinations as:
when -> then
given -> when -> then
expect
given -> expect
But nowhere can I find documentation on what the legal/meaningful combinations of these labels are. For instance, could I have:
def "do something"() {
when:
// blah
expect:
// blah
}
Could I? I do not know. What about:
def "do something else"() {
when:
// blah
then:
// blah
expect:
// blah
where:
// blah
}
Could I? Again, I do not know. But I wonder.
I am actually an author of one of the tutorials you have mentioned. I think the best to answer your question would be to really understand what particular labels are for. Maybe then it would be more obvious why certain combinations make sense and other do not. Please refer to original documentation http://spockframework.github.io/spock/docs/1.0/spock_primer.html. It explains really well all labels and their purpose. Also it comes with this diagram:
Which I hope should already tell you a lot. So for instance having both when and expect labels makes not much sense. The expect label was designed to substitute both when and then. The reasoning behind it is well explained in the documentation:
An expect block [...] is useful in situations where it is more natural to describe stimulus and expected response in a single expression.
Spock itself will not allow you to use this combination. If you try to execute following code.
def "test"() {
when:
println("test")
expect:
1==1
}
You will receive an error message like this.
startup failed:
/Users/wooki/IdeaProjects/mylibrary/src/test/groovy/ExampleTest.groovy:
13: 'expect' is not allowed here; instead, use one of: [and, then] #
line 13, column 9.
To my surprise the second of your examples works. However I believe there is really not much gain of using expect here instead of and as I would normally do.
def "do something else"() {
when:
// stimulus
then:
// 1st verification
and:
// 2nd verification
where:
// parametrization
}
The only reason to have expect or and after then is to separate code responsible for verifying the result of executing the code inside when label. For instance to group verifications that are somehow related to each other, or even to separate single verifications but to have a possibility of giving them a description using strings that can be attached to labels in Spock.
def "do something else"() {
when:
// stimulus
then: "1 is always 1"
1 == 1
and: "2 is always 2"
2 == 2
}
Hence, since you are already stating that verification part of the test began (using then block) I would stick to and label for separating further code.
Regarding where label. It works sort of as a loop indicator. So whatever combinations of labels you use before you could always put at the end the where label. This one is not really a part of a single test run, it just enforces the test to be run a number of times.
As well it is possible to have something like this:
def "test"() {
given:
def value
when:
value = 1
then:
value == 1
when:
value = 2
then:
value == 2
}
Using the above, just make sure that your test is not "testing too much". Meaning that maybe a reason why you use two groups of when-then makes a perfect excuse for this test to be actually split into two separate tests.
I hope this answered at least some of your questions.

Pyramid Chameleon Tal:condition 'Not' issue

I am trying to display conditional text in a Pyramid Chameleon template. Basically, checking if the dictionary key 'maxed_out_alerts' is empty (false) or has a string 'yes' in it.
<p tal:condition="not:maxed_out_alerts"><h3>Maxed Out.</h3></p>
<p tal:condition="maxed_out_alerts"><h3>Not Maxed Out</h3></p>
When 'maxed_out_alerts' is an empty string, 'Maxed Out' is only displayed (correctly). However, If 'maxed_out_alerts' contains 'yes' string both 'Maxed Out' and "Not Maxed Out' are displayed (incorrectly).
It seems that the NOT is always evaluated to a true condition. It should display one or the other messages not both. What am I doing wrong? thanks
For TAL conditionals in python you can say python: and then use a python syntax conditional
<p tal:condition="python:len(maxed_out_alerts) > 0"><h3>Maxed Out.</h3></p>
It could help if you save boolean state in a boolean variable. By storing this information in a string you run into such problems you are facing right now. That's what builtin python types are made for - use them.
As a pyramid developer I would advice to move the logic to evaluate the current value of maxed_out_alerts into a string into a view method and pass the computed string in a dictionary to the renderer/template. This way you can even create tests for the view logic - any pyramid tutorial, simple or advanced shows you how to do that.
A good start for any simple logic - imagine logic gets more complicated or you even have to translate the text for the template.
#view_config(name="yourname", renderer='templates/yourtemplate.pt')
def myview(request):
"""
#get boolean state from model
#could be that you want to have it the other way round
#or do it by using python ternary operator - a if test else b
if model['maxed_out_alerts'] == True:
maxed_out_alerts = 'Maxed Out'
else:
maxed_out_alerts = 'Not Maxed Out'
return dict(maxed_out_alerts = maxed_out_alerts)
In your Template
<h3 tal:content="maxed_out_alerts">text for maxed out alerts</h3>
or
<h3>${maxed_out_alerts}</h3>

How to write a compound IF statement checking two sets of two values

I know the title is confusing, but I can't figure our how to word it properly. I'm trying to figure out how to properly format a compound conditional in an IF statement in Excel. It's for a school project that's due tomorrow.
I already have something like this
=if(AND(b152="oval.jpg",c152="q'")OR(AND(b152="triangle.jpg", c153="p'")), "Correct", "Incorrect")
In psuedocode I want it to run something like this:
if (b152=="oval.jpg" && c152=="q'") or (b152=="triangle.jpg", c153="p'"):
print("YES!")
else
print("False!")
I know I'm missing something here. My current excel code returns false even if the conditions are true. Thanks ahead of time!
OR is a function in Excel, like AND. Try something like this:
=if(OR(AND(b152 = "oval.jpg", c152 = "q'"), AND(b152 = "triangle.jpg", c153 = "p'")), "Correct", "Incorrect")

Resources