0

Very new to Python and I can't get to understand why the inputs is passing through as TRUE with second condition. I was expecting to print "," instead I'm getting ".":

def define_punctuation(inputs):
    text = inputs.split()
    if text[len(text) - 1] != '/end' and text[0] == 'how' or text[0] == 'when' or text[0] == 'what' or text[0] == 'why':
        text = '?' 
        print(text)
    elif text[0] != 'how' or text[0] != 'when' or text[0] != 'what' or text[0] != 'why' and text[len(text) - 1] == '/end': 
        text = '.'
        print(text)
    else: 
        text = ','
        print(text)

define_punctuation('test test test')
2
  • 1
    You've used or condition on the second elif statement. text[0] is 'test' which is not equal to 'how', so it prints "." Commented May 18, 2022 at 10:37
  • @ÇağatayBarın yes, but I was expecting the second part of the condition text[len(text) - 1] == '/end' to turn the statement to false. I don't know why 'test' == '/end/' is true? Commented May 18, 2022 at 10:41

2 Answers 2

2

You must use like this

def define_punctuation(inputs):
    text = inputs.split()
    if (text[len(text) - 1] != '/end') and (text[0] == 'how' or text[0] == 'when' or text[0] == 'what' or text[0] == 'why'):
        text = '?' 
        print(text)
    elif (text[0] != 'how' or text[0] != 'when' or text[0] != 'what' or text[0] != 'why') and (text[len(text) - 1] == '/end'): 
        text = '.'
        print(text)
    else: 
        text = ','
        print(text)

As in your case you have used like this

    if text[0] != 'how' or text[0] != 'when' or text[0] != 'what' or text[0] != 'why' and text[len(text) - 1] == '/end':

Which say if any of condition goes write it will execute the statement

e.g

if False or False or True or False and False

Here this is wrong approach to write condition as it will execute when it will get True

Right approach is

if (False or True or False) and (False)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I just learned about this :)
this is working now thanks, now I have an issue when I pass /end "hey, print this /end" the end result should be "hey, print this." but I get "hey, print this," not sure why, I added what you suggested, not sure why this throughs TRUE.
0

I suppose that you want to this

(text[0] != 'how' or text[0] != 'when' or text[0] != 'what' or text[0] != 'why') and text[len(text) - 1] == '/end'

in the second (elif) statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.