1. Trang chủ
  2. » Thể loại khác

Hướng dẫn lập trình cơ bản với Python dành cho người mới bắt đầu

411 11 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Hướng Dẫn Lập Trình Cơ Bản Với Python Dành Cho Người Mới Bắt Đầu
Định dạng
Số trang 411
Dung lượng 10,78 MB
File đính kèm Beginning Programming with Python For Dummies.rar (8 MB)

Cấu trúc

  • Title Page

  • Copyright Page

  • Contents at a Glance

  • Table of Contents

  • Introduction

    • About This Book

    • Foolish Assumptions

    • Icons Used in This Book

    • Beyond the Book

    • Where to Go from Here

  • Part I: Getting Started with Python

    • Chapter 1: Talking to Your Computer

      • Understanding Why You Want to Talk to Your Computer

      • Knowing that an Application is a Form of Communication

        • Thinking about procedures you use daily

        • Writing procedures down

        • Seeing applications as being like any other procedure

        • Understanding that computers take things literally

      • Defining What an Application Is

        • Understanding that computers use a special language

        • Helping humans speak to the computer

      • Understanding Why Python is So Cool

        • Unearthing the reasons for using Python

        • Deciding how you can personally benefit from Python

        • Discovering which organizations use Python

        • Finding useful Python applications

        • Comparing Python to other languages

    • Chapter 2: Getting Your Own Copy of Python

      • Downloading the Version You Need

      • Installing Python

        • Working with Windows

        • Working with the Mac

        • Working with Linux

      • Accessing Python on Your Machine

        • Using Windows

        • Using the Mac

        • Using Linux

      • Testing Your Installation

    • Chapter 3: Interacting with Python

      • Opening the Command Line

        • Starting Python

        • Using the command line to your advantage

        • Using Python environment variables to your advantage

      • Typing a Command

        • Telling the computer what to do

        • Telling the computer you’re done

        • Seeing the result

      • Using Help

        • Getting into help mode

        • Asking for help

        • Leaving help mode

        • Obtaining help directly

      • Closing the Command Line

    • Chapter 4: Writing Your First Application

      • Understanding the Integrated DeveLopment Environment (IDLE)

      • Starting IDLE

        • Using standard commands

        • Understanding color coding

        • Getting GUI help

        • Configuring IDLE

      • Creating the Application

        • Opening a new window

        • Typing the command

        • Saving the file

      • Running the Application

      • Understanding the Use of Indentation

      • Adding Comments

        • Understanding comments

        • Using comments to leave yourself reminders

        • Using comments to keep code from executing

      • Loading and Running Existing Applications

        • Using the command line or terminal window

        • Using the Edit window

        • Using the Python Shell window or Python command line

      • Closing IDLE

  • Part II: Talking the Talk

    • Chapter 5: Storing and Modifying Information

      • Storing Information

        • Seeing variables as storage boxes

        • Using the right box to store the data

      • Defining the Essential Python Data Types

        • Putting information into variables

        • Understanding the numeric types

        • Understanding Boolean values

        • Understanding strings

      • Working with Dates and Times

    • Chapter 6: Managing Information

      • Controlling How Python Views Data

        • Making comparisons

        • Understanding how computers make comparisons

      • Working with Operators

        • Defining the operators

        • Understanding operator precedence

      • Creating and Using Functions

        • Viewing functions as code packages

        • Understanding code reusability

        • Defining a function

        • Accessing functions

        • Sending information to functions

        • Returning information from functions

        • Comparing function output

      • Getting User Input

    • Chapter 7: Making Decisions

      • Making Simple Decisions Using the if Statement

        • Understanding the if statement

        • Using the if statement in an application

      • Choosing Alternatives Using the if

        • Understanding the if

        • Using the if

        • Using the if

      • Using Nested Decision Statements

        • Using multiple if or if

        • Combining other types of decisions

    • Chapter 8: Performing Repetitive Tasks

      • Processing Data Using the for Statement

        • Understanding the for statement

        • Creating a basic for loop

        • Controlling execution with the break statement

        • Controlling execution with the continue statement

        • Controlling execution with the pass clause

        • Controlling execution with the else statement

      • Processing Data Using the while Statement

        • Understanding the while statement

        • Using the while statement in an application

      • Nesting Loop Statements

    • Chapter 9: Dealing with Errors

      • Knowing Why Python Doesn’t Understand You

      • Considering the Sources of Errors

        • Classifying when errors occur

        • Distinguishing error types

      • Catching Exceptions

        • Basic exception handling

        • Handling more specific to less specific exceptions

        • Nested exception handling

      • Raising Exceptions

        • Raising exceptions during exceptional conditions

        • Passing error information to the caller

      • Creating and Using Custom Exceptions

      • Using the finally Clause

  • Part III: Performing Common Tasks

    • Chapter 10: Interacting with Modules

      • Creating Code Groupings

      • Importing Modules

        • Using the import statement

        • Using the from

      • Finding Modules on Disk

      • Viewing the Module Content

      • Using the Python Module Documentation

        • Opening the pydoc application

        • Using the quick-access links

        • Typing a search term

        • Viewing the results

    • Chapter 11: Working with Strings

      • Understanding That Strings Are Different

        • Defining a character using numbers

        • Using characters to create strings

      • Creating Stings with Special Characters

      • Selecting Individual Characters

      • Slicing and Dicing Strings

      • Locating a Value in a String

      • Formatting Strings

    • Chapter 12: Managing Lists

      • Organizing Information in an Application

        • Defining organization using lists

        • Understanding how computers view lists

      • Creating Lists

      • Accessing Lists

      • Looping Through Lists

      • Modifying Lists

      • Searching Lists

      • Sorting Lists

      • Working with the Counter Object

    • Chapter 13: Collecting All Sorts of Data

      • Understanding Collections

      • Working with Tuples

      • Working with Dictionaries

        • Creating and using a dictionary

        • Replacing the switch statement with a dictionary

      • Creating Stacks Using Lists

      • Working with queues

      • Working with deques

    • Chapter 14: Creating and Using Classes

      • Understanding the Class as a Packaging Method

      • Considering the Parts of a Class

        • Creating the class definition

        • Considering the built-in class attributes

        • Working with methods

        • Working with constructors

        • Working with variables

        • Using methods with variable argument lists

        • Overloading operators

      • Creating a Class

      • Using the Class in an Application

      • Extending Classes to Make New Classes

        • Building the child class

        • Testing the class in an application

  • Part IV: Performing Advanced Tasks

    • Chapter 15: Storing Data in Files

      • Understanding How Permanent Storage Works

      • Creating Content for Permanent Storage

      • Creating a File

      • Reading File Content

      • Updating File Content

      • Deleting a File

    • Chapter 16: Sending an E-Mail

      • Understanding What Happens When You Send E-Mail

        • Viewing e-mail as you do a letter

        • Defining the parts of the envelope

        • Defining the parts of the letter

      • Creating the E-mail Message

        • Working with a text message

        • Working with an HTML message

      • Seeing the E-mail Output

  • Part V: The Part of Tens

    • Chapter 17: Ten Amazing Programming Resources

      • Working with the Python Documentation Online

      • Using the LearnPython.org Tutorial

      • Performing Web Programming Using Python

      • Getting Additional Libraries

      • Creating Applications Faster Using an IDE

      • Checking Your Syntax with Greater Ease

      • Using XML to Your Advantage

      • Getting Past the Common Python Newbie Errors

      • Understanding Unicode

      • Making Your Python Application Fast

    • Chapter 18: Ten Ways to Make a Living with Python

      • Working in QA

      • Becoming the IT Staff for a Smaller Organization

      • Performing Specialty Scripting for Applications

      • Administering a Network

      • Teaching Programming Skills

      • Helping People Decide on Location

      • Performing Data Mining

      • Interacting with Embedded Systems

      • Carrying Out Scientific Tasks

      • Performing Real-Time Analysis of Data

    • Chapter 19: Ten Interesting Tools

      • Tracking Bugs with Roundup Issue Tracker

      • Creating a Virtual Environment Using VirtualEnv

      • Installing Your Application Using PyInstaller

      • Building Developer Documentation Using pdoc

      • Developing Application Code Using Komodo Edit

      • Debugging Your Application Using pydbgr

      • Entering an Interactive Environment using IPython

      • Testing Python Applications using PyUnit

      • Tidying Your Code Using Isort

      • Providing Version Control Using Mercurial

    • Chapter 20: Ten Libraries You Need to Know About

      • Developing a Secure Environment Using PyCrypto

      • Interacting with Databases Using SQLAlchemy

      • Seeing the World Using Google Maps

      • Adding a Graphical User Interface Using TkInter

      • Providing a Nice Tabular Data Presentation Using PrettyTable

      • Enhancing Your Application with Sound Using PyAudio

      • Manipulating Images using PyQtGraph

      • Locating Your Information Using IRLib

      • Creating an Interoperable Java Environment Using JPype

      • Accessing Local Network Resources Using Twisted Matrix

      • Accessing Internet Resources Using Libraries

  • Index

  • About the Author

