2 possible outputs for 1 if statement python 3.x [duplicate] - python-3.x

This question already has answers here:
if statement with two conditions in Python
(2 answers)
Closed 5 years ago.
I am new to python and I am just figuring out the basics. I was just wondering how to have two possible choices in one if statement from one input.
q2 = input("What is the capital of Brazil? ")
if q2 == 'Brasilia' or 'brazilia':
print("Correct!")
else:
print("Wrong! The answer was Brasilia.")
However this does not work as when you put in a wrong answer, it says that it is "Correct!"

There are a number of ways of getting the desired result here:
if q2 == 'Brasilia' or q2 == 'brasilia':
if q2.lower() == 'brasilia':
if q2 in ('Brasilia', 'brasilia')
if q2.lower() in ('brasilia',)
Option #1 is just a correction for what you have. If you have only one real option that is just case sensitive, option #2 is a simple way to go. If you have many options, #3 and #4 are the way to go.

Theor does not work like you're trying to use it; think of it as bool(q2 == 'Brasilia') or bool('brasilia'); bool('brasilia') is True, so it will always be true.
You would need to use "q2 == 'Brasilia' or q2 == 'brasilia'", although q2.lower() == 'brasilia' is more idiomatic and more forgiving, unless it is important that it be strict.

If capitalization is not important then you could do:
if q2.lower() == 'brazilia':
or, if only first letter can be like this then:
if q2[0].lower() == 'b' and q[1:] == 'razilia':
Also, if you have more different words that fit the answer then use Python's in statement to check if the world belongs to a list of possible choices:
if q2 in ['Brazilia', 'Brasilia']:
etc. You can combine str.lower() and/or str.upper() with in statement if necessary.

Related

Why in JavaScript and so in other programming languages is not possible to do if (a==b==c) to compare 3 variable at once? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
Why, objectively, in programming languages in general, as far as I know, isn't possibile to compare 3 variable at once doing something like this:
if(a == b == c)
{
do something;
}
but it is necessary to do something like:
if(a == b && b == c)
{
do something;
}
why it is necessary to repeat twice the b variable?
Why the simplified way isn't implemented as well to compare multiple variables but is is necessary to use logic operators to make the comparison work?
The same question can be raised inequalities as a > b > c etc...
It has to do with the way the language evaluates boolean values. There are two different ways it could evaluate a == b == c: (a == b) == c, or a == (b == c).
In the first case, (a == b) == c, we start by evaluating a == b, which will return either true or false. The problem comes in when we try to do the next step. After evaluating what was in the parentheses, we could have either true == c or false == c, and unless c was equal to either true or false, the result of that (and the entire expression) would be false.
Hopefully you can see how this also applies to both ways of evaluating the expression, as well as with any other comparison operators you may use. Comparison operators simply return true or false based on the values directly to either side of them, and scripting languages run expressions in order, not all at once.
Another way to see it is if you rewrote the == operator as a function:
function isEqual(a, b):
if a == b:
return true
else:
return false
That is pretty much exactly what the == operator does. It simply returns true or false based on the values of its two arguments. Writing a == b == c would be the same as writing either isEqual(isEqual(a, b), c) or isEqual(a, isEqual(b, c)). Either way, you would be comparing a boolean to a potentially other type of value.

what is the time complexity for that piece of code?

what is the time complexity of this code?
how can I improve this code?
import random
n=input('choose one h/t? ')
v=random.randint(0,1)
if n=='h':
if v==0:
print('Hurrah!!! You win. Result is Head.')
else:
print('alas!!! You lose. Result is Tell.')
elif n=='t':
if v==1:
print('hurrah!!! You win. Result is Tell.')
else:
print('alas!!! You lose. Result is Head.')
I suggest you:
either merge the h and v if to get one if only
either determine first if it’s a h or t case, outside of other if. Then, use a function to test the other parts.
Indeed, just refactor to use functions as you are repeating yourself.

How to exactly compare object type in Python 3?

In Python 2 code I had something like:
...
elif type(value) == datetime.date:
return transform_date(value)
elif type(value) == datetime.datetime:
return transform_datetime(value)
...
Now, if I follow advise of avoiding "antipattern", I should replace it with isinstance.
isinstance(value, datetime.date)
And there will be a problem, because then correctness will depend on which type I check first.
I am well aware of more than 10 years old How to compare type of an object in Python? and What's the canonical way to check for type in Python? , but this question differs in two important ways:
It's about Python 3, idioms may be different
I am interested in exact check, because the transformation depends on the exact type (otherwise it will be lossy)
Exact match: For example, obj.__class__ or type(obj) matches.
As in Python there is only one obvious way to do it, the answer to this question should not depend on opinion that much.
If you really want strict per-exact-class match, the pythonic solution hasn't changed since py2: use a dict
dispatch = {
datetime.date: transform_date,
datetime.datetime: transform_datetime,
# etc
}
transform = dispatch.get(type(value), some_default_func)
transform(value)

Python: NameError: name "string" is not defined, not via input()

The function below checks to see if the first 9 digits of string (n) equate to the 10th character (an integer from 1-9 or X for 10).
def isISBN(n):
checkSum = 0
for i in range(9):
checkSum = checkSum + (eval(n[i])*(i+1))
if checkSum%11 == eval(n[9]) or (checkSum%11 == 10 and n[9] == 'X'): return True
else: return False
When I run the function for n='020103803X' I get an error:
NameError: name 'X' is not defined
I've searched for this problem and found that most people's issues were with input() or raw_input(), but as I am not using input(), I'm confused as to why I can't test if a character is a specific string. This is my first post as Python beginner, please tell if I'm breaking rules or what extra info I should include.
The problem is with your use of eval: eval('X') is the same as doing X (without the quotes). python sees that as a variable reference, and you have no variable named X.
There is no reason to use eval here. What are you hoping to accomplish? Perhaps you should be checking to see if the character is a digit?
if checkSum%11 == n[9].isdigit() or (checkSum%11 == 10 and n[9] == 'X'): return True
You're trying to get a response from
eval('X')
This is illegal, as you have no symbol 'X' defined.
If you switch the order of your if check, you can pass legal ISBNs. However, it still fails on invalid codes with an X at the end.
def isISBN(n):
checkSum = 0
for i in range(9):
checkSum = checkSum + (eval(n[i])*(i+1))
if (checkSum%11 == 10 and n[9] == 'X') or \
checkSum%11 == eval(n[9]):
return True
else:
return False
Note also that you can short-cut that return logic by simply returning the expression value:
return (checkSum%11 == 10 and n[9] == 'X') or \
checkSum%11 == eval(n[9])
Eval is not the proper usage, nor is the way you use it correct. For example, see Wikipedia which shows the use. You probably want to use a try: except: pair.
try:
int(n[i]
except:
print "this character is not a digit"
A call to eval is sometimes used by inexperienced programmers for all
sorts of things. In most cases, there are alternatives which are more
flexible and do not require the speed penalty of parsing code.
For instance, eval is sometimes used for a simple mail merge facility,
as in this PHP example:
$name = 'John Doe';
$greeting = 'Hello';
$template = '"$greeting,
$name! How can I help you today?"';
print eval("return $template;");
Although this works, it can cause some security problems (see §
Security risks), and will be much slower than other possible
solutions. A faster and more secure solution would be changing the
last line to echo $template; and removing the single quotes from the
previous line, or using printf.
eval is also sometimes used in applications needing to evaluate math
expressions, such as spreadsheets. This is much easier than writing an
expression parser, but finding or writing one would often be a wiser
choice. Besides the fixable security risks, using the language's
evaluation features would most likely be slower, and wouldn't be as
customizable.
Perhaps the best use of eval is in bootstrapping a new language (as
with Lisp), and in tutoring programs for languages[clarification
needed] which allow users to run their own programs in a controlled
environment.
For the purpose of expression evaluation, the major advantage of eval
over expression parsers is that, in most programming environments
where eval is supported, the expression may be arbitrarily complex,
and may include calls to functions written by the user that could not
have possibly been known in advance by the parser's creator. This
capability allows you to effectively augment the eval() engine with a
library of functions that you can enhance as needed, without having to
continually maintain an expression parser. If, however, you do not
need this ultimate level of flexibility, expression parsers are far
more efficient and lightweight.
Thanks everyone. I don't know how I didn't think of using int(). The reason I used eval() was because the past few programs I wrote required something like
x = eval(input("Input your equation: "))
Anyways the function works now.
def isISBN(n):
checkSum = 0
for i in range(9):
checkSum = checkSum + (int(n[i])*(i+1))
if n[9] == 'X':
if checkSum%11 == 10: return True
else: return False
elif checkSum%11 == int(n[9]): return True
else: return False

Swap Date around on a Natural Programming language variable?

I am trying to find a way to flip a date around in the natural programming language.
What I have is a #DOB which is equal to 19700830 yyyymmdd and I need it to be mmddyyyy. Is there an easy way to do this in Natural?
Question: How can I flip the date around to my specific format the easiest and most
efficient way in Natural?
Code:
RESET #NAME(A21/25)
#ROLE(A7/25)
#DOB(A10)
#I(P3)
#ADC(A1/25)
#SSN(A9)
I have tried using the FOR loop to get my results, but it is bulky and won't compile as of yet.. It is bulky at best.
FOR INDEX(P3) FROM 1 TO 8
IF INDEX >= 1 AND INDEX <= 4
#YYYY = #DOB(INDEX)
IF INDEX >= 5 AND INDEX <= 6
#MM = #DOB(INDEX)
IF INDEX >= 7 AND INDEX <= 7
#DD = #DOB(INDEX)
LOOP
This is what I would like to do but I am not completely certain that it will work. I think there is a better way but I do not have any real great books on the language and it is something that I do not do all that often. Once or twice a year so it is new to me.
The easiest way to do this is two redefine your variable and them just move and use the pieces of the redefine.
DEFINE #DOB(A10)
REDEFINE #DOB(#Y(A4) #M(A2) #D(A2))
Then you can just use the piece and move them around the way that you want.
WRITE WORK FILE 2 #M ',' #D ',' #Y

Resources