Write a function that takes an imput (call it usr_in), the user's age (usr_age) and the user's name (usr_nm) and outputs the following string: "Hi, My name is [usr_nm], I am [usr_age] years old, and my favorite number is [usr_in]"

def usr_str(usr_in, usr_nm, usr_age): usr_string = "Hi, my name is " + usr_nm + " and I am " + str(usr_age) + " years old, and my favorite number is " + str(usr_in) "." print(usr_string) The first line of code allows us to define our function (def usr_str) where the [usr_str] could be any undefined name. And then defines our 3 inputs.
The second line is a little more complicated. It takes the imputs from our function and combines them into our string and then sets the variable usr_string to equal the string including our inputs. In order to add the text (ie. "Hi,my name is") we just have to put them in quotation marks and the code recognises it as a string. When we add the user name to the code we just include it as a variable as it is already a string. However for the two numbers, we must put them inside str() in order to allow the computer to recognise the numbers as a string. Otherwise will just get the following error:
TypeError: can only concatenate str (not "int") to str
The final line then prints the string we just created.
In order to call this funtion we just have to add the following line of code:
usr_str(42, "William", 20) >>> Hi my name is William and I am 20 years old, and my favorite number is 42.
Try it for yourself!

WT
Answered by William T. Python tutor

1264 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Create a program that takes in two numbers and returns the highest of the two


Write a function that checks whether a number is prime or not.


What is the difference between a for loop and a while loop.


Which four data types are used in Python? Can you give an example of each?


We're here to help

contact us iconContact ustelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences