0% found this document useful (0 votes)
14 views6 pages

Python Input Types Explained

The document provides examples of various input types in Python, including basic string, integer, float, list, tuple, dictionary, set, and boolean inputs. It also covers more advanced inputs like JSON-like dictionaries and multiple lines until EOF. Each example includes code snippets, expected input, and output formats.

Uploaded by

kiffaytullashaik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views6 pages

Python Input Types Explained

The document provides examples of various input types in Python, including basic string, integer, float, list, tuple, dictionary, set, and boolean inputs. It also covers more advanced inputs like JSON-like dictionaries and multiple lines until EOF. Each example includes code snippets, expected input, and output formats.

Uploaded by

kiffaytullashaik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Input Types with Examples

1. Basic String Input

Code:

s = input("Enter a string: ")

print(s)

Input:

Hello World

Output:

Hello World

2. Integer / Float Input

Code:

num = int(input("Enter an integer: "))

f = float(input("Enter a float: "))

print(num, f)

Input:

10

3.14

Output:

10 3.14

3. List of Integers (Array-style)

Code:

arr = list(map(int, input("Enter space-separated numbers: ").split()))

print(arr)

Input:

12345

Output:

[1, 2, 3, 4, 5]

4. List of Strings

Code:
Python Input Types with Examples

words = input("Enter words: ").split()

print(words)

Input:

apple banana mango

Output:

['apple', 'banana', 'mango']

5. 2D List (Matrix)

Code:

rows = int(input("Enter number of rows: "))

matrix = [list(map(int, input().split())) for _ in range(rows)]

print(matrix)

Input:

123

456

Output:

[[1, 2, 3], [4, 5, 6]]

6. Tuple Input

Code:

t = tuple(map(int, input("Enter tuple values: ").split()))

print(t)

Input:

10 20 30

Output:

(10, 20, 30)

7. Dictionary Input (Key-Value Pairs)

Code:

d = {}
Python Input Types with Examples

n = int(input("Enter number of items: "))

for _ in range(n):

key, value = input("Enter key and value: ").split()

d[key] = value

print(d)

Input:

name John

age 25

Output:

{'name': 'John', 'age': '25'}

8. Set Input

Code:

s = set(map(int, input("Enter unique elements: ").split()))

print(s)

Input:

12234

Output:

{1, 2, 3, 4}

9. Multiple Variables in One Line

Code:

a, b, c = map(int, input("Enter three numbers: ").split())

print(a, b, c)

Input:

5 10 15

Output:

5 10 15

10. List of Characters


Python Input Types with Examples

Code:

chars = list(input("Enter characters: "))

print(chars)

Input:

hello

Output:

['h', 'e', 'l', 'l', 'o']

11. Boolean Input

Code:

val = input("Enter true or false: ").lower() == "true"

print(val)

Input:

True

Output:

True

12. JSON-like Dictionary Input

Code:

import json

d = [Link](input("Enter JSON: "))

print(d)

Input:

{"name": "Alice", "age": 30}

Output:

{'name': 'Alice', 'age': 30}

13. Input Using literal_eval

Code:

from ast import literal_eval

data = literal_eval(input("Enter a literal: "))


Python Input Types with Examples

print(type(data), data)

Input:

[10, 20, 30]

Output:

<class 'list'> [10, 20, 30]

14. Multiple Lines of Input

Code:

lines = []

for _ in range(3):

[Link](input())

print(lines)

Input:

first line

second line

third line

Output:

['first line', 'second line', 'third line']

15. Read Until EOF ([Link])

Code:

import sys

for line in [Link]:

print([Link]())

Input:

Hello

World

Python

(then Ctrl+D)

Output:

Hello
Python Input Types with Examples

World

Python

Common questions

Powered by AI

Python's dictionary input handling is particularly useful for managing user input data that naturally maps to key-value pairs, such as configuration settings or user profiles. This is achieved by reading a number of inputs and mapping them into keys and values within a dictionary. For instance, `for _ in range(n): key, value = input("Enter key and value: ").split()` constructs a dictionary from user inputs. If two pairs are entered, like 'name John' and 'age 25', this yields a dictionary: {'name': 'John', 'age': '25'}, facilitating easy retrieval and storage of related data .

