Why won't my True statement work? - python

Here is a dictionary:
Vocab ={'Adherent' : " supporter; follower.",
'Incoherent' : "without logical or meaningful connection; disjointed; rambling",
'Inherent' : "existing in someone or something as a permanent and inseparable element, quality, or attribute"}
I've created a simple set of if statements in a loop:
while 1:
x = Vocab[random.choice(Vocab.keys())]
print x
t1=raw_input("What word matches this definition?: ")
if t1 in Vocab == True:
if Vocab[t1] == x:
print "That's correct!"
elif Vocab[t1] != x:
print "That's wrong!"
else:
print "That's not a word!"
raw_input("Hit 'enter': ")
For some strange reason, when the user inputs a key that is in the dictionary, the code outputs:
"That's not a word"
Why isn't the if statement with the '== True' working?

You don't need to use if t1 in Vocab == True, simply use if t1 in Vocab.
The problem is the operand precedence. The == has priority over in, so when you write if t1 in Vocab == True python interprets as if t1 in (Vocab == True).
To fix the precedence issue, you can write like this: if (t1 in Vocab) == True:, but again there is no need to compare if the result of t1 in Vocab is True, simple use this:
if t1 in Vocab:

You shouldn't need to use the "== True." Python should evaluate the if statement when you use this syntax without that.

A couple of things. First, if you're on Windows, there is the possibility that it might not be stripping the '\r' at the end of the input line, or you might have extra whitespace in general from your input. But also, you can simplify your code significantly, as so:
t1=raw_input("What word matches this definition?: ")
try:
if Vocab[t1.strip()] == x: # This should fix your 'not a word' problem
print "That's Correct"!
else:
print "That's Wrong!"!
except KeyError:
print "That's not a word!"
There's no need to test if a key is in a dictionary before using it. Simply try and use it and then catch the resulting KeyError.
edit
#MagnunLeno is also totally correct about the precedence problem, although simplifying your code as I have recommended makes it a moot point.

Related

I was creating my own palindrome program when I came across that if I use [ ] for 'if' loop, every time it printed the 'if' statement

The use of parentheses for 'if' loop results in two different output for a palindrome program!
1.) () this gives the accurate result
2.) [] this only gives you the result of 'if' statement even if the "String" is not a palindrome
def isapalindrome(String):
if(String == String[::-1]):
return("is a palindrome!")
else:
return("is not a palindrome!")
String = input("Enter the String of your choice: ")
isapalindrome(String)
this code executes properly!
def isapalindrome(String):
if[String == String[::-1]]:
return("is a palindrome!")
else:
return("is not a palindrome!")
String = input("Enter the String of your choice: ")
isapalindrome(String)
this code executes only the 'if' statement!
() and [] are nothing alike.
() does what you expect it to, but wouldn't even be necessary since there is only one operator.
[] will create a list with a single element that equals the truth value of String == String[::-1], so either [True] or [False]. Independently of what the list contains, non-empty list in python are truthy. This means that your if condition will always evaluate to True
As other comments suggest, the correct structure of an if statement is:
if condition:
print("Do something")
else:
print("Do nothing")
Parenthesis are useful when using boolean expressions:
if (A==B) == C:
print("Do")
Point being, the brackets '[ ]' do not really belong there. As they are used to select a memory space within a given memory slot. Just like we would do with arrays.
I think is good that you are exploring different things, it is always good to know why things are the way they are.

How do I return "Yes" if all words in the sentence are lowercase?

I can currently have my code return "Yes" for each character, but I'm not sure how to make the code return just ONE Yes at the end of the code, if every word in the sentence was lowercase. Here's what I have
sentence = "hello thEre is this aLL lowercase"
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
print("Yes")
lower = True
if not ch.islower():
print("No")
lower = False
I know I cannot have print("Yes") in the loop because it will print everytime, but I don't know how to do it any other way. Thanks for any help.
Here is one way to approach the solution.
I’m intentionally not providing any explanation, because it will help your learning to research the concepts on your own. Look into:
List comprehension
The all() function
Boolean tests
Sample code:
s = ‘lower case statement’
result = all([i.islower() for i in s.split()])
print('Yes' if result else 'No')
>>> ‘Yes’
I recommend taking each part of the short code apart to discover how it’s working.
Simplified:
Personally, I don’t mind sharing this in an educational setting, because part of learning to write Python (and code in general) is learning to write it efficiently. That said, here’s a simplified solution:
print('Yes' if s.islower() else 'No')
>>> ‘Yes’
If you only care about it being all lowercase then the first time you find a capital letter you should break out of the loop. Then only print yes if lower is true outside the loop.
I'm assuming this is an exercise, so I won't give any code.
You need to have a variable "any non-lowercase word found" that is set to false before the loop and set to true if a word is found that is not lowercase. If the variable is still false after the loop you can print "yes", otherwise not.
Maybe if you have written the code to implement this you will find that it can be optimized.
You can use isLower(), just remember to remove spaces
def checkLower(string):
string = string.replace(" ","")
print(string)
for i in string:
if i.islower() == False:
return "no"
return "yes"
You can simply do this way using .islower() because The islower() methods return True if all characters in the string are lowercase, Otherwise, It returns False.
sentence = "hello thEre is this aLL lowercase"
if(sentence.isLower()):
print('Yes')
else:
print('No')
sentence = "hello there this is all lowercase"
sent = sentence.split(" ")
lower = True
for wd in sent:
for ch in wd:
if not ch.islower():
lower = False
if lower:
print("Yes")
if not lower:
print("No")
I don't have much idea about python and how it works but here is the logic i added to the code provided.
Right now you are printing "Yes" every time you find a lowercase word.
def isAllLower(sentence):
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
lower = True
if not ch.islower():
lower = False
if lower == True:
print("Yes")
elif lower == False:
print("No")
isAllLower("hello thEre is this aLL lowercase")
The simplest by far way is to compare the lowered by default sentence using the lower() function, with the initial function!
def SentenceisLower(sentence):
sentencelower = sentence.lower()
if (sentence == sentencelower):
print("Yes!")
Where there is no reply in any other outcome!

