1

I'm trying to create a Python function that returns a polite greeting for everyone except for Lewis and Clark. Here is what I tried:

def politeGreeting(name):
    #if the user's name is Lewis or Clark, say "Oh, it's you." 
    if name == "Lewis" or "Clark":
        return("Oh, it's you")
    #if the user's name is anything else
    else:
        return("Hello," + name + "!")

name = input("please enter your name")        
print (politeGreeting(name))

Right now, this is printing Oh, it's you for everyone, not just for Lewis and Clark. I don't understand why - my IDE isn't returning any error messages. Please help if you can, thank you.

thebjorn
  • 26,297
  • 11
  • 96
  • 138
Chameleon
  • 99
  • 1
  • 9

3 Answers3

4

This should fix your problem of not restating the condition == for each comparison. Lewis or Clark:

def politeGreeting(name):
  #if the user's name is Lewis or Clark, say "Oh, it's you." 
  if name == "Lewis" or name == "Clark":
    return("Oh, it's you")
  #if the user's name is anything else
  else:
    return("Hello, " + name + "!")

name = input("Please enter your name:")        
print(politeGreeting(name))

However if you want to allow for different capitalizations of input try something like this which uses str.lower() and str.title():

def politeGreeting(name):
  #if the user's name is Lewis or Clark, say "Oh, it's you." 
  if name.lower() in {"lewis", "clark"}: # Use set for O(1) lookup time
    return("Oh, it's you " + name.title())
  #if the user's name is anything else
  else:
    return("Hello, " + name.title() + "!")

name = input("Please enter your name:")        
print(politeGreeting(name))
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • You should describe what the problem is in the original code as well as providing the solution – Ryan Haining Dec 20 '16 at 01:12
  • 1
    @shash678 Made sense after realizing I needed to restate the condition. Also good to know how to answer for different capitalization cases. Thanks for the link to repl.it - really cool compiler / IDE! – Chameleon Dec 20 '16 at 01:47
0

The expression name == "Lewis" or "Clarke" will always evaluate to True. Use name in ("Lewis", "Clarke") instead.

def politeGreeting(name):
    #if the user's name is Lewis or Clark, say "Oh, it's you." 
    if name in ("Lewis", "Clark"):
        return("Oh, it's you")
    #if the user's name is anything else
    else:
        return("Hello," + name + "!")

    name = input("please enter your name")        
    print (politeGreeting(name))
Andrew Guy
  • 9,310
  • 3
  • 28
  • 40
0
def politeGreeting(name):
    #if the user's name is Lewis or Clark, say "Oh, it's you." 
    if if name == "Lewis" or name == "Clark":
        return("Oh, it's you")
    #if the user's name is anything else
    else:
        return("Hello," + name + "!")

name = input("please enter your name")        
print (politeGreeting(name))
Jonathan Porter
  • 1,365
  • 7
  • 34
  • 62