954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Useful input trick

By AutoPython on Nov 14th, 2009 10:06 am

!USING PYTHON 3.1!

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, youhave 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


Now:

breakfast = sausage
lunch = pizza
dinner = chicken


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

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

woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

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

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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 :(.

AutoPython
Junior Poster
138 posts since Sep 2009
Reputation Points: 14
Solved Threads: 18
 

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

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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

Paul Thompson
Veteran Poster
1,119 posts since May 2008
Reputation Points: 264
Solved Threads: 183
 

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.

AutoPython
Junior Poster
138 posts since Sep 2009
Reputation Points: 14
Solved Threads: 18
 

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

e-papa
Posting Pro in Training
465 posts since Mar 2011
Reputation Points: 23
Solved Threads: 4
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: