Part 1 - The input() & print() functions & how they work for an interactive program

Introduction

Now that we have covered the basics, we will now write a program that makes use of them. We will use the "Hello World" program we wrote earlier, but this time we will make it interactive.


Instead of saying hello to the world, we want to introduce ourselves as well. In order to do this, we will need our program to prompt us for information and display it on the screen.


Two functions can do exactly that - input() and print() .


input()

The input() function is used to display a prompt where information will be entered.


Example

myName = input("Enter your name")

myAge = input("Enter your age")


The string "Enter your name" is the prompt that will be shown to the user in the output. After they enter the relevant information, this information is stored as a string in the variable myName. The next input command prompts the user for their age and stores that as a string in the variable myAge.


print()

The print() function is used to display information to the user. It accepts zero or more expressions as parameters, separated by commas.

In the statement below, five parameters are passed to the print() function.

print("Hello World, my name is", myName, "and I am", myAge, "years old")


The first is the string "Hello World, my name is". The next is the variable myName which was declared with the input() function. After that is the string "and I am", followed by the variable myAge and then the string "years old".


We do not use quotation marks when referring to the variables. If we do, we will get the output

Hello World, my name is myName and I am myAge years old.

since the variable names become a string.


Another way to do this is to use the % formatter we learned earlier.

Syntax

print("Hello World, my name is %s and I am %s years old"%(myName, myAge))


We can also use the format() function to do the same.

Syntax

print("Hello World, my name is {} and I am {} years old".format(myName, myAge))

No comments:

Post a Comment