Using a set for input data is particularly useful to automatically handle and remove duplicate numbers due to its inherent property of storing only unique elements. This ensures the output data is perfectly de-duplicated without additional logic. For the input '1 2 2 3 4', after processing via `set(map(int, input().split()))`, the output will be {1, 2, 3, 4}, with duplicate '2' removed .

The steps involved in reading a matrix of numbers in Python include obtaining the number of rows with `int(input())` and then using a list comprehension to iterate over each row, splitting and converting each input line into a list of integers using `list(map(int, input().split()))`. For two rows of input '1 2 3' and '4 5 6', the resulting output will be a 2D list structured as [[1, 2, 3], [4, 5, 6]], representing the matrix format .

Using the `sys.stdin` module allows a Python program to continuously read input until EOF (end-of-file) is reached, which is beneficial for handling large or indeterminate input sizes usually from files or complex input streams. This differentiates from the standard `input()` method, which reads one input line at a time and expects explicit user intervention for each input line. Using `sys.stdin.forEach(line)` is efficient as it reads input non-interactively, ideal for data input from scripts or files until EOF, marked typically by Ctrl+D in Unix systems, enabling seamless processing of multiline inputs .

A Python program can efficiently handle multiple lines of input from a user by using a loop to append each line of input into a list. This is achieved by iterating a set number of times or until an EOF (end-of-file) marker is encountered. Each line is gathered using the `input()` function and appended to a list. For instance, using a loop with a range: `for _ in range(3): lines.append(input())`, gathers three lines of input and stores them in a list called `lines`. The expected output for three lines of 'first line', 'second line', and 'third line' would be a list: ['first line', 'second line', 'third line'].

Mapping multiple variables in one line using `map(int, input().split())` facilitates ease of data handling by assigning multiple user inputs simultaneously to variables, streamlining data processing and reducing code verbosity. For input '5 10 15', the line `a, b, c = map(int, input().split())` assigns 5 to `a`, 10 to `b`, and 15 to `c`, with the output being 5 10 15 when printed, showcasing efficient variable assignment and data handling .

When using `input()` to read a large sequence of characters and converting each into a list, performance considerations include potential memory constraints due to the creation of a large list and increased processing time for very large inputs. The method involves using `list(input())`, which individually appends each character to a new list. For very large strings, this can tax memory allocation and processing efficiency, impacting performance. Considerations should include optimizing input size, ensuring sufficient memory, and implementing lazy loading or pagination techniques if needed to manage memory more effectively .

To convert a string of space-separated numbers into a tuple in Python, the `map` function can be used alongside `int` conversion, wrapped by the `tuple` constructor. The input string is split into components by spaces and each component is mapped to an integer using `map(int, input().split())`. This sequence is then turned into a tuple, effectively transforming the input. For the input '10 20 30', the result is a tuple: (10, 20, 30).

Using `literal_eval` from the `ast` module for input handling allows safe evaluation of a string as a Python literal (e.g., list, tuple, dict, integers, etc.). Unlike `eval()`, which can execute arbitrary code, `literal_eval` only processes actual Python literals, eliminating the risk of executing malicious code. This makes it more secure compared to using just `input()` when the latter is used without precautions to evaluate user data. For instance, when input is '[10, 20, 30]', `literal_eval` successfully converts it into a list, preserving its data type .

JSON handling of input data in Python offers advantages such as ease of integration with web technologies, as JSON is a widely used data format for APIs and consistent structure for data validation. Using `json.loads()` converts JSON strings into Python dictionaries, enabling straightforward parsing of structured data. Limitations include the need for data to be properly formatted JSON and potential performance overhead during parsing in large datasets. For a JSON input like '{"name": "Alice", "age": 30}', the method `json.loads()` converts it into a Python dictionary: {'name': 'Alice', 'age': 30} .

You might also like