0

Trying to make some code that using a function that takes 3 parameters, I can give the forename, middle name and surname of a person and it outputs them as just the initials however if the 2nd parameter (the middle name) is blank then it is replaced with the letter "Z".

This is the code that doesn't do what I want:

#Creates the function with 3 parameters
def FormatName (string1, string2, string3):
  #Takes the parameters and saves the initial
  Newstring1 = string1[:1]
  Newstring2 = string2[:1]
  Newstring3 = string3[:1]
  #Makes all initials uppercase
  return Newstring1.upper() + Newstring2.upper() + Newstring3.upper()

#Gets the parts of the name you need via user input
Forename = input("What is your Forename? ")
Middle_Check = input("Do you have a middle name? Y/N")

#Checks if Middle name is present
if Middle_Check == "n" or "N":
  Middle_Name = "Z"
elif Middle_Check == "y" or "Y":
  Middle_Name = input("What is your Middle Name? ")
else:
  print("Please Enter Y or N.")
Surname = input("What is your Surname? ")


Name = FormatName(Forename, Middle_Name, Surname)

print("Formed Name: {}".format(Name))

and this is the code that I changed it to which does work:

def FormatName (string1, string2, string3):
  #Takes the parameters and saves the initial
  Newstring1 = string1[:1]
  Newstring3 = string3[:1]
  
  if string2 == "":
    Newstring2 = "Z"
  else:
    Newstring2 = string2[:1]

  return Newstring1.upper() + Newstring2.upper() + Newstring3.upper()
  

Forename = input("What is your Forename? ")
Middle_Name = input("What is your Middle Name? If you have none, leave blank. ")
Surname = input("What is your Surname? ")

Name = FormatName(Forename, Middle_Name, Surname)

print("Formed Name: {}".format(Name))

Can someone explain to me why the 1st code doesn't work while the 2nd one does even though all I did was move around the If statement and reword that statement. Thank you.

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
Meeracoat
  • 9
  • 2

0 Answers0