Python assigns values to multiple variables at the same time.

Source: Internet
Author: User
Assigning multiple values at the same time is a cool programming shortcut: In Python, you can use tuples to assign multiple values at a time. Multiple values are assigned at the same time.

The following is a cool programming shortcut: In Python, you can use tuples once.

Assign multiple values.

>>> V = ('A', 2, True)

>>> (X, y, z) = v ①

>>> X

'A'

>>> Y

2

>>> Z

True

1. v is a triple of three elements, and (x, y, z) is the element that contains three variables.

Group. Assigning one value to the other will assign values to each value in v in sequence.

For each variable. This feature has multiple purposes. Assume that you need to specify a name for a specific range

Value. You can use the built-in range () function to assign values to multiple variables.

Row continuous variable assignment.

>>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,

SATURDAY, SUNDAY) = range (7) ①

>>> MONDAY

0

>>> TUESDAY

1

>>> SUNDAY

6

1. the built-in range () function constructs an integer sequence. (Technically

The range () function returns neither a list nor a tuples, but an overlap.

But you will learn the difference later .) MONDAY, TUESDAY,

WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY

Variable. (This example is from the calendar module, which is short and interesting.

Print the calendar, a bit like a UNIX program cal. The calendar module is the number of stars.

Defines an integer constant.

2. now, each variable has its value: MONDAY is 0, TUESDAY is 1,

And so on.

You can also use multi-variable assignment to create a function that returns multiple values. you only need to return one package.

Tuples that contain all values. The caller can regard the returned value as a simple tuples, or

Assign values to different variables.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.