Python By Example

First Program - Input and Print

by Jiffin Joachim Gomez on 11th December 2017

In my first Python program I will start with basic program which shows you how to read some input from the user and also to print an output. There are a few built-in functions that we use in this program. First one is the input function which reads a line of input in string format. You can specify a string as argument to the input function and that string will be displayed on the standard output as a prompt for the user.

The second most important function that we use in this program is the print function which prints objects to the standard output. The objects are converted to string before printing and they are separeted by a space and terminated by a new line (\n) at the end. You can specify different separator and ending characters using end using the keywords sep and end as arguments.

In this program we also use the function int which converts its argument to an integer and the format function which is used to format a string using format specifiers. Lets look at the program now.

# First program
name = input("Please enter your name: ")
age = int(input("Enter your age: "))

print("Hello", name)
print("You will be",age+1,"years old next year.")
print("Hello", name, end="!!")
print(name, age, sep="---->")
print("{}'s age is now {}".format(name,age))

The output of the above program will be similar to this:

Please enter your name: Bob
Enter your age: 26
Hello Bob
You will be 27 years old next year.
Hello Bob!!Bob---->26
Bob's age is now 26

The first line of this program is comment. Comment lines start with a # character. In second line you prompt the user to enter a name. The input function will return a string containnig the name that was input by the user and it is assigned to a variable name.

Then we read the age and we convert the age string to integer using the int function.

In the print function you can pass string constants and variable as arguments and they will be converted to string and printed.

In the third print statement we are changing the termination character to !! instead of new line, which is the default. The sep keyword tells the print function to print ----> between the values for name and age.

The formatfunction substitutes the value of name variable in place of the first curly braces {} and the value of age in place of the second curly braces.

Post a comment


Nothing the first to share wisdom.