How do I stop None from appearing?

Viewed 48

This is my code and I made it say "Please enter the right letter next time." when the incorrect base is inputted to the code, it does that it like:

Please enter the right letter next time.

None

How can I remove the "None" from appearing when ran?

  if base == "A":
    return "T"
  elif base == "T":
    return "A"
  elif base == "C":
    return "G"
  elif base == "G":
    return "C"
  else:
    return print("Please enter the right letter next time.")
 
#main program
base1 = match_base("X")
print(base1)

3 Answers

It's because you're trying to return a print statement which doesn't make any sense.

Please change to:

  if base == "A":
    return "T"
  elif base == "T":
    return "A"
  elif base == "C":
    return "G"
  elif base == "G":
    return "C"
  else:
    return "Please enter the right letter next time."
 
#main program
base1 = match_base("X")
print(base1)

If you don't want to recover, use an exception.

def match_base(base):
  if base == "A":
    return "T"
  elif base == "T":
    return "A"
  elif base == "C":
    return "G"
  elif base == "G":
    return "C"
  else:
    raise ValueError("Please enter the right letter next time.")

If you do want to recover, let the caller do the work:

def match_base(base):
  if base == "A":
    return "T"
  elif base == "T":
    return "A"
  elif base == "C":
    return "G"
  elif base == "G":
    return "C"
  else:
    return None

base1 = match_base("X")
if not base1:
    print("Please enter the right letter next time.")
else:
    print(base1)

Note that this would be easier with a dictionary:

maps = {'A':'T', 'T':'A','C':'G','G':'C'}
def match_base(base):
    return maps.get(base, None)

The reason you are getting None is because your program is trying to assign the print statement to a variable. print("Please enter the right letter next time.") cannot be a stored in a variable.

So it should look like this instead:

  if base == "A":
    return "T"
  elif base == "T":
    return "A"
  elif base == "C":
    return "G"
  elif base == "G":
    return "C"
  else:
    print("Please enter the right letter next time.")
Related