E-Book: Python Programming for Beginners Succinctly | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (915)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (628)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (592)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)

E-Book Preview: Python Programming for Beginners Succinctly

The following chapters are excerpts from Python Programming for Beginners Succinctly, written by Jason Cannon. Look for this upcoming title to be added in early January to the Succinctly series—Syncfusion’s free library of pithy technology books.

Introduction

Choosing a place to begin when learning a new skill can often be difficult, especially when you are dealing with a broad or complex topic. In many cases, there is so much information available that it can be a real challenge to decide exactly where to start. Even worse, you may finally take the first steps toward learning, only to quickly discover far too many concepts, programming examples, and nuances that aren’t fully and thoughtfully explained. This type of experience can be incredibly frustrating, ultimately leaving you with more questions than answers.

Python Succinctly will help you sidestep this frustration. In this book we make no assumptions about your technical background, your knowledge of computer programming, or your general understanding of the Python language. You need no prior knowledge to benefit from reading this book. In these pages you will be guided step-by-step using a logical and systematic approach. While there will be new concepts, code, and jargon introduced, they will be explained in plain language, making it easy for absolutely anyone to understand.

Throughout the book you will be presented with many examples, as well as various Python programs. You can download all of these examples, as well as additional resources, at http://www.LinuxTrainingAcademy.com/python-succinctly.

Let’s get started.

Chapter 7 Tuples

A tuple is an immutable list, meaning that once it is defined it cannot be changed. This is different from normal lists in which you can add, remove, and change the values. With tuples none of these actions are an option. Where tuples are similar to lists is that they are ordered in the same fashion, and the values in the tuple can be still be accessed by index. In fact, you can perform many of the same operations on a tuple that you can on a list. You can concatenate tuples, you can iterate over the values in a tuple with a for loop, you can access values from the end of the tuple using negative indices, and you can access slices of a tuple. Tuples are created using comma separated values between parentheses. The pattern is tuple_name = (item_1, item_2, item_N). If you only want a single item in a tuple, that single item must always be followed by a comma. The pattern is tuple_name = (item_1,).

Tuples are key for organizing and holding data that will not, or should not change at any point during the execution of your program. Using a tuple is a great way to ensure that the values are not accidentally altered. For example, the months of the year should not change.

Code Listing 211

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

jan = months_of_the_year[0]

print(jan)

print()

for month in months_of_the_year:

    print(month)

# You cannot modify values in a tuple.  This will raise an exception.

Months_of_the_year[0] = ‘New January’

 

Code Listing 212

January

January

February

March

April

May

June

July

August

September

October

November

December

Traceback (most recent call last):

  File “tuples.py”, line 10, in <module>

    months_of_the_year[0] = ‘New January’

TypeError: ‘tuple’ object does not support item assignment

Even though you are unable to change the values within a tuple, you can always remove the entire tuple during the execution of your program by making use of the previously mentioned del statement.
Code Listing 213

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

print(months_of_the_year)

del months_of_the_year

# This will raise an exception since the tuple was deleted.

Print(months_of_the_year)

Output:

Code Listing 214

(‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

Traceback (most recent call last):

  File “tuples2.py”, line 5, in <module>

    print(months_of_the_year)

NameError: name ‘months_of_the_year’ is not defined

Switching between Tuples and Lists

In order to make a list from a tuple, use the list() built-in function and pass in the tuple. To create a tuple from a list, use the tuple() built-in function. The built-in function type() will display an object’s type.

Code Listing 215

months_of_the_year_tuple = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

months_of_the_year_list = list(months_of_the_year_tuple)

print(‘months_of_the_year_tuple is {}.’.format(type(months_of_the_year_tuple)))

print(‘months_of_the_year_list is {}.’.format(type(months_of_the_year_list)))

animals_list = [‘toad’, ‘lion’, ‘seal’]

animals_tuple = tuple(animals_list)

print(‘animals_list is {}.’.format(type(animals_list)))

print(‘animals_tuple is {}.’.format(type(animals_tuple)))

Output:

Code Listing 216

months_of_the_year_tuple is <class ‘tuple’>.

Months_of_the_year_list is <class ‘list’>.

Animals_list is <class ‘list’>.

Animals_tuple is <class ‘tuple’>

Looping through a Tuple

If you are looking to perform a particular action on every item within a tuple, use a for loop. The pattern is for item_variable in tuple_name followed by a code block.

Code Listing 217

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

for month in months_of_the_year:

    print(month)

Output:

Code Listing 218

January

February

March

April

May

June

July

August

September

October

November

December

Tuple Assignment

You can use tuples to assign values to multiple variables at the same time. In the following example, the variables jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, and dec are assigned the months of the year from the months_of_the_year tuple.

Code Listing 219

months_of_the_year = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)

(jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec) = months_of_the_year

print(jan)

print(dec)

Output:

Code Listing 220

January

December

It is also possible to use tuple assignment with lists.

Code Listing 221

contact_info = [‘555-0123’, ‘david@gmail.com’]

(phone, email) = contact_info

print(phone)

print(email)

Output:

Code Listing 222

Tuple assignment can also be used with functions as well. For example, you could create a function that returns a tuple and assigns those values to different variables.

The following example uses the built-in max() and min() functions. The max() built-in function will return the largest item that is passed to it. The min() built-in function will return the smallest item that is passed to it.

Code Listing 223

def high_and_low(numbers):

    “””Determine the highest and lowest number”””

    highest = max(numbers)

    lowest = min(numbers)

    return (highest, lowest)

lucky_numbers = [37, 71, 47, 13, 17, 67]

(highest, lowest) = high_and_low(lucky_numbers)

print(‘The highest number is: {}’.format(highest))

print(‘The lowest number is: {}’.format(lowest))

Output:

Code Listing 224

The highest number is:71

The lowest number is: 13

You can also use tuple assignment in a for loop. In the following example the contacts list is comprised of a series of tuples. Each time the for loop is performed the variables name and phone will be populated with the contents of a tuple from the contacts list.

Code Listing 225

contacts = [(‘David’, ‘555-0123’), (‘Tom’, ‘555-5678’)]

for (name, phone) in contacts:

    print(“{}’s phone number is {}.”.format(name, phone))

Output:

Code Listing 226

David’s phone number is 555-0123.

Tom’s phone number is 555-5678.

Review

A tuple is an immutable list, which means that once it has been defined the values in the tuple cannot be changed.

The del statement can be used to delete a tuple. Del tuple_name

It is possible to convert a tuple to a list using the list() built-in function.

Lists can also be converted to tuples by using the tuple() built-in function.

You can use tuple assignment to assign values to multiple variables at the same time. (var_1, var_N) = (value_1, value_N)

Tuple assignment can be used in for loops.

The max() built-in function will return the largest item that is passed to it.

The min() built-in function will return the smallest item that is passed to it.

Exercises

ZIP Codes

Try creating a list of cities that will include a series of tuples that contain both a city’s name and its ZIP code. Loop through the list and utilize tuple assignment. Assign one variable to denote the city name and another variable to represent the ZIP code. Display the city’s name and ZIP code to the screen.

Sample output:

Code Listing 227
 

The ZIP code for Short Hills, NJ is 07078.

The ZIP code for Fairfax Station, VA is 22039.

The ZIP code for Weston, CT is 06883.

The ZIP code for Great Falls, VA is 22066.

Solution

Code Listing 228
 

cities = [

    (‘Short Hills, NJ’, ‘07078’),

    (‘Fairfax Station, VA’, ‘22039’),

    (‘Weston, CT’, ‘06883’),

    (‘Great Falls, VA’, ‘22066’)

]

for (city, zip_code) in cities:

    print(‘The ZIP code for {} is {}.’.format(city, zip_code))

Resources

list() documentation: https://docs.python.org/3/library/functions.html#func-list

max() documentation: https://docs.python.org/3/library/functions.html#max

min() documentation: https://docs.python.org/3/library/functions.html#min

type() documentation: https://docs.python.org/3/library/functions.html#type

tuple() documentation: https://docs.python.org/3/library/functions.html#func-tuple

About the Author

Jason Cannon started his career as a Unix and Linux System Engineer in 1999. Since that time he has utilized his Linux skills at companies such as Xerox, UPS, Hewlett-Packard, and Amazon.com. Additionally, he has acted as a technical consultant and independent contractor for small businesses as well as Fortune 500 companies.

He enjoys teaching others how to use and exploit the power of open source software. Jason is the author of Command Line Kung Fu, Shell Scripting, and Linux for Beginners. He is also the founder of the Linux Training Academy where he blogs and teaches online video training courses.

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed