Input Techniques
1. Taking Input using input() Function
The input()
function by default takes string input.
# For string text = input("Enter text: ") # For integers num = int(input("Enter an integer: ")) # For floating or decimal numbers decimal = float(input("Enter a decimal number: "))
2. Taking Multiple Inputs
Multiple inputs can be taken using the map()
and split()
methods. The split()
method splits the space-separated inputs and returns an iterable.
# For Strings a, b = input("Enter two words: ").split() # For integers x, y = map(int, input("Enter two integers: ").split()) # For floating point numbers m, n = map(float, input("Enter two decimals: ").split())
3. Taking Input as a List or Tuple
You can use split()
and map()
functions to take inputs as a list or tuple.
# For Input - 7 8 9 4 23 12 numbers = list(map(int, input("Enter numbers: ").split())) print(numbers)
Output:
[7, 8, 9, 4, 23, 12]
4. Taking Fixed and Variable Numbers of Inputs
# Input: example 5 1 2 3 label, *values = input("Enter label and numbers: ").split() values = list(map(int, values)) print(label, values)
Output:
example [5, 1, 2, 3]
Output Techniques
1. Output on a Different Line
The print()
method is used in Python for printing to the console.
items = ['apple', 'banana', 'cherry'] for item in items: print(item)
Output:
apple banana cherry
2. Output on the Same Line
The end
parameter in Python can be used to print on the same line.
items = ['apple', 'banana', 'cherry'] for item in items: print(item, end='')
Output:
applebananacherry
3. Output Formatting
To format your output, you can use {}
and the format()
function.
print('I enjoy {}'.format('coding.')) print("I enjoy {0} {1}".format('Python', 'programming.'))
Output:
I enjoy coding. I enjoy Python programming.
4. Output using f-strings
F-strings are a modern way to format strings in Python.
greeting = "Welcome" print(f"{greeting} to Python!")
Output:
Welcome to Python!
Conclusion
In this article, we covered various input and output techniques in Python, including taking inputs through the input()
function, handling multiple inputs, and formatting outputs. These techniques are essential for effectively interacting with users and displaying results in Python programming.
0 Comments