Write a function that prints My name is <first name> <last name>Prototype: def say_my_name(first_name, last_name=""):first_name and last_name must be strings otherwise, raise a TypeError exception with the message first_name must be a string or last_name must be a stringYou are not allowed to import any module
Question
Write a function that prints My name is <first name> <last name>Prototype: def say_my_name(first_name, last_name=""):first_name and last_name must be strings otherwise, raise a TypeError exception with the message first_name must be a string or last_name must be a stringYou are not allowed to import any module
Solution
To write the requested function, follow these steps:
-
Define the function
say_my_namewith two parameters:first_nameandlast_name. Thelast_nameparameter is optional and has a default value of an empty string. -
Inside the function, check if both
first_nameandlast_nameare strings. If either of them is not a string, raise aTypeErrorexception with the message "first_name must be a string or last_name must be a string". -
If both
first_nameandlast_nameare strings, print the message "My name is <first name> <last name>". You can use string concatenation or f-strings to format the message.
Here's the code for the function:
def say_my_name(first_name, last_name=""):
if not isinstance(first_name, str) or not isinstance(last_name, str):
raise TypeError("first_name must be a string or last_name must be a string")
else:
print(f"My name is {first_name} {last_name}")
Note that this code does not require importing any modules.
Similar Questions
Write a Python program that inputs a user's first and last name and prints them in reverse order with a space in between.For example, if the program inputs the first name "Joe" and the last name "Bakers," it should output:Bakers Joe
Write a function that prints a name.Prototype: void print_name(char *name, void (*f)(char *));
3. Printing teachersmandatoryWrite a function printTeacher:It accepts two arguments firstName and lastNameIt returns the first letter of the firstName and the full lastNameExample: printTeacher("John", "Doe") -> J. DoeWrite an interface for the function named printTeacherFunction.
Write a function that reads your name in lowercase and perform the following operationprints it in uppercaseprints the length of the name
ou are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following:Hello firstname lastname! You just delved into python.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.