Nội dung

Getting Started with Python

Talking to Your Computer

▶ Creating programs to talk to your computer

▶ Understanding what a program does and why you want to create it

▶ Considering why you want to use Python as your programming language

H aving a conversation with your computer might sound like the script of a science fiction movie After all, the members of the Enterprise on Star

Trek frequently engaged in conversations with their computer, which often responded With the emergence of interactive software like Apple's Siri, such exchanges have become increasingly plausible and commonplace.

In this chapter, we explore the significance of instructing your computer and the benefits it brings You'll learn about the necessity of a specialized language for effective communication and why Python is an excellent choice for this purpose Ultimately, the key takeaway is that programming is a unique form of communication, similar to the interactions you already have with your computer.

Understanding Why You Want to Talk to Your Computer

Engaging with a machine may feel unusual initially, but it is essential since computers cannot read minds Even if they could, communication would still be necessary for interaction Effective exchanges of information between you and the machine are crucial for any activity to take place.

8 Part I: Getting Started with Python

Effective communication between you and a computer is essential for achieving desired outcomes, as it also facilitates interactions with other machines and individuals to fulfill your requests.

Communication often occurs in a way that goes unnoticed unless you reflect on it For instance, when you engage in an online chat room, it may seem like you're directly interacting with another individual In reality, your computer is communicating with the other person's computer through the chat room platform, which serves as an intermediary This complex interaction highlights the layers of communication involved in seemingly simple online exchanges.

Commu nication with your computer may be invisible unless you really think about it.

In Figure 1-1, the central cloud represents a network of computers running various applications, enabling seamless communication between you and your friend through a chat application Despite the complex processes occurring in the background, the experience feels effortless and intuitive, making the act of chatting appear straightforward and invisible.

Chapter 1: Talking to Your Computer

Knowing that an Application is a Form of Communication

Computer communication relies on various applications, each designed for specific tasks For instance, you use one app for checking emails, another for online shopping, and yet another for creating presentations These applications enable users to convey ideas to computers in an understandable format, providing the necessary tools to manipulate data appropriately The data required for a presentation differs significantly from that used in purchasing a gift, highlighting the need for distinct applications tailored to each task This differentiation ensures that both users and computers can effectively interact with the data.

In today's digital landscape, there are applications available to address nearly every conceivable need, many of which you may not have even considered yet With millions of applications developed over the years, it can be challenging to grasp the potential of creating a new application for interacting with your computer The key lies in understanding your data and how you wish to engage with it Some data may not be common enough to attract a programmer's attention, or you might require it in a specific format that existing applications do not support In such cases, developing a custom application becomes essential to effectively communicate with your data.

This article explores the development of applications tailored to unique data sets, emphasizing the importance of addressing specific access needs For instance, having a video library database without a user-friendly access method highlights the necessity for a customized solution By creating an application that effectively manages both the unique data and individual requirements, users can enhance their interaction with the information they need.

