Tuesday, 28 May 2019

How to read multiple values from the keyboard in a single line

#how to read multiple values from the keyboard in a single line
a,b=(int(x) for x in input("enter 2 numbers:").split())
print(a,b)
print("product =",a*b)
"""output:
enter 2 numbers:10 20
10 20
product = 200

1Q: Why do use split()?

Ans: There are two reasons:
(1) It leads to error if I give i/ps by giving spaces.
Ex: 10 20 #error
(2) It takes only 1 input, and stores into two inputs like 1 and 0
so we will get a result like the below:
1 0
product=0

so the split() function is mandatory when we want to read more than one i/p from the keyboard

What is split()?
The split() method splits a string into a list.

You can specify the separator, the default separator is any whitespace.

Example:
"2 4".split() #We have to call the split() function w.r.t string
['2', '4']
>>> "1, 2 3 Hyd, Vij Kurnul,Kadapa atp".split(',')
['1', ' 2 3 Hyd', ' Vij Kurnul', 'Kadapa atp']
>>>

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...