Python: Is it possible to judge input using if statement in one line

I'm using python 3.6. I want to input a string or something and judge it by if statement in one line.
This might be a simple question but I couldn't solve this problem. I know how to do in without one line:
words = input()
if words == 'a':
print(words)
else:
print('Not a')
However, I couldn't put it into one line. What I want to do is like this:
print(input() if input() == 'a' else 'Not a')
It doesn't work. The first input and the second input is different. Is it possible to keep the result of first input and check its condition in one line?
Thanks!
You can use the singleton generator/list trick to avoid calling a function twice, but still reuse its result:
print(next(x if x == 'a' else 'Not a' for x in [input()]))
While you're at it, you can also shorten the ternary x if y else z construct to become even more cryptic :-)
print(next(('Not a', x)[x == 'a'] for x in [input()]))
But fewer lines are not an end in itself. The five lines you have are perfectly valid and readable.
>>> words = input()
'a'
>>> print(words if words=='a' else 'not a')
a
>>> words = input()
'b'
>>> print(words if words=='a' else 'not a')
not a

how to check if string is palindrome of another string

I am trying to check if a string that is passed in to a function is a palindrome of the second string that is passed in. Google defines a palindrome to be a word that is the same spelled forwards or backwards.
def palindrome(strA, strB):
if (strA == strB and strA[::1] == strB):
print "true"
else:
print "false"
if __name__ == '__main__':
palindrome("sirap", "paris")
In the code above, I am attempting to check if the given string is equal to the second string both forwards and backwards yet the test i give it in main returns false. Any ideas on what im missing?
You check if 'sirap' is the same as 'paris' as well as checking if reversed 'sirap' is the same as 'paris'. You just have too many things in your if:
if strA[::-1] == strB:
print "true"
else:
print "false"
What you had would work if you passed in a palindrome as well as its reverse, the same thing. For example, palindrome("stats", "stats") would print "true", but I don't think that's what you had in mind. You will also notice that I used strA[::-1] instead of strA[::1]. That is because strA[::1] starts at the beginning and goes to the end, but you want to go backwards, so you should use -1.
You could even do it in one line:
print ("false", "true")[str[::-1] == strB]
I did a similar test using the "100 projects" to learn python (useful for learning any language)
You could do something like this, and just run the script. For this I just made some changes to the original palindrome script I wrote.
print "This will check if its a palindrome"
inputstring = raw_input("String1: ")
inputstring2 = raw_input("String2: ")
inputstring = inputstring.lower()
inputstring2 = inputstring.lower()
revstring = inputstring[::-1] #Reverses the string
if revstring == inputstring2:
print "Yes: " + revstring
else:
print "No: " + revstring

Comparing two string in python

Is there any in build function in python which enables two compare two string.
i tried comparing two strings using == operator but not working.
try:
if company=="GfSE-Zertifizierungen":
y=2
if x<y:
print "**************Same company***********"
x=x+1
flag=0
pass
if x==y:
flag=1
x=0
count=count+1
except Exception as e:
print e
This is not even showing any error nor working out.
Can anyone assist me where I m going wrong
In python to compare a string you should use the == operator.
eg:
a = "hello"
b = "hello2"
c = "hello"
then
a == b # should return False
a == c # should return True
Suggestion: print the content of your variable "company" to check what's inside of it. Be sure to have the same case (lower/upper letters).
The == operator for strings in python compares each letter of one string to another. If they are all the same, the string is equal.
The only two possibilities here are that you are not reaching the line
if company=="GfSE-Zertifizierungen":
or company is not actually the same.
To help troubleshoot, add something like:
try:
print "Got to here"
print company
if company=="GfSE-Zertifizierungen":
y=2
....
You can use == to check both the string are equal or not.
The problem is not with your if statement.
>>> company="GfSE-Zertifizierungen"
>>> if company == "GfSE-Zertifizierungen":
print "OK"
else:
print "NOT OK"
Output:
OK
You can use debugger to see whats wrong with your code.

Categories