Thinking about procedures you use daily

A procedure is simply a set of steps you follow to perform a task For example, when making toast, you might use a procedure like this:

1 Get the bread and butter from the refrigerator.

2 Open the bread bag and take out two pieces of toast.

3 Remove the cover from the toaster.

10 Part I: Getting Started with Python

4 Place each piece of bread in its own slot.

5 Push the toaster lever down to start toasting the bread.

6 Wait for the toasting process to complete.

7 Remove toast from the toaster.

While your method for making toast may differ, it's important to note that you typically wouldn't butter the bread before toasting it Additionally, remember to remove the bread from its wrapper, as toasting it with the packaging could lead to undesirable outcomes Although many people don't consciously consider the process, they follow a similar procedure when making toast.

Computers rely on clear procedures to execute tasks, requiring users to specify the steps, their sequence, and any exceptions that may lead to errors Essentially, an application serves as a written guide that instructs the computer on what actions to take, when to perform them, and how to carry them out By leveraging the procedural knowledge you've accumulated throughout your life, you can easily adapt this understanding to meet the specific requirements of a computer for various tasks.

When I was in grade school, our teacher asked us to write a paper about making toast After we turned in our papers, she brought in a toaster and some loaves of bread Each paper was read and demonstrated None of our procedures worked as expected, but they all produced humorous results In my case, I forgot to tell the teacher to remove the bread from the wrapper, so she dutifully tried to stuff the piece of bread, wrapper and all, into the toaster The lesson stuck with me Writing about procedures can be quite hard because we know precisely want we want to do, but often we leave steps out — we assume that the other person also knows precisely what we want to do.

Life is filled with experiences that depend on effective procedures, much like the checklist pilots use before takeoff to ensure safety A well-structured procedure is crucial, as it can prevent catastrophic failures, such as plane crashes Although mastering the art of writing an effective procedure requires time and practice, it is certainly achievable, often necessitating multiple attempts to perfect it.

Chapter 1: Talking to Your Computer works completely, but eventually you can create one Writing procedures down isn’t really sufficient, though — you also need to test the procedure by using someone who isn’t familiar with the task involved When working with computers, the computer is your perfect test subject.

Seeing applications as being like any other procedure

A computer functions similarly to a grade school teacher by following a defined procedure when executing an application When you develop an application, you outline a series of steps for the computer to carry out in order to achieve a specific task Omitting any step can lead to unexpected results, as the computer lacks the ability to infer your intentions or automatically perform tasks Ultimately, the computer operates solely based on the precise procedure you provide.

Understanding that computers take things literally

Getting Your Own Copy of Python

Getting Your Own Copy of Python

▶ Obtaining a copy of Python for your system

▶ Finding and using Python on your system

▶ Ensuring your installation works as planned

To create applications, you typically need supporting software unless you opt for the challenging route of writing in machine code, which most programmers avoid If you're interested in developing applications using Python, you'll require specific tools that assist in writing Python code, offer helpful resources, and allow you to execute your code This chapter guides you through obtaining and installing the Python application on your hard drive, locating the installed tools for use, and testing your installation to ensure everything functions correctly.

Downloading the Version You Need

Every platform, defined by its specific combination of computer hardware and operating system software, has unique rules for running applications Python simplifies this process by allowing you to write code that is compatible across all supported platforms, while the Python application handles the necessary translation for each platform To ensure proper functionality, it's essential to have a version of Python that is compatible with your specific platform.

