Our programs have been all well and good so far, but they have been quite limited because the user doesn’t really interact with them in any way. Most real programs require some action from the user. It’s time to start asking our user to answer questions!
The way we ask the user a question with Python is the
input() command. The answer the user types can be saved into a text (string) variable as follows.
name = input("What is your name?") print("Hello, "+name)
How can we combine the above last few features to automatically ask what the persons name is, find the space, and use it’s value to split the name into firstname and familyname?
name = input( "Type your full name:" ) space = name.index(" ") given_name = name[:space] family_name = name[space+1:] print( "Your first name is: "+given_name ) print( "Your family name is: "+family_name )
- Create a Python program that asks a persons name and their favourite food, and then prints a message saying hello and that it’s your favourite too. Example screen of the expected result follows.