Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

Input and Output


Taking Input and showing Output in required way plays an important role in interactive coding. So lets focus on input and output of various data types.

raw_input()

this is used to take input as long as it reached end of line.Note that there should not be any spaces.Taking input terminates with a new line character and if there are any spaces in the input line it results in error

after taking the input we can convert them to our required data type using functions like int(),float(),str()

input()

this is especially used to input integers. The advantage of input() over raw_input() can be cleared with the following example

how to take two two or more data types as input from a single line separated by spaces?

Here we make use split() and map() functions

Output formatting

You might have already noticed that print statement automatically inserts a new line. The use of comma like in the above code prints the values in a single line separated by a space. The sys module provides various functions for output formatting but here we learn how to use basic knowledge of formatting to output in our required way. Lets see a few examples to learn output formatting

The output must be self explanatory.

Exercise

Write a program that asks the user to input their name, age, and country. The program should then print out a message that includes this information in a sentence. The program should include:

  1. Taking a name as input using raw_input().
  2. Taking an age as input using input(), and converting it to an integer.
  3. Taking a country name as input using raw_input().
  4. Formatting the output to display a sentence that includes the name, age, and country.

The program should demonstrate input handling and string formatting in Python.

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy