+ 1

Simple Python question: how can I read 2 numbers from the same line?

How can I read 2 numbers from the same line that are separated by a space e.g: 1 2 not: 1 2 I tried this, but it does not work: a,b=int(input()),int(input()) print(a-b) Thank you for your time.

23rd Nov 2018, 3:35 PM
Stefan Secrieru
Stefan Secrieru - avatar
6 Respostas
+ 3
Try this: (a, b) = (int(k) for k in input().split())
23rd Nov 2018, 3:58 PM
portpass
0
portpass It seems to be harder the I thought. I did not learn the thing you wrote there but I will try. Thank you!
23rd Nov 2018, 4:22 PM
Stefan Secrieru
Stefan Secrieru - avatar
0
Ok. All you need is split() method. You can rewrite the code in simpler way, but a bit longer: (a, b) = input().split() a = int(a) b = int(b) https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2456/
23rd Nov 2018, 4:45 PM
portpass
0
portpass Thank you for your time, it is working, but how can I do the same thing with 4 numbers?
24th Nov 2018, 11:44 AM
Stefan Secrieru
Stefan Secrieru - avatar
0
Stefan Secrieru, You really can do the same with 4 numbers: a, b, c, d = input().split() a = int(a) ... or you can use the fist variant: a, b, c, d = (int(k) for k in input().split()) If you want to operate with more variables, try using lists and loops: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2431/
24th Nov 2018, 3:55 PM
portpass
0
Oh... Thank you!
24th Nov 2018, 4:32 PM
Stefan Secrieru
Stefan Secrieru - avatar