22 Part I: Getting Started with Python

✓ Hewlett-Packard Unix (HP-UX)

✓ Mac OS X (comes pre-installed with the OS)

✓ Microsoft Disk Operating System (MS-DOS)

✓ Operating System 390 (OS/390) and z/OS

✓ Windows 32-bit (XP and later)

This book is compatible with Windows, Mac OS X, and Linux platforms, and its examples are designed to work on various systems without relying on platform-specific code If you try it on a different platform, please share your experience at John@JohnMuellerBooks.com As of now, the latest version of Python is 3.3.4, and I will provide updates on my blog at http://blog.johnmuellerbooks.com, where you can also find answers to questions related to the book.

To download the appropriate version for your platform, visit http://www.python.org/download/releases/3.3.4/ and scroll halfway down the page to access the hidden download section You will find options for Windows, Mac OS X, and Linux, allowing you to select the version that suits your needs.

Chapter 2: Getting Your Own Copy of Python you with the default setup that is used in this book The platform-specific links on the left side of the page show you alternative Python configurations that you can use when the need arises For example, you may want to use a more advanced editor than the one provided with the default Python pack- age, and these alternative configurations can provide one for you.

The Python download page con tains links for all sorts of versions.

To explore additional platforms, click the "Other" link on the left side of the page, where you'll find a list of Python installations for various systems, as illustrated in Figure 2-2 It's important to note that many of these installations are supported by volunteers rather than the official Python developers for Windows.

Mac OS X, and Linux Make sure you contact these individuals when you have installation questions because they know how best to help you get a good installation on your platform.

24 Part I: Getting Started with Python

Python available on all sorts of platforms.

After you download your copy of Python, it’s time to install it on your system The downloaded file contains everything needed to get you started:

✓ Integrated DeveLopment Environment (IDLE) application

✓ Uninstaller (only on platforms that require it)

Chapter 2: Getting Your Own Copy of Python

This book is designed for users of the default Python installation available at [python.org](http://www.python.org/download/releases/3.3.4/) The subsequent sections will guide you through the installation process of Python on the three main platforms supported: Windows, Mac OS X, and Linux.

Installing applications on a Windows system follows a similar procedure across different types of software The key distinction lies in locating the downloaded file to initiate the installation This process is applicable to any Windows system, regardless of whether you are using the 32-bit or 64-bit version of Python.

1 Locate the downloaded copy of Python on your system.

The file name for Python installation varies, typically appearing as python-3.3.4.msi for 32-bit systems and python-3.3.4.amd64.msi for 64-bit systems The version number, in this case, 3.3.4, is included in the filename and corresponds to the version utilized in this book.

2 Double-click the installation file.

When you attempt to open a Python installation file, you may encounter a security warning dialog box prompting you to confirm whether to run the file If this occurs, simply click "Run" to proceed Following this, a Python Setup dialog box will appear, which may vary based on the version of the Python installer you have downloaded.

The setup process begins by asking you who should have access to Python.

26 Part I: Getting Started with Python

3 Choose a user installation option (the book uses the default setting of Install for All Users) and click Next.

During the Python installation process, you will be prompted to specify an installation directory, as illustrated in Figure 2-4 Opting for the default destination can streamline the process and save you time, but you have the flexibility to choose any location for the installation.

Decide on an installation location for your copy of

Installing Python in the Windows \Program Files or \Program Files (x86) folder can lead to issues due to two main reasons: the folder name contains a space, complicating access from applications, and it typically requires administrator privileges, resulting in frequent conflicts with the User Account Control (UAC) feature of Windows.

4 Type a destination folder name, if necessary, and click Next.

Python asks you to customize its installation, as shown in Figure 2-5.

Enabling the "Add python.exe to Path" option during installation is essential as it allows easy access to Python from the Command Prompt, saving you time in the future While you may not need to focus on this feature immediately, it's beneficial to have it enabled The book assumes this feature is activated, and you can rest assured that the other options shown in Figure 2-5 are enabled by default, ensuring you have full access to Python's capabilities.

Chapter 2: Getting Your Own Copy of Python

Customize your instal lation to meet your needs.

5 (Optional) Click the down arrow next to the Add python.exe to Path option and choose the Will Be Installed On Local Drive option.

During the installation process, a User Account Control dialog box may appear, prompting you to confirm the installation If this occurs, click "Yes" to proceed Once confirmed, the installation will continue, and you will eventually see an "Installation Complete" dialog box.

Python is ready for use.

Most Mac systems come with a pre-installed version of Python, but it is often outdated, reflecting the age of the device For the purposes of this guide, the existing installation should suffice, as you will focus on getting started with Python rather than pushing the boundaries of its programming capabilities.

28 Part I: Getting Started with Python

Interacting with Python

▶ Using commands to perform tasks

Every application you develop interacts with the computer and its data, making data the core reason for any application's existence Whether it's a complex program or a simple game like Solitaire, each application manipulates data in some form The acronym CRUD encapsulates the fundamental operations that most applications perform.

Understanding CRUD operations is essential for grasping how applications manage data on your computer Before an application can access this data, you must use a programming language to outline tasks in a format the computer can interpret This chapter focuses on introducing Python, which translates your list of desired actions into machine-readable instructions, enabling effective data manipulation.

40 Part I: Getting Started with Python

Python provides various methods for interacting with the language, including the Integrated Development Environment (IDLE), which facilitates application development However, for experimentation or running existing applications, the command-line version of Python is often more effective It offers enhanced control over the Python environment through command-line switches, consumes fewer resources, and features a minimalist interface, allowing users to concentrate on coding rather than navigating a graphical user interface (GUI).

Understanding the importance of the README file

Many applications include a README file The

The README file is an essential resource that contains updated information not included in the official documentation prior to an application's production release Unfortunately, many users overlook this file, often unaware of its existence, which leads to missed insights about their new product For instance, Python includes a README.txt file in the \Python33 directory, offering valuable and intriguing details that users should explore.

✓ How to build a copy of Python for Linux systems ✓ Where to find out about new features in this version of Python ✓ Where to find the latest version of the

Python documentation ✓ How to convert your older Python applica tions to work with Python 3.3.x

✓ What you need to do to test custom Python modifications

✓ How to install multiple versions of Python on the same system ✓ How to access bug and issue tracking for Python

✓ How to request updates to Python ✓ How to find out when the next version of Python will come out

Reading the README file is essential for mastering Python, as it equips you with valuable knowledge that will impress others and spark their curiosity, leading them to seek your insights and expertise.

Of course, you could always just sit there, thinking that the README is just too much effort to read.

Depending on your platform, you might have multiple ways to start the com- mand line Here are the methods that are commonly available:

✓ Select the Python (command-line) option found in the Python 3.3 folder

This option starts a command-line session that uses the default settings.

✓ Open a command prompt or terminal, type Python, and press Enter Use this option when you want greater flexibility in configuring the Python environment using command-line switches.

To open a command-line session with Python, navigate to the Python installation folder, typically found at C:\Python33 on Windows, and execute the Python.exe file This method not only launches Python with default settings but also allows for elevated privileges, enabling access to secured resources, and offers the option to modify executable file properties by adding command-line switches.

When you initiate Python from the command line, you will eventually see a prompt that indicates the Python version, the host operating system, and provides guidance on accessing more information Your prompt may vary slightly based on your operating system, whether you're using IDLE instead of the command line, your system's configuration, or the specific version of Python installed.

The Python command prompt tells you a bit about the Python environment.

42 Part I: Getting Started with Python

Using the command line to your advantage

While this section may initially appear complex, the information it contains is valuable and will be useful in the future Although you might not need it right away, take some time to familiarize yourself with the content now, so you can easily refer back to it when necessary.

To initiate Python from the command prompt, simply type "Python" and hit Enter Additionally, you have the option to include extra parameters to modify Python's functionality.

Options, also known as command-line switches, start with a minus sign followed by one or more letters For instance, to access help for Python, you would type "Python -h" and hit Enter, which provides further information on using Python via the command line A detailed description of these options will be provided later in this section.

To execute a Python file, simply provide its filename as input, allowing Python to load and run the specified file You can easily run any example applications included in the downloadable code by inputting the name of the corresponding file, such as SayHello.py for the "Say Hello" example.

To run this example, you type Python SayHello.py and press Enter.

An application can receive extra information, known as an argument, to influence its operation While arguments are an important aspect of application functionality, they will be explored in more detail later in the book.

Many of the options presented may not seem relevant at the moment, but they are included for easy access when needed This logical placement within the book allows you to familiarize yourself with the available resources, while also providing the flexibility to skip this content until it becomes necessary.

Python uses case-sensitive options For example, -s is a completely different option from -S The Python options are

✓ -b: Add warnings to the output when your application uses certain Python features that include: str(bytes_instance), str(bytearray_ instance), and comparing bytes or bytearray with str().

✓ -bb: Add errors to the output when your application uses certain Python features that include: str(bytes_instance), str(bytearray_ instance), and comparing bytes or bytearray with str().

✓ -B: Don’t write py or pyco files when performing a module import.

The `-c` command allows you to initiate a program using the information specified by cmd, while also instructing Python to cease processing any subsequent details as options, treating them instead as part of the command.

✓ -d: Start the debugger (used to locate errors in your application).

✓ -E: Ignore all the Python environment variables, such as PYTHONPATH, that are used to configure Python for use.

The command "-h" provides on-screen help regarding options and basic environment variables in Python After displaying this information, Python exits immediately, ensuring that users can review the help details without any additional actions.

✓ -i: Force Python to let you inspect the code interactively after running a script It forces a prompt even if stdin (the standard input device) doesn’t appear to be a terminal.

Writing Your First Application

▶ Working with the Integrated DeveLopment Environment (IDLE)

▶ Seeing how the first application works

Application development is often perceived as a mystical art performed by tech-savvy individuals, but in reality, it is a straightforward process grounded in practical skills and techniques.

Application development involves a series of processes that, while not strictly procedural, are certainly not magical As Arthur C Clarke famously stated, “Any sufficiently advanced technology is indistinguishable from magic.” This chapter aims to demystify the development process and familiarize you with the technology behind it By the end, you will have the skills to create a simple application without relying on any form of magic.

Using tools can significantly simplify the process of writing applications, and while Python can be used without them, employing a tool enhances the experience In this chapter, we will explore the Integrated Development Environment (IDLE) that comes with Python, which offers more functionality than the command-line tool previously discussed IDLE allows for a more efficient and user-friendly approach to application development, making it easier to write and manage your Python code.

58 Part I: Getting Started with Python

While IDLE is a comprehensive tool that comes with Python and meets all your development needs, there are many other tools available for writing Python applications As your programming skills advance, you may prefer alternatives like Komodo Edit for a more user-friendly experience For a detailed list of various development tools, you can visit the Python wiki at https://wiki.python.org/moin/IntegratedDevelopmentEnvironments.

You can develop any Python application using a simple text editor that outputs plain text, but this method can be inefficient To streamline the development process, developers have created Interactive Development Environments (IDEs) The default IDE for Python is IDLE, but there are numerous other IDEs available that also support Python programming.

Integrated Development Environments (IDEs) offer a diverse range of features, which is why numerous options exist in the market Among them, IDLE stands out by providing a fundamental set of functionalities commonly found in many IDEs, ensuring essential capabilities for developers.

✓ Recognize and highlight keywords and certain types of special text.

✓ Perform both simple editing (such as cut, copy, and paste) and code- specific editing (such as showing the parentheses that surround an expression).

✓ Save and open Python files.

✓ Browse the Python path to make locating files easy.

✓ Browse and locate Python classes.

✓ Perform simple debugging tasks (removing errors from the code).

IDLE provides a comprehensive GUI that simplifies many tasks compared to the command-line version of Python, which lacks some of IDLE's features While debugging is possible through the command line, it can be a challenging and error-prone experience In contrast, IDLE makes the debugging process significantly easier and more user-friendly.

Chapter 4: Writing Your First Application

You find IDLE in the Python 3.3 folder on your system as IDLE (Python GUI)

Upon clicking or double-clicking the entry, the IDLE editor appears, displaying information about the Python host along with command suggestions The specific details visible may vary based on your platform, Python version, IDLE configuration, and system settings, resulting in potentially different screenshots.

IDLE pro vides you with a GUI editing experience for your application code.

60 Part I: Getting Started with Python

IDLE offers the same commands as the command-line version of Python, but it does not display them all, as it is designed to leverage its GUI features for ease of use Users can still access help mode by typing help() and pressing Enter, even though this command is not included in the initial command list for IDLE, unlike in the command-line version.

You can access all the same commands in IDLE that you can with the com mand line version.

Chapter 4: Writing Your First Application

The book lacks the color coding visible when using help( ), but this feature is available in the editor, enhancing the clarity of commands and distinguishing them from other text To exit help mode, simply press Enter Similar to the command-line version, descriptive text appears with each action performed.

To execute a command in Python, type print('This is some text.') and press Enter to see the expected output The command appears in purple, indicating it's a function, while the data within the command is shown in green, and the output itself is displayed in blue This color coding enhances readability, demonstrating one of the many advantages of using IDLE over the command line for coding tasks.

With color coding, you can easily determine the use for each kind of text in an application.

62 Part I: Getting Started with Python

IDLE makes obtaining the help you need easy Look at the Help menu and you see three entries for obtaining help:

✓ About IDLE: Provides you with the latest information about IDLE.

✓ IDLE Help: Shows you a text file containing information about working with the IDLE IDE For example, this is where you find a list of the IDLE commands.

✓ Python Docs: Contains information required to work with Python com- mands and other elements.

To access additional help in IDLE, navigate to Help➪About IDLE, where you'll find the About IDLE dialog box This dialog provides URLs for further assistance and features buttons that display helpful text files, particularly the README and NEWS files To exit the dialog box, simply click Close.

IDLE dialog box contains useful infor mation that you might not see otherwise.

The content displayed when selecting Help ➪ Python Docs varies based on your platform, as illustrated by the Windows version of the dialog box in Figure 4-5 The Python Docs file offers essential information for utilizing Python in application development, including a tutorial section that provides additional tips to enhance your learning experience after completing this book.

Chapter 4: Writing Your First Application

Docs to dis cover more about using

IDLE is basically a fancy text editor, when you think about it, so it’s not sur- prising that you can configure it to perform the task of editing text better

To configure IDLE preferences, access the IDLE Preferences dialog box by selecting the Options menu Here, you can customize various settings, including the font style and size used for text display The Font/Tabs tab allows you to adjust the font specifications and set the number of spaces for indentation, which is essential for proper code formatting.

IDLE enhances code readability through color coding, allowing users to customize highlighting colors, as illustrated in Figure 4-7 Users can save their color selections as themes, enabling the creation of different themes tailored to specific environments, such as one for bright conditions on a laptop and another for low-light settings.

64 Part I: Getting Started with Python

IDLE to meet your particular require ments.

Change the highlighting used for text so that you can see it better.

Chapter 4: Writing Your First Application

Talking the Talk

Performing Common Tasks

Performing Advanced Tasks

The Part of Tens

Ngày đăng: 24/08/2021, 22:34

w