Respuesta :
Answer:
- inputName = input("Input your name: ")
- nameComp = inputName.split(" ")
- if(len(nameComp) == 3):
- print(nameComp[2] + ", " + nameComp[0] + " " + nameComp[1][0])
- elif(len(nameComp) == 2):
- print(nameComp[1] + ", " + nameComp[0])
- else:
- print("Invalid name")
Explanation:
The solution code is written in Python 3.
Firstly use input function to prompt user to enter a name (Line 1).
Next, use split method to divide the input name into a list of individual name components (first name, middle name and last name) by using a single space " " as separator (Line 2).
If the length of nameComp is equal to 3 (this means the input name consists of first, middle and last name), print the name in form of lastName, firstName and middle Initial. This can be done by using appropriate index to get the target name component from the nameComp list and reorder them in the print statement (Line 4-5).
If the nameComp is equal to 2 (this means input name only consists of first name and last name), use the similar way as above to use index to get the target name component from the nameComp list and reroder them in the print statement (Line 6-7).
Add one more else condition to handle the situation where invalid name is enter (Line 8-9).
The program requires conditional statements.
Conditional statements are statements, whose execution depends on the truth value of the condition
The program in Python, where comments are used to explain each line is as follows:
#This gets the name from the user
userName = input("Name: ")
#This splits the name using spaces, as a separator
namsSplit = userName.split(" ")
#If the user enters three names
if(len(namsSplit) == 3):
#This prints the appropriate output format
print(namsSplit[2] + ", " + namsSplit[0] + " " + namsSplit[1][0])
#If the user enters two names
elif(len(namsSplit) == 2):
#This prints the appropriate output format
print(namsSplit[1] + ", " + namsSplit[0])
#All other names are regarded as invalid
else:
print("Invalid!")
Read more about similar programs at:
https://brainly.com/question/13678097