Useful input trick

AutoPython 6 Tallied Votes 562 Views Share


Hello DaniWeb! Today I'm going to teach you a cool variable trick that I learned. So here's an example:

a, b, c = input('?x?x?: ').split('x')

Now let's input something like:

>>> a, b, c = input('?x?x?: ').split('x')
?x?x?: 1x2x3

Now, variable 'a' is set to 1, variable 'b' is set to 2, variable 'c' is set to 3. I hope I explained that well enough. It can be used in various sections. NOTE: Because you used 3 variables, you have to have three answers divided by the character you split with. If you only used 'a, b' you would only be able to do '1x2'.

Now lets use another example using more common names:

breakfast, lunch, dinner = input('breakfast&lunch&dinner').split('&')

Now if we run this in idle the result is:

>>> breakfast, lunch, dinner = input('breakfast&lunch&dinner: ').split('&')
breakfast&lunch&dinner: sausage&pizza&chicken


breakfast = sausage
lunch = pizza
dinner = chicken

That's going to be it for this tutorial! Hope you find it useful!

Gribouillis commented: nice +2
e-papa commented: Good. +3
BustACode commented: Good stuff. Thanks. +1
woooee 814 Nearly a Posting Maven

You should use this with a try/except (within is while) since anyone would enter more or fewer characters at some time.

Gribouillis 1,391 Programming Explorer Team Colleague

nice, it looks like a kind of 'scanf' for python.

AutoPython 5 Junior Poster

Thanks for the feed back. I would edit it and show an example with the try/except thing, but I've already used all my edits :(.

Gribouillis 1,391 Programming Explorer Team Colleague

That's a problem with these code snippet. In the active state snippets, people can update their code long after the initial post.

lllllIllIlllI 178 Veteran Poster

Wow a tutorials, i havent seen one of these posted for aages...

AutoPython 5 Junior Poster

Yeah, I thought the same thing. I want to post more tutorials here. It's just that I don't have to many good subjects to post on.

e-papa 13 Posting Pro in Training

This is good, it will really reduce the number of input() functions i use in my programs.

vinodvinu -3 Light Poster

Thank you for this tip.

TrustyTony commented: Thanks not by post, by upvote, please! -3
BustACode 15 Light Poster

Coincidentally how to do a multi-input was rattling around my head for the past two weeks. Tonight, I click on turtorials for S & G, and bam!, there's the answer.


Member Avatar for 111100/11000

but shouldn't that be reversed

breakfast&lunch&dinner: sausage&pizza&chicken

breakfast&lunch&dinner: sausage&chicken&pizza


breakfast = sausage
lunch = chicken
dinner = pizza
Member Avatar for 111100/11000

you can also do:

x,y,z = input('Enter 3 numbers: ')

than if you enter:

Enter 3 numbers: 567

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.