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!

Answered by William T. Python tutor

864 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What are the main data structures that I can use in Python


How would you get a piece of code to print the numbers 1 to 10


Write a program that computes the sum of all numbers up to a input number n


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


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2024

Terms & Conditions|Privacy Policy