1

My code below only prints "Remove Special Character". but if i leave only ("#"), it runs very well.

def name_character(word=input("Username: ")):
    if ("#") or ("$") or ("&") in word:
        return print ("Remove Special Character")
    if word == "":
        return print ("Enter Username")
    else: 
        return print (word)

(name_character())
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Albert
  • 13
  • 3
  • `or` is a boolean operator, not the English grammar construct. You need to be explicit: `'#' in word or '$' in word or '&' in word`. – Martijn Pieters Oct 17 '17 at 11:03
  • @MartijnPieters Just put the strings in a array: ` chars = ['#', '$', '&'] ` – ghovat Oct 17 '17 at 11:05
  • 1
    @ghovat: yes, the duplicate gives you more options. I was merely pointing out the reason why the OP's attempt did not work. – Martijn Pieters Oct 17 '17 at 11:06
  • 1
    Also, do not use default values to a function parameter to ask the user for input. That `input()` call will be processed **just once**. See ["Least Astonishment" and the Mutable Default Argument](//stackoverflow.com/q/1132941) – Martijn Pieters Oct 17 '17 at 11:07

2 Answers2

0

Try this:

>>> username = "foo#"
>>> any(x in username for x in "#&$")
True
>>> username = "bar"
>>> any(x in username for x in "#&$")
False
user1747134
  • 2,374
  • 1
  • 19
  • 26
0

Your comparison is turning somewhat like this

if("#" or .....)

and # is returned at the first comparison.

Do it in multiple or comparison, it will work

def name_character(word=input("Username: ")):
    if (("#") in word )or (("$") in word ) or (("&") in word ) :
        return print ("Remove Special Character")
    if word == "":
        return print ("Enter Username")
    else: 
        return print (word)

(name_character())
Rathan Naik
  • 993
  • 12
  • 25