© 2019 BrainStemSchool.com

December 13, 2016

December 9, 2016

December 7, 2016

Please reload

Simple Input

December 9, 2016

 

https://youtu.be/YelkDnk97HQ

Remember the traditional program flow: 

 

Input -> Processing -> Output

 

Input is defined in this context as data the user gives to the program. The program then uses that data in some way - manipulates it or just stores it in memory. Finally the program creates output. A program without output would be downright boring.

 

Picture a program that asks a user for his or her name and responds appropriately: 

(in this example, the user input is italicized)

 

What is your name?

Michael

Hello, Michael! Have a good day.

 

The first line is called the prompt - some output that elicits user input. The user inputs his name which is stored in the computer's memory. Finally the program uses that input in an output line.

 

Here's a short program to achieve this goal: 

 

name=input("What is your name?")

print("Hello, %s! Have a good day." % name)

 

Points to note: 

name is a variable. You know that because it is on the left side of the equal sign. 

input() produces a value. You know that because it's on the right side of the equal sign. Actually it "returns" a value.

name's type is str or String. The input() function always gives you strings, even if you input numbers. Try this one to see the error it produces. 

 

age=input("What is your age?")

print("In 5 years you'll be %i years old." % age+5 )

 

It says that %i is for ints but you seem to want a string there. Go ahead and change the %i to a %s and see the familiar error message. 

 

In this case you'll need a cast.

 

Next Post: Dealing With Input as a String

 

Share on Facebook
Share on Twitter
Please reload

Please reload

Recent Posts
Tags