Software Development Exam  >  Software Development Notes  >  Basics of Python  >  Taking Input in Python

Taking Input in Python | Basics of Python - Software Development PDF Download

Introduction

Python is a versatile programming language widely used for its simplicity and readability. One of the fundamental aspects of programming is taking input from the user. In this article, we will explore various methods and techniques to obtain user input in Python. We will cover basic input using the input() function, type conversion, handling numerical inputs, and tackling common input-related challenges.

Basic Input using 'input()' function

The 'input()' function is the simplest way to receive user input in Python. It reads a line of text entered by the user and returns it as a string. Here's a basic example:

name = input("Enter your name: ")

print("Hello, " + name + "!")

Output:

Enter your name: John

Hello, John!

Explanation:

  • The 'input()' function prompts the user to enter their name.
  • The inputted value is stored in the 'name' variable.
  • The program then prints a greeting message using the user's input.

Type Conversion

Often, we need to convert the user's input to a specific data type, such as integer or float. Python provides built-in functions to convert strings to different data types. Let's see an example:

age = input("Enter your age: ")

age = int(age)  # Convert input to an integer

print("Next year, you will be", age + 1, "years old.")

Output:

Enter your age: 25

Next year, you will be 26 years old.

Explanation:

  • The user is asked to enter their age.
  • The input is initially stored as a string in the 'age' variable.
  • We use the 'int()' function to convert the input to an integer.
  • Finally, the program adds 1 to the age and prints the result.

Handling Numerical Inputs

When dealing with numerical input, it's important to validate and handle potential errors. Let's consider an example where we ask the user to enter two numbers and perform a basic arithmetic operation:

num1 = input("Enter the first number: ")

num2 = input("Enter the second number: ")

try:

    result = int(num1) + int(num2)

    print("The sum is:", result)

except ValueError:

    print("Invalid input. Please enter valid numbers.")

Output 1:

Enter the first number: 10

Enter the second number: 20

The sum is: 30

Output 2:

Enter the first number: 10

Enter the second number: abc

Invalid input. Please enter valid numbers.

Explanation:

  • The user is prompted to enter two numbers.
  • The inputs are stored as strings in 'num1' and 'num2'.
  • We use 'nt()' to convert the inputs to integers and perform the addition.
  • If the conversion fails (e.g., when a non-numeric value is entered), a 'ValueError' is raised, and the program displays an error message.

Common Input Challenges

(i) Taking multiple inputs on a single line:

To receive multiple inputs in a single line, we can use the 'split()' method. This splits the input at each whitespace and returns a list of individual values. Here's an example:

name, age = input("Enter your name and age: ").split()

print("Name:", name)

print

Output:

Enter your name and age: John 25

Name: John

Age: 25

Explanation:

  • The user enters two values separated by a space.
  • The 'split()' method splits the input into two values and stores them in the 'name' and 'age' variables.
  • The program then prints the name and age separately.

(ii) Taking input with a specific format:

Sometimes, we need to restrict the input format or validate it against a specific pattern. In such cases, we can use regular expressions ('re' module) to match the input against a pattern. Here's an example:

import re

while True:

    email = input("Enter your email: ")

    if re.match(r"[^@]+@[^@]+\.[^@]+", email):

        print("Valid email:", email)

        break

    else:

        print("Invalid email. Please enter a valid email address.")

Output 1:

Enter your email: john@gmail.com

Valid email: john@gmail.com

Output 2:

Enter your email: john@.com

Invalid email. Please enter a valid email address.

Explanation:

  • The user enters an email address.
  • The program checks if the input matches the regular expression pattern.
  • If the input matches, it's considered valid, and the program exits the loop.
  • If the input doesn't match, the program displays an error message and asks the user to enter a valid email address.

Sample Problems and Solutions

Problem 1: Write a program that asks the user to enter two numbers and prints their product.

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

product = num1 * num2

print("The product is:", product)

Problem 2: Write a program that asks the user to enter a string and prints its length.

string = input("Enter a string: ")

length = len(string)

print("The length of the string is:", length)

Conclusion

Taking input is an essential aspect of programming. Python provides several built-in functions and methods to obtain user input, handle errors, and convert data types. By using the techniques described in this article, you can create more interactive and versatile programs.

The document Taking Input in Python | Basics of Python - Software Development is a part of the Software Development Course Basics of Python.
All you need of Software Development at this link: Software Development
49 videos|38 docs|18 tests

Top Courses for Software Development

49 videos|38 docs|18 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

video lectures

,

pdf

,

study material

,

Exam

,

Viva Questions

,

Previous Year Questions with Solutions

,

Sample Paper

,

Summary

,

MCQs

,

Taking Input in Python | Basics of Python - Software Development

,

shortcuts and tricks

,

Extra Questions

,

Important questions

,

Semester Notes

,

past year papers

,

mock tests for examination

,

Free

,

Objective type Questions

,

Taking Input in Python | Basics of Python - Software Development

,

practice quizzes

,

Taking Input in Python | Basics of Python - Software Development

,

ppt

;