Introduction to Python Programming & GUI with PyQt PDF
Document Details
Uploaded by ReplaceableNoseFlute6855
University of South Africa
2012
B.M. Harwani
Tags
Summary
This textbook introduces Python programming, focusing on practical examples. It covers Python fundamentals, and GUI application development in PyQT, along with database handling. The book is suitable for programmers at all levels.
Full Transcript
Open Rubric Copyright Introduction to Python® Programming and Developing GUI Applications with PyQT B.M. Harwani Publisher and General Manager, Course Technology PTR: Stacy L. Hiquet Associate Director of Marketing: Sarah Panella Manager of Editorial Services: Heather Talbot Marketing Manager:...
Open Rubric Copyright Introduction to Python® Programming and Developing GUI Applications with PyQT B.M. Harwani Publisher and General Manager, Course Technology PTR: Stacy L. Hiquet Associate Director of Marketing: Sarah Panella Manager of Editorial Services: Heather Talbot Marketing Manager: Mark Hughes Senior Acquisitions Editor: Mitzi Koontz Project Editor: Kim Benbow Technical Reviewer: Keith Davenport Copy Editor: Gene Redding Interior Layout: MPS Limited, a Macmillan Company Cover Designer: Mike Tanamachi Indexer: BIM Indexing Services Proofreader: Brad Crawford © 2012 Course Technology, a part of Cengage Learning. ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced, transmitted, stored, or used in any form or by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher. For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800- 354-9706 For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions Further permissions questions can be emailed to [email protected] Python and the Python logos are trademarks or registered trademarks of the Python Software Foundation. All other trademarks are the property of their respective owners. All images © Cengage Learning unless otherwise noted. Library of Congress Control Number: 2011936040 ISBN-13: 978-1-4354-6097-3 ISBN-10: 1-4354-6097-9 eISBN-10: 1-4354-6098-7 Course Technology, a part of Cengage Learning 20 Channel Center Street Boston, MA 02210 USA Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at: international.cengage.com/region Cengage Learning products are represented in Canada by Nelson Education, Ltd. For your lifelong learning solutions, visit courseptr.com Visit our corporate website at cengage.com Printed in the United States of America 1 2 3 4 5 6 7 13 12 11 Dedication This book is dedicated to my mother, Mrs. Nita Harwani, and American inventor and entrepreneur, the late Steve Jobs. My mother is next to God for me, and whatever I am today is because of the moral values taught by her. Steve Jobs, co-founder, chairman, and chief executive officer of Apple Inc. has been and will always be a great inspiration for me. Acknowledgments I owe a debt of gratitude to Mitzi Koontz, Senior Acquisitions Editor at Course Technology, Cengage Learning for her initial acceptance and giving me an opportunity to create this work. I am highly grateful to the whole team at Cengage for their constant cooperation and contribution to create this book. I must thank Keith Davenport, the technical editor for his excellent, detailed review of the work and the many helpful comments and suggestions he made. He offered a significant amount of feedback that helped to improve the book’s content. He played a vital role in improving its structure and the quality of information. Special thanks to Gene Redding, the copy editor for first class structural and language editing. I appreciate his efforts in enhancing the contents of the book and giving it a polished look. Big and ongoing thanks to Kim Benbow, my project editor, for doing a great job and her sincere efforts to get the book published on time. A great big thank you goes to the production staff who worked tirelessly to produce this book. I enjoyed working with each of you. I am also thankful to my family (my small world): Anushka (my wife) and my two little darlings, Chirag and Naman, for always inspiring me and giving me the courage to work harder. I should not forget to thank my dear students who have been good teachers for me, as they help me to understand the basic problems they face with a subject, which enables me to directly teach those topics. Their endlessly interesting queries help me to write books with a practical approach. About the Author B.M. Harwani is founder and owner of Microchip Computer Education (MCE), based in Ajmer, India, which provides computer education on all programming and web developing platforms. Harwani graduated with a BE in computer engineering from the University of Pune, and also has a C Level (master’s degree) in computer technology from DOEACC, Government of India. Being involved in the teaching field for over 16 years, he has developed the art of explaining even the most complicated technical topics in a straightforward and easily understandable fashion. He has written several books on various subjects that include JSP, JSF, EJB, PHP,.NET, Joomla, jQuery, and smartphones. His latest books include Beginning Web Development for Smartphones (Shroff, 2011), Core Data iOS Essentials (Packt Publishing, 2011) and Blogging with WordPress 3 for Beginners (CreateSpace, 2011). He also writes articles on a variety of computer subjects, which can be seen on a number of websites. To find out more, visit his blog at http://bmharwani.com/blog. Table of Contents Copyright 2 Acknowledgments 4 About the Author 5 Contens 6 Intrduction 11 Chapter 1 Python and Its Features 15 1.1 Python 16 1.2 Installing Python 19 1.3 Interacting with Python 24 1.4 Writing Your First Python Program 27 1.5 Data Types in Python 29 1.6 Basic Elements in a Program 31 1.7 Comments 32 1.8 Continuation Lines 33 1.9 Printing 34 Summary 37 Chapter 2 Getting Wet in Python 38 2.1 Performing Arithmetic Operations 39 2.2 Bitwise Operations 49 2.3 Complex Numbers 52 2.4 Making Decisions 54 2.5 Logical Operators 58 2.6 Chaining Comparison Operators 60 2.7 Loops 63 Summary 73 Chapter 3 Sequences 74 3.1 Sequences 75 3.2 Strings 76 3.3 Lists 90 3.4 Tuples 96 3.5 Sets 100 Summary 103 Chapter 4 Functions and Modules 104 4.1 Functions 105 4.2 Function Attributes 115 4.3 Recursion 117 4.4 Iterators 120 4.5 Modules 124 Summary 129 Chapter 5 Classes 130 5.1 The Class Statement 131 5.2 Class Methods 139 5.3 Static Methods 141 5.4 Garbage Collection 144 5.5 Inheritance 146 5.6 Multilevel Inheritance 153 5.7 Operator Overloading 163 5.8 Descriptors 168 Summary 172 Chapter 6 File Handling 173 6.1 Exception Handling 186 6.2 Raising an Exception 191 Summary 193 Chapter 7 PyQt 194 7.1 Qt Toolkit 196 7.2 PyQt 197 7.3 Installing PyQt 198 7.4 Window and Dialogs 201 7.5 Creating a GUI Application with Code 202 7.6 Using Qt Designer 205 7.7 Understanding Fundamental Widgets 220 7.8 Event Handling in PyQt 223 7.9 First Application in Qt Designer 224 7.10 Using Custom Slots 231 7.11 Converting Data Types 234 7.12 Defining Buddies 237 Summary 242 Chapter 8 Basic Widgets 243 8.1 Using Radio Buttons 244 8.2 Using Checkboxes 249 8.3 Entering Integer and Float Values Using a Spin Box 256 8.4 ScrollBars and Sliders 260 8.5 Working with a List Widget 266 Summary 274 Chapter 9 Advanced Widgets 275 9.1 Displaying System Clock Time in LCD Format 276 9.2 Working with Calendar and Displaying Dates in Different Formats 280 9.3 Using Combo Box 286 9.4 Displaying a Table 291 9.5 Displaying Web Pages 295 9.6 Displaying Graphics 299 Summary 303 Chapter 10 Menus and Toolbars 304 10.1 Understanding Menus 305 10.2 Creating a Toolbar 312 10.3 Dock Widget 319 10.4 Tab Widget 325 10.5 Converting a Tab Widget 332 Summary 337 Chapter 11 Multiple Documents and Layouts 338 11.1 Multiple-Document Interface 339 11.2 Layouts 347 Summary 355 Chapter 12 Database Handling 356 12.1 Why MySQL? 357 12.2 Creating a Database 361 12.3 Database Maintenance Through Console-Based Programs 365 12.4 Database Maintenance Through GUI Programs 374 Summary 387 Index 388 Introduction Python is an interpreted, general-purpose, high-level programming language that is very popular among developers and professionals because of its vast library of addon modules. It is a platform-independent scripted language that is supported by many individuals as an open-source project. The fact that it is freely available and runs on all platforms makes it ever more popular. The goal of Introduction to Python Programming and Developing GUI Applications with PyQT is to teach the Python programming language through practical examples. Whether you are new to computers or are an experienced programmer, this book is intended to help you develop your programming skills. It is written with the requirements of all levels in mind —developers, professionals, and beginners. The book begins with a solid introduction of Python from scratch—loops, control structures, sequences, functions, classes, and exception handling. Thereafter, the book explains persistence through file handling and targets developers by introducing GUI application development in PyQT. As you read through the book, you will acquire the skills needed for building practical Python programming applications and will learn how these skills can be put into use in real-world scenarios. Like any good book, Introduction to Python Programming explains the more basic concepts, one step at a time, by writing small programs to demonstrate each step. Gradually, once the reader is acquainted with logical blocks, the book explains using the blocks for understanding more complex concepts. By the time you finish the book, you will understand how to break problems down into manageable chunks, and then refine your code into applications. How This Book is Organized This book starts with a discussion of Python’s basics, beginning with easy examples, and then gradually going deeper to uncover the more complex topics of GUI programming in Python. By the end of the book, readers will also have an understanding of using back-end databases for storing and fetching information. Chapter 1, “Python and its Features”: In this chapter, you will have a detailed introduction to Python and its features, such as installing Python on different platforms, interacting with Python through Command Line mode and the IDLE IDE. You will also learn to write your first Python program. The chapter also introduces the Python basics, like its different data types, literals, variables, and keywords. Finally, the chapter explains how to write comments, continuation lines, and print messages. Chapter 2, “Getting Wet in Python”: In this chapter, you will learn to apply arithmetic operations and different logical and membership operators in Python programs. You will see the use of escape sequences. You will learn to get data from the user as well as process incoming data. You will also see how to convert data into different types, learn to display octal and hexa values, perform bitwise operations, and use complex numbers. You will also learn how to use the if...elsestatement in making decisions. Finally, the chapter explains how to use whileand forloops for doing repetitive tasks. Chapter 3, “Sequences”: This chapter focuses on using different containers. You will learn to perform different operations on strings, including concatenating strings, splitting strings, and then converting them into different cases, such as uppercase, title case, and lowercase, etc. Also, you will learn to do list slicing, searching elements in tuples, and performing operations on sets, such as finding their union, intersection, and differences. You will learn how key/value pairs are maintained in a dictionary and how to append, delete, or and modify key/value pairs. Finally, the chapter explains how to create one- and two-dimensional arrays. Chapter 4, “Functions and Modules”: In this chapter, you will learn about different statements that define and return values from functions. Also, you will learn to use default value parameters and keyword arguments in a function, as well as use local and global variables. The chapter explains how to create lambda functions for smaller expressions. Also, you will learn how to apply functions to sequences using different function attributes and implement recursion. For accessing collections of data, the chapter explains how to use iterators, generators, and generator expressions. You will learn to import and use modules for built-in functions. The chapter also explains how to pass command-line arguments to a Python program. Chapter 5, “Classes”: This chapter focuses on classes. You will learn how to define a class, define functions for it, initialize its instance variables, and use class and static methods. You will also learn to use class attributes to display specific information related to the class. You will learn the concept of garbage collection and its role in freeing up memory consumed by objects that are out of scope. Also, you will learn to apply single, multilevel, and multiple inheritance through running practical examples. You will learn the use of private and public access specifiers and how to apply method overriding and operator overloading to perform arithmetic operations on instances. Finally, the chapter explains polymorphism and setting and getting values of instance attributes through properties and descriptors. Chapter 6, “File Handling”: In this chapter, you will learn to perform different operations on files. You will learn to open a file in different modes and to read its contents, update existing content, delete content, and append new content. You will also see how to copy a file, read a file sequentially or randomly, and read only specific content. You will learn to create a binary file as well as pickle and unpickle objects. Finally, the chapter explains how to implement exception handling and the procedure for raising exceptions. Chapter 7, “PyQt”: In this chapter, you will be introduced to the Qt toolkit, Qt Designer, and PyQt. You will learn about different Qt Designer components, such as the toolbar, the Object Inspector, the Property Editor, and the Widget Box. You will also learn to create a GUI application through coding. Also, you will learn about the fundamental Label, Line Edit, and Push Button widgets as well as learn to develop applications using them. You will also learn about signal/slot connection in the Qt Designer and how to connect signals to both predefined slots and to custom slots. Chapter 8, “Basic Widgets”: This chapter demonstrates how to create a GUI application using Radio Buttons, which enable the user to select one option out of several. You will also learn how to select more than one option by using CheckBoxes and specify integers as well as float values using Spin Boxes. Also, you will learn to use ScrollBars and Sliders to display large documents and represent integer values. Finally, the chapter explains how to display options with a List widget, add items to a List widget, and delete and edit existing items in a List widget. Chapter 9, “Advanced Widgets”: This chapter explains how to access and display system clock time in LCD digits. You also will see how to display a calendar and display a selected date in different formats. You will learn to create an application that displays options with a Combo Box, displays information with a Table widget, displays web pages, and displays graphics. Chapter 10, “Menus and Toolbars”: In this chapter, you will learn to create menus and toolbars. Also, you will learn about the Action Editor and how it can help you define actions for menus and toolbars. You will also learn how to manage application resources in one place through a resource file. You will see how to create dockable windows and how to display information in small chunks with the Tab widget. Finally, the chapter explains how to convert a Tab widget into a Tool Box or Stacked widget. Chapter 11, “Multiple Documents and Layouts”: In this chapter, you will learn to manage multiple documents in a main window through an MDI. You will see how child windows in MdiArea can be arranged in cascading and tile fashions. You will also learn to place a collection of widgets that do similar tasks in a Group Box. You will also learn to organize widgets in different layouts. Chapter 12, “Database Handling”: In this chapter, you will learn to install and use the MySQLdb module, which is required in order to access the MySQL Database Server through Python. Also, you will learn to maintain a database through console-based programs and through GUI programs. You will also learn to write Python scripts to insert, fetch, delete, search, and update rows in a database table. Companion Website Downloads You may download the companion website files from www.courseptr.com/downloads. Please note that you will be redirected to the Cengage Learning website. Chapter 1. Python and Its Features This chapter covers the following: Introduction to Python and its features Installing Python on different platforms Interacting with Python through Command Line Mode and IDLE Writing Your First Python Program Understanding data types and basic elements in Python Writing comments and continuation lines and printing messages Python Python is a very powerful high-level, dynamic object-oriented programming language created by Guido van Rossum in 1991. It is implemented in C, and relies on the extensive portable C libraries. It is a cross-platform language and runs on all major hardware platforms and operating systems, including Windows, Linux/UNIX, and Macintosh. Python has an easy-to-use syntax and is quite easy to learn, making it suitable for those who are still learning to program. Python has a rich set of supporting libraries, and many third-party modules are available for it. Python is a programming language that also supports scripting, making it suitable for rapid application development. Python comes with a powerful and easy to-use graphical user interface (GUI) toolkit that makes the task of developing GUI applications in Python quite easy. It is freely available. Python Implementations Python currently has three implementations, known as CPython, Jython, and Iron-Python. In this book, you will be using CPython, the most widely used implementation, which I will refer to as just Python for simplicity. A small description of all three implementations is as follows: CPython. Classic Python (often just called Python) is the fastest, most up-to-date, and complete implementation of Python. It is implemented in C (i.e., its libraries and modules are all coded in standard C). It is cross-platform and runs on almost all platforms. Jython. Jython is a Python implementation that is Java Virtual Machine (JVM) compliant. With Jython, we can use all Java libraries and frameworks. IronPython. IronPython is a Python implementation for the Microsoft designed Common Language Runtime (CLR), popularly known as.NET. With Iron Python, you can use all CLR libraries and frameworks. Features of Python As mentioned earlier, Python is a scripting language that includes a vast library of add-on modules. It supports integration of pre-built components for creating complex applications. Python has full access to operating system (OS) services. Following are a few of its features: Python is easy to learn. Programmers familiar with traditional languages will find all the familiar constructs, such as loops, conditional statements, arrays, and so on. It has easier to read syntax. It avoids the use of punctuation characters like { } $ / and \. It uses white space to indent lines for defining blocks instead of using brackets. Python is free. You can download and install any version of Python and use it to develop software for commercial or personal applications without paying a penny. Python is developed under the open-source model. You can copy Python, modify it, and even resell it. It comes with a large number of libraries included, and there are many more that you can download and install. Python can be integrated with other languages, like C, C++, and Java. That is, the components written in these languages can be embedded with Python programs, thus making it easier to develop complex solutions. Python is an interpreted language, therefore it supports a complete debugging and diagnostic environment making the job of fixing mistakes much faster. Also, the software development is quite rapid and flexible in it. Python is a good choice for web development, networking, games, data processing, and business applications. For efficient memory management, Python uses garbage collection, so you don’t have to worry about memory leaks. The Python run-time environment handles garbage collection of all Python objects. Each object has a reference counter to make sure that no live objects are removed. Only the object with a reference counter value equal to 0 is garbage collected. Python supports exception handling. That is, errors are raised as exceptions so that you can take corrective measures. Python signals almost all errors with an exception. However, you cannot take advantage of Python’s features unless you install it and begin using it. So, read on to understand how Python is installed on different platforms. Installing Python To install Python, you will need to download its most recent distribution from the following URL: www.python.org. Don’t worry if you already have an earlier version of Python installed on your machine. You can have multiple versions of Python on the same computer. The new version of Python is installed in a separate location and will not interfere with the older version on your computer. Many Linux distributions and Mac OS X come with Python 2.x as part of the operating system. Let’s have a look at the steps for installing Python on Microsoft Windows. Installing Python on Microsoft Windows For Microsoft Windows, download the latest Python installer program from its site. This book is based on Python version 3.2, and its installer program is python-3.2.msi. Download it, and then double-click on it to begin the installation wizard. Note You need to be logged in as the administrator to run the install. The first dialog box of the installation wizard, shown in Figure 1.1, asks whether you want to install this Python version for all the users or only for one user (i.e., the administrator). Select the option Install For All Users, followed by selecting the Next button. Figure 1.1. Python installation wizard. In the next dialog, you will be asked for the destination folder where you want to install Python files. The wizard also displays a folder name by default that represents the Python version being installed. In this case, the default folder will be C:\Python32\. You can either keep the default folder or specify a new folder for your Python installation. Select the Next button to continue. If you have a previous installation, then you will be asked whether you wish to back up replaced files. The option to make backups is already selected, and the default folder for the backup appears as C: \Python32\BACKUP. Click Next to continue. The next dialog is to specify the Python features (i.e., the components) that you want to install, as shown in Figure 1.2. You can select or unselect the features as per your requirement. On selecting a feature, the hard disk space needed by its files will be displayed. Keeping the default components selected, click Next to continue. Figure 1.2. Selecting Python components to install. The installer program will copy the Python files to the selected folder, and you will be asked to select the Finish button to exit the installation wizard. On successful installation of Python, you will find a new group, called Python 3.2, added to your Windows system that you can see by selecting the Start > All Programs option. The Python 3.2 group shows several options, such as IDLE (Python GUI), Module Docs, Python (Command Line), Python Manuals, and Uninstall Python. On selecting the Python (Command Line) menu item, you see the Python Command Line window displaying the Python prompt (>>>), as shown in Figure 1.3. The window informs you which version of Python is running, the date the version was released, and a few hints for viewing copyright, credits, and license information. Below the hints messages is displayed the Python prompt (>>>) where you can issue Python commands. To execute Python commands, you write them at the prompt followed by pressing the Enter key. To close the Python Command Line window, press Ctrl+Z followed by the Enter key. Figure 1.3. Python Command Line window. [View full size image] Congratulations for successfully installing Python on Windows! Now I’ll show you how to install Python on Mac OS X. Installing Python on the Mac Python is part of the Mac OS environment. Tiger (Mac OS 10.4) includes Python 2.3.5 and IDLE (Integrated DeveLopment Environment). Leopard (Mac OS 10.5) includes Python 2.5.1. Snow Leopard (Mac OS 10.6) includes Python 2.6. The Python files can be found in the /System/Library/Frameworks/Python.framework/Versions folder. To install or upgrade to Python 3.2, download the pre-built Mac OS X installer from www.python.org. The file name will be python-3.2.macosx.dmg. To initiate the installation procedure, double-click the file. It will create a disk image named Universal MacPython 3.2. The disk image will contain a license, a ReadMe file, and the MacPython.mpkg file. You need to double-click the MacPython.mpkg file to install Python on your computer. The installer will take you through a few steps that include agreeing to the license terms and conditions for using Python, specifying a destination folder, and selecting installation type (e.g., whether it is an upgrade or a fresh installation). To test whether the upgraded version of Python is successfully installed on your Mac platform, open the Terminal window and type python followed by the Enter key. The Python command invokes Python and displays its prompt (>>>) along with the version information. If the prompt displays the version as 3.2, it confirms that the upgraded version of Python is successfully installed on your computer, and you can execute Python commands at the prompt. To close the prompt and exit Python, press Ctrl+D. Installing Python on UNIX To install Python on the UNIX platform, the first step, as usual, is to download and extract its installer program from www.python.org. The next step is to give the following command to configure options for your UNIX system:./configure Thereafter, the following commands are needed to begin the installation procedure: make make install The preceding commands will install Python files in the /usr/local/bin folder and install its libraries in /usr/local/lib/python32 folder. Since the make installcommand can overwrite your previous Python installation, it is better to use the make altinstallcommand: make altinstall prefix=~ exec-prefix=~ prefix=~installs all platform-independent files in the ~/lib folder, and exec-prefix=~installs all binary and other platform-specific files in the ~/bin folder. The make altinstallcommand creates ${prefix}/bin/python, which refers to the new python installation. Interacting with Python There are two ways to work with Python interactively: Using Command Line Mode Using IDLE IDE Command Line Mode In command line mode, you type Python instructions one line at a time. You can also import code from other files or modules. To open Python’s command line mode in Windows, select Start > All Programs > Python 3.2 to open the Python 3.2 group. The group shows several options, such as IDLE (Python GUI), Module Docs, Python (command line), Python Manuals, and Uninstall Python. Select the Python (command line) option from the group. Alternatively, you can open a command prompt window and type python followed by pressing the Enter key. If you get an error message saying that the Python program couldn’t be found, it means that your operating system could not find the path for the Python installation. To define the correct path for the Python installation, right-click on the My Computer icon and select Properties from the shortcut menu that appears. Select the Advanced tab from the dialog that appears, and click the Environment Variables button at the bottom. A list of environment variables will be displayed. Double click the Pathvariable to edit it. In the Edit box, add the location of your Python installation (i.e., ;C:\python32) at the end of the line, and select OK. Also, click the OK button in all of the windows that are open until you get back to your desktop. Open another command prompt window (because the old window will still have the old path settings) and invoke Python by typing python followed by Enter. On Mac OS X, open the Terminal window and type python3 followed by the Enter key. On UNIX, open a new shell window and type python3.2 at a command prompt. After typing the appropriate command in the respective platform, Python’s command line mode is invoked, displaying a window (refer to Figure 1.3). While working in command line mode, a history of the commands given is maintained. You can use the up and down arrows, as well as the Home, End, Page Up, and Page Down keys, to scroll through the commands used previously. Since whatever you type in command line mode is not saved, it is better to save code in a file and then execute it. The following section shows you how to use this method, too. IDLE (Integrated DeveLopment Environment) IDLE is a simple IDE that comes with the standard Python distribution. IDLE combines an interactive interpreter with code editing, debugging tools, and several specialized browsers/viewers built into it. It provides automatic indentation and colors to the code based on Python syntax types, making your program more readable. Also, you can navigate to the previously given commands that are in the buffer using the mouse, arrow keys, or Page Up and Page Down keys. You can also toggle up and down through the previously given commands using the Alt+P and Alt+N key commands. You can also complete Python keywords or user-defined values by pressing Alt+/. To start IDLE on Windows, select Start > All Programs > Python 3.2 > IDLE (Python GUI). On Mac OS X, navigate to the Python 3.2 subfolder in the Applications folder, and run IDLE from there. On UNIX, type idle3.2 at a command prompt. The Python Shell window opens upon invoking IDLE, as shown in Figure 1.4. Figure 1.4. Python Shell window. Besides executing individual Python commands in the Python Shell window, you can also write and edit Python programs in any editor and execute them through IDLE. You can use any text editor, like Notepad on Windows or ed on Linux, for writing and editing Python programs. Besides using external editors, you can also use IDLE’s built-in editor for the same purpose. To open IDLE’s editor, select File > New Window. A blank window appears where you can type a Python program. To save the program, select File > Save As. The program will be saved with extension.py. The.py extension shows that it is a Python program. To execute the program, select Run > Run Module or press the F5 key. While running a program, IDLE will display the line(s) where errors, if any, occur. You can also open and edit programs written in other editors by selecting File > Open. Alternatively, you can right-click on the program name in an Explorer window and select Edit with IDLE to open it in IDLE’s editor. Writing Your First Python Program As mentioned earlier, you can write your first Python program either through IDLE’s built-in editor or through any editor. I will be using IDLE’s editor throughout the book for writing programs. You can launch IDLE by selecting Start > All Programs > Python 3.2 > IDLE (Python GUI). Then select the File > New Window option to open IDLE’s built-in editor and write the following small program: arearect.py # The program calculates area of rectangle l=8 b=5 a=l*b print ("Area of rectangle is ", a) Save it to your computer in any desired folder by any name, for example, arearect.py. Note Remember to add the.py extension when saving the file, as IDLE does not add the extension automatically. The program consists of two variables, l and b, initialized to values 8 and 5, respectively. The l and b variables here represent the length and breadth of a rectangle. The l and b are multiplied, and the result is stored in a third variable, a, that is then displayed as the area of a rectangle. To run the program, select Run > Run Module from the menu or just press F5. You will get the following output: Area of rectangle is 40 Congratulations! You have successfully written and executed your first Python program. Running Python Programs from the Command Prompt You can run Python programs from the command prompt, too. Open the command prompt and type python arearect.py followed by the Enter key to open Python and tell it to run the script file, arearect.py. You will get the output of the program as previously shown. You might have noticed that variables l, b, and a are of integer types. What are other data types in Python? Go to the next section for a brief overview of different data types in Python. Data Types in Python Python has a rich set of fundamental data types. The operations that are applicable on an object depend on its data type (i.e., an object’s data type determines which operations are applicable on it). The list of data types are as follows: Integers: Integers are 32 bits long, and their range is from –232 to 232 – 1 (i.e., from –2,147,483,648 to 2,147,483,647). Long Integers: It has unlimited precision, subject to the memory limitations of the computer. Floating Point Numbers: Floating-point numbers are also known as double-precision numbers and use 64 bits. Boolean: It can hold only one of two possible values: True or False. Complex Number: A complex number has a real and an imaginary component, both represented by float types in Python. An imaginary number is a multiple of the square root of minus one, and is denoted by j. For instance, 2+3j is a complex number, where 3 is the imaginary component and is equal to 3 × √−1. Strings: Sequences of Unicode characters. Lists: Ordered sequences of values. Tuples: Ordered, immutable sequences of values. Sets: Unordered collections of values. Dictionaries: Unordered collections of key-value pairs. Note Unicode is a standard that uses 16-bit characters to represent characters on your computer. Unlike ASCII (American Standard Code for Information Interchange), which consists of 8 bits, Unicode uses 16 bits and represents characters by integer value denoted in base 16. A number does not include any punctuation and cannot begin with a leading zero (0). Leading zeros are used for base 2, base 8, and base 16 numbers. For example, a number with a leading 0b or 0B is binary, base 2, and uses digits 0 and 1. Similarly, a number with a leading 0o is octal, base 8, and uses the digits 0 to 7, and a number with a leading 0x or 0X is hexadecimal, base 16, and uses the digits 0 through 9, plus a, A, b, B, c, C, d, D, e, E, f, and F. Note An object that can be altered is known as a mutable object, and one that cannot be altered is an immutable object. Basic Elements in a Program Every program consists of certain basic elements, a collection of literals, variables, and keywords. The next few sections explain what these terms mean. Literals A literal is a number or string that appears directly in a program. The following are all literals in Python: 10 # Integer literal 10.50 # Floating-point literal 10.50j # Imaginary literal 'Hello' # String literal "World!" # String literal '''Hello World! It might rain today # Triple-quoted string literal Tomorrow is Sunday''' In Python, you can use both single and double quotes to represent strings. The strings that run over multiple lines are represented by triple quotes. Variables Variables are used for storing data in a program. To set a variable, you choose a name for your variable, and then use the equals sign followed by the data that it stores. Variables can be letters, numbers, or words. For example, l = 10 length = 10 length_rectangle = 10.0 k="Hello World!" You can see in the preceding examples the variable can be a single character or a word or words connected with underscores. Depending on the data stored in a variable, they are termed as integer, floating point, string, boolean, and list or tuple variables. Like in above examples, the variables land lengthare integer variables, length_rectangleis a floating-point variable, and kis a string variable. Following are examples of boolean, list, and tuple variables: a=True # Boolean variable b=[2,9,4] # List variable c=('apple', 'mango', 'banana') # tuple variable A tuple in python language refers to an ordered, immutable (non changeable) set of values of any data type. Keywords Python has 30 keywords, which are identifiers that Python reserves for special use. Keywords contain lowercase letters only. You cannot use keywords as regular identifiers. Following are the keywords of Python: and assert break class continue def del elif else except exec finally for from global if import in is lambda not Comments Comments are the lines that are for documentation purposes and are ignored by the interpreter. The comments inform the reader what the program is all about. A comment begins by a hash sign (#). All characters after the # and up to the physical line end are part of the comment. For example, # This program computes area of rectangle a=b+c # values of b and c are added and stored in a Continuation Lines A physical line is a line that you see in a program. A logical line is a single statement in Python terms. In Python, the end of a physical line marks the end of most statements, unlike in other languages, where usually a semicolon (;) is used to mark the end of statements. When a statement is too long to fit on a single line, you can join two adjacent physical lines into a logical line by ensuring that the first physical line has no comment and ends with a backslash (\). Besides this, Python also joins adjacent lines into one logical line if an open parenthesis ( ( ), bracket ( [ ), or brace ( { ) is not closed. The lines after the first one in a logical line are known as continuation lines. The indentation is not applied to continuation lines but only to the first physical line of each logical line. Printing For printing messages and results of computations, the print()function is used with the following syntax, print(["message"][variable list]) where messageis the text string enclosed either in single or double quotes. The variable list may be one or more variables containing the result of computation, as shown in these examples: print ("Hello World!") print (10) print (l) print ("Length is ",l) You can display a text message, constant values, and variable’s values through the printstatement, as shown in the preceding examples. After printing the desired message/value, the print()function also prints the new-line character, meaning the cursor moves onto the next line after displaying the required message/value. As a result, the message/value displayed through the next print()function appears on the next line. To suppress printing of the newline character, end the print line with end=‘ ’ followed by a comma (,) after the expression so that the print()function prints an extra space instead of a newline character. For example, the strings displayed via the next two print()functions will appear on the same line with a space in between: print("Hello World!", end=" ') print('It might rain today') You can also concatenate strings on output by using either a plus sign (+) or comma (,) betweens strings. For example, the following printfunction will display the two strings on the same line separated by a space: print('Hello World!', 'It might rain today') The following statement merges the two messages and displays them without any space in between: print('Hello World!'+'It might rain today') In order to get a space in between the strings, you have to concatenate a white space between the strings: print('Hello World!'+ ' '+ 'It might rain today') You can also use a comma for displaying values in the variables along with the strings: print ("Length is ", l, " and Breadth is ", b) Assuming the values of variables l and b are 8 and 5, respectively, the preceding statement will display the following output: Length is 8 and Breadth is 5 You can also use format codes (%) for substituting values in the variables at the desired place in the message: print ("Length is %d and Breadth is %d" %(l,b)) where %dis a format code that indicates an integer has to be substituted at its place. That is, the values in variables l and b will replace the respective format codes. Note If the data type of the values in the variables doesn’t match with the format codes, auto conversion takes place. The list of format codes is as shown in Table 1.1. You will be learning to apply format codes in the next chapter. Table 1.1. Frequently Used Format Codes Format Usage Code %s Displays in string format. %d Displays in decimal format %e Displays in exponential format. %f Displays in floating-point format. %o Displays in octal (base 8) format. %x Displays in hexadecimal format. %c Displays ASCII code. The following program demonstrates using the print()function for displaying different output: printex.py print (10) print('Hello World! \ It might rain today. \ Tomorrow is Sunday.') print('''Hello World! It might rain today. Tomorrow is Sunday.''') Output: 10 Hello World! It might rain today. Tomorrow is Sunday. Hello World! It might rain today. Tomorrow is Sunday. Summary In this chapter, you had a detailed introduction to Python and its features. You saw the procedure of installing Python on different platforms. You saw how to interact with Python through command line mode and through the IDLE IDE. You also learned to write your first Python program. I also introduced you to the Python basics, like its different data types, literals, variables, and keywords. Finally, you saw how to write comments, continuation lines, and print messages. In the next chapter, you will learn to apply different arithmetic operations in Python programs, use escape sequences in a program, and get data from a user and convert it into the desired data type. Also, you will learn to deal with octal and hexa values. You will also learn to perform bitwise operations, use complex numbers, and take decisions through an if...elsestatement. Finally, you will learn to use different loops, like while and forloops. Chapter 2. Getting Wet in Python This chapter covers the following: Performing Arithmetic Operations Using Escape Sequences Displaying Octal and Hexa Values Performing Bitwise Operations Using Complex Numbers Making Decisions: if...elseStatement Using Loops: whileand forLoops Breaking and Continuing a Loop Using Operators: Logical Operators and Membership Operators Performing Arithmetic Operations Arithmetic operators play a major role in programming, and it is essential to understand the use of different operators for efficient programming. Python provides several arithmetic operators for performing different operations on numerical data. The list of arithmetic operators used in Python is shown in Table 2.1. Table 2.1. Arithmetic Operators Operation Description x+y Addition x-y Subtraction x*y Multiplication x/y Division x // y Truncating division x ** y Exponentiation. Sets x to the power y; i.e., xy x%y Modulo operator –x Unary minus +x Unary plus Table 2.1 displays the usual arithmetic operators such as addition, subtraction, and multiplication. The multiplication and division operators have higher precedence than the addition and subtraction operators. The modulo operator returns the remainder of the division operation. What is the difference between the division operator and the truncating division operator? Let’s see. Division Operator The truncating division operator (//), also known as floor division, truncates the result to an integer (ignoring the remainder) and works with both integers and floating-point numbers. The true division operator (/) also truncates the result to an integer if the operands are integers. It also means that the true division operator returns a floating-point result if either operand is a floating-point number. Note When both operands are integers, the /operator behaves like //. The following program uses the true division operator for calculating the area of a triangle. areatriangle.py b=17 h=13 a=1.0/2.0*b*h print ("Area of triangle is", a) print ("Base= %d, Height is %d, Area of triangle is %f" %(b,h,a)) Output: Area of triangle is 110.5 Base= 17, Height is 13, Area of triangle is 110.500000 In this program, you are using the true division operator, /, which returns an integer if both the operands are integers. To get the correct result, 1/2 is converted into a float, 1.0/2.0, so that the result from the true division operator comes out to be a float. One thing to observe in the program’s output is that the %fdirective returns the float value up to six decimal places. Can it be rounded to 2 or 3 decimal places? Let’s see. The following program calculates the average of three values and displays the result rounded up to the desired number of decimal places: average1.py p=q=r=10 a=1.0/3.0*(p+q+r) print ("Average of three variables is", a) print ("Average of three variables is %.2f" %a) print ("Average of three variables is %d" %a) Output: Average of three variables is 10.0 Average of three variables is 10.00 Average of three variables is 10 In this program, you see that the floating-point result is rounded to 2 places by using %.2f. Also, you see that the floating-point value is truncated to a decimal value when %dformat code is applied to it. While using the true division operator, /, you need to ensure that either operand is a floating-point number to avoid getting an incorrect truncating integer. While using the true division operator, it’s better to begin the source file with this statement: from _ _future_ _ import division This statement ensures that the true division operator works without truncation on operands of any type. Basically, the from __future__ statement ensures that the script uses the new-style floating-point division operator. average2.py from __future__ import division p=q=r=10 a=(p+q+r)/3 print ("Average of three variables is", a) Output: Average of three variables is 10.0 Exponentiation To apply exponentiation, use double asterisks: **. For example, a**b means ab. You get an exception if ais less than zero and bis a floating- point value with a nonzero fractional part. You can also use the built-in pow()function for applying exponentiation. For example, pow(a, b)is the same as a**b. You will learn about exception handling in Chapter 6, “File Handling.” Let’s write a program to calculate the volume of a sphere. The formula is 4/3*pi*r3, where the value of radius ris known to be 3. volsphere.py from __future__ import division r=3 pi=22/7 v=4/3*pi*pow(r,3) print ("Volume of sphere is %.2f" %v) Output: Volume of sphere is 113.14 In this program, you can see that r3is computed through pow(). The expression pow(r,3)can also be replaced by r**3, as both do the same task. Is there any way to get the value of pi instead of computing it manually as 22/7? Yes, the math module, besides other important functions, also provides the value of pi to use directly in arithmetic expressions. You will learn about the math module in detail in Chapter 4, “Functions and Modules.” For now, let’s see how the value of pi can be used through the math module. Rewrite the program above to use the pi value provided by the math module. from __future__ import division from math import pi r=3 v=4/3*pi*pow(r,3) print ("Volume of sphere is %.2f" %v) The statement from math import piimports the value of pi from the math module to be used directly in the arithmetic expression. The value represented will be 3.1415926535897931. Multiple Assignment Statement The basic assignment statement can do more than assign the result of a single expression to a single variable. It can also assign multiple variables at one time. The rule is that the left and right sides must have the same number of elements, and the values will be assigned on a one-to-one basis. Examples p,q,r=10,20,30 sum, avg=p+q+r,(p+q+r)/3 The values on the right side of the assignment operator will be assigned on a one-to-one basis; for example, 10 will be assigned to the pvariable, 20 will be assigned to the qvariable, and so on. Similarly, in the second example, the result of the expression p+q+rwill be assigned to the sum variable, and the result of the expression (p+q+r)/3will be assigned to the variable avg. Using Escape Sequences Escape sequences are special characters that represent nonprinting characters such as tabs, newlines, and such. These special characters begin with a backslash. When Python sees a backslash, it interprets the next character with a special meaning. Table 2.2 shows a list of escape characters that can be used in Python scripts. Table 2.2. Escape or Non-Printable Characters Escape Character Description \a Bell (beep) \b Backspace \f Form feed \n Newline \r Carriage return \t Tab \v Vertical tab \\ Literal backslash \' Single quote \" Double quote Note In a double-quoted string, an escape character is interpreted; in a single-quoted string, an escape character is preserved. The following program demonstrates using escape sequences in a program: escapeseq.py print('Hello World\nIt\'s hot today') print('Festival Discount\b\b\b\b\b\b\b\b\b Offer') print("Isn't it?") print('Isn\'t it?') print("He said: \"I am going \"") print('\\Text enclosed in back slashes\\') print ('Bell sound \a') print('Name\tEmail Address\tContact Number') Output is shown in Figure 2.1. Figure 2.1. Output of escape sequence program. In the output you see that the text Hello Worldand It's hot today appear on two different lines because of the newline character between. The text Festival Discountappears as Festival Offeruntbecause after displaying the term Festival Discountwhen the cursor was standing after the character tof the word Discount, the cursor is shifted back nine characters where the Dis. At the location of character D, the text Offeris displayed, overwriting the first five characters of the word Discountand leaving untto appear after Offer. Displaying of the text Isn't ittwice reveals that the single quote can be displayed either when enclosed within double quotes or when preceded by \when enclosed within single quotes. Similarly, you use \to display the text I am goingenclosed within double quotes. Similarly, Textenclosed in back slashes appears with \on either side because of \\.The \aescape character makes a bell sound, and \t makes Name, Email Address, and Contact Numberappear at the tab stops. Note The IDLE (Python GUI) doesn’t recognize a few escape sequence characters, including \a and \b. Therefore, when you run the preceding program in IDLE instead of the command prompt, no bell sound will appear and you will get the following output: Hello World It's hot today Festival Discount Offer Isn' t it? Isn' t it? He said: "I am going " \Text enclosed in back slashes\ Bell sound Name Email Address Contact Number You can see that \b and \a appear as some unusual symbols. Finding a Data Type To find the data type of the specified object, you use the type()function, which returns the data type of the object passed to it. Syntax: type(x) where xis the object whose data type will be returned. The function accepts all types of parameters, such as integers, strings, lists, dictionaries, tuples, functions, classes, and modules. Examples: type(10) type('Hello') The following program displays data types integers, floats, strings, Booleans, and so on. typeexample.py a=10 b=15.5 c="Hello" d=[2,9,4] e=('apple', 'mango', 'banana') f=True print (type(a)) print (type(b)) print (type(c)) print (type(d)) print (type(e)) print (type(f)) Output: This program initializes variables a, b, c, d, e, and fto data type integer, floatingpoint, string, list, tuple, and Boolean, respectively. Thereafter, the data type of these variables is determined and displayed using the type() function. Displaying Octal and Hexa Values To assign an octal value to a variable, the number should be preceded by 0o. Similarly, if a number is preceded by 0x, it is considered a hexa value. The following program demonstrates conversion of a decimal value into octal and hexa and vice versa. octhex.py a=0o25 b=0x1af print ('Value of a in decimal is', a) c=19 print ('19 in octal is %o and in hex is %x' %(c,c)) d=oct(c) e=hex(c) print ('19 in octal is', d, 'and in hexa is', e) Output: Value of a in decimal is 21 19 in octal is 23 and in hex is 13 19 in octal is 0o23 and in hexa is 0x13 In this program, variables aand bare assigned octal and hexa values, respectively. The octalvalue is converted and displayed as a decimal. Similarly, the decimal value 19is converted to octal and hexa and displayed using the directives %oand %x, respectively. Also, by using the oct()and hex()functions, the number 19 is converted to octal and hexa, respectively. Getting Data To get input from the user, you use the inputmethod. It prompts the user to enter data and reads one line from the standard input and returns it as a string that can be consequently assigned to a variable. Syntax: variable=input ('Message') The data entered by the user is assigned to the variable in string format. If you want the data in another format (integer, float, etc.), it has to be converted explicitly. Before you see explicit conversion, let’s talk about auto conversion (coercion) in Python. Coercion In Python, if you do some arithmetic operations on the operands of the same data type, no auto conversion or coercion takes place. When operands of different data types are computed, coercion takes place. Python converts the operand with the “smaller” type to the “larger” type. For example, if either of the operands is a floating number, then the other operand is also converted to float point. If either argument is a complex number, the other is also converted to complex. Similarly, if either is of type long, the other is converted to long. An integer operand is converted to float by adding.0to it. A non-complex type is converted to a complex number by adding a zero imaginary component, 0j, to it. For explicit conversion, the functions that you will be frequently using are int(), float(), and str(). The function that is needed for the next program is an int()function. Converting Explicitly into integer Type To convert the specified numerical or string into an integer data type, you use the int()function. int() The data to be converted into the integer is passed as an argument to the int()function. Syntax: int([x[, base]]) The specified xobject is converted into integer format. The baseparameter can be any value in the range 2 to 26 and refers to the base for the conversion. The default value of the baseis 10. If the argument contains some fractional part, it is dropped. For example, int(7.5)will return 7. The following program computes and displays the area of a rectangle. The area of a rectangle is the multiplication of length and width, and their values will be supplied by the user. The values supplied by the user will be through the input()function, which returns the supplied values in string format and hence will be converted into the integer data type using the int()function. arearectinput.py l=input("Enter length: ") b=input("Enter width: ") a=int(l)*int(b) print ("Area of rectangle is",a) Output: Enter length: 9 Enter width: 5 Area of rectangle is 45 In this program, you can see that the user is asked to enter values for length and width through the input()method. The values entered by the user will be assigned to the variables land b, respectively. As said earlier, the input method returns data in string format, hence the values in variables land bare first converted from string to integer format through the int()function before they are used in any arithmetic operation. The following program computes and returns the area of a circle. The formula is pi*r2. The rin the formula refers to radius, and its value will be supplied by the user. areacircleinput.py from math import pi r=int(input("Enter radius: ")) a=pi*r*r print ("Area of the circle is", a) print ("Area of the circle is %.2f" %a) Output: Enter radius: 5 Area of the circle is 78.53981633974483 Area of the circle is 78.54 Bitwise Operations Every numerical that is entered in a computer is internally represented in the form of binary digits. For instance, the decimal value 25 is internally represented in the form of binary digits as 11001. The bitwise operators operate on these binary digits to give desired results. Note The shifting and bitwise operators can only be applied to integers and long integers. Considering xand yas two operands, following are the shifting and bitwise operators: x > y(binary shift right): Returns xwith the bits shifted to the right by yplaces. This operation is the same as dividing xby 2**y. x & y(bitwise AND): Corresponding bits of xand yare compared. It returns 1if the corresponding bit of xAND yis 1; otherwise 0is returned. x | y(bitwise AND): Corresponding bits of xand yare compared. It returns 0if the corresponding bit of xand of yis 0; otherwise it returns 1. That is, if either xor yis 1, the operator returns 1. x ^ y(bitwise exclusive AND): Corresponding bits of xand yare compared. It returns 1if either xor yis 1;otherwise it returns 0. That is, the operator returns 0if the corresponding bits of xand yare the same. ~ x(bitwise inversion): It returns the complement of x; i.e., binary digit 1is converted to 0, and 0is converted to 1. The following program demonstrates the application of AND, OR, EXCLUSIVE AND, and left and right shift operators. bitwise.py a=10 b=7 c=a&b d=a ^ b e= a | b print ('The result of 10 and 7 operation is', c) print ('The result of 10 exclusive or 7 operation is' , d) print ('The result of 10 or 7 operation is', e) g=a1 print ('Right shifting - Dividing 10 by 2 becomes:',h) Output: The result of 10 and 7 operation is 2 The result of 10 exclusive or 7 operation is 13 The result of 10 or 7 operation is 15 Left shifting - Multiplying 10 by 4 becomes: 40 Right shifting - Dividing 10 by 2 becomes: 5 The integers 10 and 7 and the result of application of the &(AND) operator on them are shown in Figure 2.2(a). The figure shows that the AND operator returns 1 if both the integers are 1; otherwise it returns 0. Figure 2.2(b) shows the result of applying the EXCLUSIVE OR operator on the two integers, 10 and 7. You can see that the EXCLUSIVE OR operator returns 1 if either of the two integers is 1. Figure 2.2(c) shows the result of applying the OR operator; it returns 1 if either or both of the integers are 1. Figure 2.2. (a) Result of the AND operator. (b) Result of the EXCLUSIVE OR operator. (c) Result of the OR operator. Figure 2.3(a) shows the result of left shifting the value 10 by 2. You can see that two 0s are added to the right in the number. On every left shift, the value of the number is multiplied by 2. That is, on left shifting the number by two, the number is multiplied by 4, giving the result as 40. Figure 2.3(b) shows the number 10 shifted one bit to the right. The right- most bit of the number is dropped, and a 0 is added to its left, dividing the number by 2 and giving the result as 5. Figure 2.3. (a) Result of left-shifting the number by 2. (b) Result of right-shifting the number by 1. Complex Numbers A complex number is the combination of a real and an imaginary component, where both are represented by floating-point data type. The imaginary component of the complex number is a multiple of the square root of minus one and is denoted by j. Example: 3+1.2j In this example, 3is a real component, and 1.2is the imaginary component and is equal to 1.2 × √−1. The real and imaginary components of a complex object can be accessed by using its realand imagattributes. The following program shows the addition of two complex numbers: complex.py a = 3.0 + 1.2j b= -2.0 - 9.0j print ('The two complex numbers are', a, 'and', b) c=a+b print ('The addition of two complex numbers is:', c) print ('The addition of two real numbers is:', a.real+b.real) print ('The addition of two imaginary number is:', a.imag+b.imag) Output: The two complex numbers are (3+1.2j) and (-2-9j) The addition of two complex numbers is: (1-7.8j) The addition of two real numbers is: 1.0 The addition of two imaginary number is: -7.8 This program defines two complex numbers, aand b. The real and imaginary components of the complex number aare 3.0and 1.2, respectively. Similarly, the real and imaginary components of the complex number bare -2.0and -9.0, respectively. While adding the complex numbers, the respective real and imaginary components of the two complex numbers are added, as shown in Figure 2.4. The program also accesses the real and imaginary components of the two complex numbers by adding their realand imagattributes. Figure 2.4. Addition of two complex numbers. Note The complex numbers are displayed enclosed in parentheses (). When writing programs, you come across a situation where you want to execute a block statement out of the two blocks. That is, you need to control flow of the program and execute a block statement out of available choices, depending on the prevalent conditions. Let’s see how to make decisions in Python. Making Decisions The statement that helps in making decisions and controlling flow of the program is the if...elsestatement. if...else statement The if...elsestatement decides which block of statements to execute on the basis of the logical expression included. A block of statements is attached with ifas well as with else, and when the logical expression is evaluated, either the ifor the elseblock statement is executed. Syntax: if (logical expression): statement(s) else: statement(s) If the logical expression evaluates to true, then the ifstatement is executed; otherwise, the elsestatement is executed. Note The elsestatement is optional. Let’s write a program that asks the user to enter a student’s grades. If the grades are greater than or equal to 60, the program should display a message, First Division. If not, it should display the message Second Division. ifelse1.py m=int(input("Enter grades: ")) if(m >=60): print ("First Division") else: print ("Second Division") Output: Enter grades: 75 First Division Enter grades: 50 Second Division You can see in this program that the user enters grades through an input()method. Since the value entered by input()is in string format, it is converted to an integer and assigned to the variable m. Using an if...elsestatement, you check the value in variable m. If the value in variable mis greater than or equal to 60, the ifblock will be executed, displaying the message First Division. If the value entered is less than 60, the elseblock will be executed, displaying the text Second Division. The output of the program confirms this. In this program, greater than or equal to (>=) compares the value of the variable mwith 60. Table 2.3 lists the comparison operators. Table 2.3. Comparison Operators Operator Meaning < Less than > Greater than = Greater than or equal to == Equal to != Not equal to In the next program, again you ask the user to enter a student’s grades. If the grades entered are greater than or equal to 60, a message First Divisionwill be displayed. If the grades entered are greater than or equal to 45 but less than 60, the message Second Divisionwill be displayed. If the grades entered are less than 45, Third Divisionwill be displayed. For such programs, you nest an if...elseblock within the elseblock of the outer if...elsestatement. Let’s see how this nesting is done in the following program: ifelse2.py m=int(input("Enter grades: ")) if(m >=60): print ("First Division") else: if(m >=45): print ("Second Division") else: print ("Third Division") Output: Enter grades: 75 First Division Enter grades: 50 Second Division Enter grades: 40 Third Division You can see in this program that an if...elsestatement is written within an elsestatement of the outer if...elsestatement. The if...else statement within the elsestatement will be executed if the logical expression included in the outer ifstatement evaluates to False. That is, if the user enters a value less than 60, the inner if...elsestatement will be executed to check if the entered value is greater than 45, and the appropriate message will be displayed. if-elif-else statement If you have multiple logical expressions to evaluate, and on the basis of those logical expressions you want to execute a specific set of code block, you need to use an if-elif-elsestatement. Syntax: if (logical expression): statement(s) elif (logical expression 1): statement(s) [elif (logical expression n): statement(s)] else: statement(s) You can see that the elsestatement and the ifstatement nested in it are merged to form an elifstatement. An elifstatement is helpful in avoiding excessive indentation. The program ifelse2.pythat you wrote earlier can be rewritten with an if-elif-elsestatement as shown here: ifelif.py m=int(input("Enter grades: ")) if(m >=60): print ("First Division") elif (m >=45): print ("Second Division") else: print ("Third Division") What if you need to combine more than one logical expression? You use logical operators for connecting logical expressions. Let’s have a quick look at logical operators. Logical Operators In writing logical expressions, you sometimes need to combine two or more logical expressions. The logical expressions are usually combined with the logical operators AND, or, and not. The list of logical operators with a brief description is shown in Table 2.4. Table 2.4. Logical Operators Logical Operator Description AND The logical expression connected with the AND logical operator returns trueif all the logical expressions evaluate to true. or The logical expression connected with the orlogical operator returns trueif any of the logical expressions evaluates to true. not The logical expression preceded by the notlogical operator is negated. That is, the logical expression that evaluates to truebecomes falsewhen preceded by the logical notoperator and vice versa. Consider the logical expressions xand yconnected with the logical AND operator as shown below: x and y On combining the logical expressions by the logical AND operator, first the logical expression xis evaluated, and if it returns false, the result of the combination will be x; otherwise, the result will be y. Similarly, on combining the logical expressions xand yby the logical or operator, first the logical expression xis evaluated, and if it results in true, the result of the combination will be x; otherwise, the result will be y. The program ifelse2.pythat you wrote earlier can be rewritten by combining the logical expressions with logical operators: ifelse3.py m=int(input("Enter grades: ")) if(m >=60): print ("First Division") if(m >=45 and m Edit Buddies or the Edit Buddies icon from the toolbar to switch to Buddy Editing mode. To go back to Widget Editing mode from Buddy Editing mode, you can choose any of the three options: press F3, select the Edit > Edit Widgets from the menu, or click the Edit Widgets icon on the toolbar. In Buddy Editing mode, select a Label widget and drag it to the Line Edit widget that you want to set as its buddy and release the mouse button. The Label and Line Edit widgets will become buddies. On defining a buddy for the Label widget, the &(ampersand) in its text becomes invisible. After setting the three Line Edit widgets as buddies of the Label widgets, the dialog will appear as shown in Figure 7.20(a). To switch from Buddy Editing to Widget Editing mode, either press F3 or select the Edit Widgets icon from the toolbar. The dialog in Widget Editing mode will appear as shown in Figure 7.20(b). Figure 7.20. (a) Widgets on the form with the buddies set. (b) The dialog in Widget Editing mode. [View full size image] Before running the application, let’s see how to set the tab order of the widgets. Setting Tab Order Tab order means the order in which the widgets will get focus when the Tab and Shift+Tab keys are pressed. The default tab order is based on the order in which widgets are placed on the form. To change this order, you need to switch to Tab Order Editing mode by either selecting the Edit, Edit Tab Order option or choosing the Edit Tab Order icon from the toolbar. In Tab Order Editing mode, each input widget in the form is shown with a number indicating its position in the tab order (see Figure 7.21(a)). If the user gives the first input widget the input focus and then presses the Tab key, the focus will move to the second input widget, and so on. You can change the tab order by clicking on each number in the correct order. When you select a number, it will change to red, indicating the currently edited position in the tab order chain. Clicking on the next number will make it the second in the tab order, and so on. In case of a mistake, you can restart numbering by choosing Restart from the form’s context menu. To edit the tab order in the middle of the form, select a number with the Ctrl key pressed from where you want to change the tab order or choose Start from Here from the context menu. Let’s set the tab order of the widgets on our dialog as shown in Figure 7.21(b). Figure 7.21. (a) Initial tab order of the widgets on the form. (b) Modified tab order of the widgets on the form. [View full size image] Note There is one more way to specify the tab order. Right-click anywhere on the form and select Tab Order List from the context menu that appears. Save the application with the name buddytab.ui. Upon conversion to Python code, the XML file buddytab.uiwill appear as shown here: buddytab.py #Form implementation generated from reading ui file 'buddytab.ui' from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(490, 182) self.label = QtGui.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(10, 20, 91, 16)) self.label.setObjectName(_fromUtf8("label")) self.quantity = QtGui.QLineEdit(Dialog) self.quantity.setGeometry(QtCore.QRect(120, 10, 113, 20)) self.quantity.setObjectName(_fromUtf8("quantity" )) self.label_2 = QtGui.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(280, 10, 71, 16)) self.label_2.setObjectName(_fromUtf8("label_2")) self.rate = QtGui.QLineEdit(Dialog) self.rate.setGeometry(QtCore.QRect(370, 10, 113, 20)) self.rate.setObjectName(_fromUtf8("rate")) self.label_3 = QtGui.QLabel(Dialog) self.label_3.setGeometry(QtCore.QRect(10, 50, 101, 16)) self.label_3.setObjectName(_fromUtf8("label_3")) self.discount = QtGui.QLineEdit(Dialog) self.discount.setGeometry(QtCore.QRect(130, 50, 113, 20)) self.discount.setObjectName(_fromUtf8("discount" )) self.pushButton = QtGui.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(120, 100, 111, 23)) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.result = QtGui.QLabel(Dialog) self.result.setGeometry(QtCore.QRect(50, 140, 351, 16)) self.result.setText(_fromUtf8("")) self.result.setObjectName(_fromUtf8("result")) self.label.setBuddy(self.quantity) self.label_2.setBuddy(self.rate) self.label_3.setBuddy(self.discount) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) Dialog.setTabOrder(self.quantity, self.discount) Dialog.setTabOrder(self.discount, self.rate) Dialog.setTabOrder(self.rate, self.pushButton) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog" , None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("Dialog", "&Number of items" , None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("Dialog", "& per item" , None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("Dialog", " &Discount Per- centage", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("Dialog", " Calculate Amount", None, QtGui.QApplication.UnicodeUTF8)) Let’s create a Python script to import the Python code to invoke the user interface design and to compute the amount when number of items, price per item, and discount percentageare supplied by the user. Name the Python script callbuddytab.pyw; its code is shown below: callbuddytab.pyw from __future__ import division import sys from buddytab import * class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self. calculate) def calculate(self): if len(self.ui.quantity.text())!=0: q=int(self.ui.quantity.text()) else: q=0 if len(self.ui.rate.text())!=0: r=int(self.ui.rate.text()) else: r=0 if len(self.ui.discount.text())!=0: d=int(self.ui.discount.text()) else: d=0 totamt=q*r disc=totamt*d/100 netamt=totamt-disc self.ui.result.setText("Total Amount: " +str(totamt)+", Discount: "+str(disc)+" , Net Amount: "+str(netamt)) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_()) In this code, you can see that the Push Button’s clicked()signal is connected to the calculate()function. After supplying the values for number of items, price per item, and discount percentagein the Line Edit widgets, when the user selects the Calculate Amount Push Button, the calculate()function will be invoked. In the calculate()function, you validate the Line Edit widgets to check if any Line Edit widget is left blank. The value of Line Edit that is left blank is assumed to be 0. Thereafter, you compute the net amount, which is total amount minus discount, where total amountis the product of number of itemsand price per item. The computed net amountis then converted to string data type to be displayed via a Label widget. On running the application, you will find the underscored characters N, P, and Din the Label’s texts, Number of items, Price per item, and Discount Percentage, as shown in Figure 7.22. The underscored characters mean that you can use Alt+N, Alt+P, and Alt+D shortcut keys for setting focus to the respective Line Edit widgets for entering values for number of items, price per item, and discount percentage. If you don’t see the underscored characters in the Labels, just press Alt, and underscores will appear. Figure 7.22. The characters acting as shortcut key appear underlined. Summary In this chapter you had a brief introduction to the Qt toolkit and PyQt. You learned the procedure of installing PyQt. You learned about different Qt Designer components such as the toolbar, the Object Inspector, the Property Editor, and the Widget Box. You also learned to create a GUI application through coding. You learned about the fundamental Label, Line Edit, and Push Button widgets and developed applications using them. You also had a good introduction to signal/slot connections in Qt Designer and learned to connect signals to the predefined slots and to custom slots. In the next chapter you will learn about basic widgets such as Radio Buttons, Checkboxes, Spin Boxes, Scroll Bars, Sliders, and Lists. To better understand these basic widgets, you will develop individual application using each of them. Chapter 8. Basic Widgets In this chapter, we will focus on a few basic widgets. These enable the user to choose one or more options and select integer or float values from a specified range. Not only will you learn how to display options to the user but also how to add, delete, or modify existing options. We will cover the following in this chapter: Using radio buttons Using checkboxes Entering integer and float values using a spin box Scroll bars and sliders Working with List widget Let’s begin the chapter with radio buttons. Using Radio Buttons To display selectable options that are mutually exclusive (selecting one option automatically deselects other options in the group), you use Radio Button widgets, which are instances of the QRadioButtonclass. The class displays a radio button along with a text label. The radio button can be either in a selected (checked) or unselected (unchecked) state. If you want two or more sets of radio buttons, where each set allows exclusive selection of a radio button, put them into different button groups (instances of QButtonGroup). Button groups are explained in detail in Chapter 11, “Multiple Documents and Layouts.” Methods provided by QRadioButton are shown in Table 8.1. Table 8.1. Methods Provided by the QRadioButton Class Method Use isChecked() Returns true if the button is in selected state. setIcon() Used to display an icon with the radio button. setText() Used to set the text of the radio button. To specify a shortcut key for the radio button, precede the preferred character in the text with an ampersand (&). setChecked() Pass the Boolean value true to this method to make the radio button the default. Signals emitted by QRadioButtonare shown in Table 8.2. Table 8.2. Signals Emitted by the QRadioButton Class Signal Description toggled() Emitted whenever button changes its state from checked to unchecked or vice versa. clicked() Emitted when a button is activated (i.e., pressed and released) or when its shortcut key is pressed. stateChanged()Emitted when a radio button changes its state from checked to unchecked or vice versa. To understand the concept of radio buttons, let’s create an application that asks the user to enter two numbers and displays four options—Add, Subtract, Multiply, and Divide—in the form of radio buttons. On selecting an option through Radio Button, the respective operation will be performed on the two numbers and the result displayed. Let’s create a new application based on the Dialog without Buttons template. Drag and drop three Label widgets, two LineEdit widgets, four radio buttons, and a push button onto the form. Set the textproperty of the first two Label widgets to Enter First Numberand Enter Second Number. Leave the textproperty of the third Label at the default, TextLabel, as you will be setting its text through the program to display the result of computation. Also, set the textproperty of the four radio buttons to Add, Subtract, Multiply, and Divide. Set the objectNameproperty of the three Label widgets to labelFirstNumber, labelSecondNumber, and labelResult. Set the objectNameproperty of the two LineEdit widgets to lineFirstNumberand lineSecondNumber. The default objectNames of the four Radio Buttons are radioButton, radioButton_2, radioButton_3, and radioButton_4. Change these to radioAdd, radioSubtract, radioMultiply, and radioDivide. Set the objectNameof the push button to ComputeButton. The form will appear as shown in Figure 8.1. Figure 8.1. Form displaying four options to the user via radio buttons. Save the application with the name radiobtn.ui. On converting the.ui(XML) file into Python code through the pyuic4command utility, you will get the code shown here: radiobtn.py # Form implementation generated from reading ui file 'radiobtn.ui' from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(430, 448) self.labelResult = QtGui.QLabel(Dialog) self.labelResult.setGeometry(QtCore.QRect(60, 240, 171, 21)) self.labelResult.setObjectName(_fromUtf8("labelResult")) self.lineSecondNumber = QtGui.QLineEdit(Dialog) self.lineSecondNumber.setGeometry(QtCore.QRect(170, 60, 113, 20)) self.lineSecondNumber.setObjectName(_fromUtf8("lineSecondNumber")) self.labelSecondNumber = QtGui.QLabel(Dialog) self.labelSecondNumber.setGeometry(QtCore.QRect(50, 60, 111, 16)) self.labelSecondNumber.setObjectName(_fromUtf8("labelSecondNumber")) self.labelFirstNumber = QtGui.QLabel(Dialog) self.labelFirstNumber.setGeometry(QtCore.QRect(60, 30, 101, 16)) self.labelFirstNumber.setObjectName(_fromUtf8("labelFirstNumber")) self.ComputeButton = QtGui.QPushButton(Dialog) self.ComputeButton.setGeometry(QtCore.QRect(180, 280, 75, 23)) self.ComputeButton.setObjectName(_fromUtf8("ComputeButton")) self.radioAdd = QtGui.QRadioButton(Dialog) self.radioAdd.setGeometry(QtCore.QRect(60, 110, 82, 17)) self.radioAdd.setObjectName(_fromUtf8("radioAdd")) self.radioDivide = QtGui.QRadioButton(Dialog) self.radioDivide.setGeometry(QtCore.QRect(60, 200, 82, 17)) self.radioDivide.setObjectName(_fromUtf8("radioDivide")) self.radioSubtract = QtGui.QRadioButton(Dialog) self.radioSubtract.setGeometry(QtCore.QRect(60, 140, 82, 17)) self.radioSubtract.setObjectName(_fromUtf8("radioSubtract")) self.radioMultiply = QtGui.QRadioButton(Dialog) self.radioMultiply.setGeometry(QtCore.QRect(60, 170, 82, 17)) self.radioMultiply.setObjectName(_fromUtf8("radioMultiply")) self.lineFirstNumber = QtGui.QLineEdit(Dialog) self.lineFirstNumber.setGeometry(QtCore.QRect(170, 30, 113, 20)) self.lineFirstNumber.setObjectName(_fromUtf8("lineFirstNumber")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) self.labelResult.setText(QtGui.QApplication.translate("Dialog", "TextLabel", None, QtGui.QApplication.UnicodeUTF8)) self.labelSecondNumber.setText(QtGui.QApplication.translate("Dialog", "Enter Second Number", None, QtGui.QApplication.UnicodeUTF8)) self.labelFirstNumber.setText(QtGui.QApplication.translate("Dialog", "Enter First Number", None, QtGui.QApplication.UnicodeUTF8)) self.ComputeButton.setText(QtGui.QApplication.translate("Dialog", "Compute", None, QtGui.QApplication.UnicodeUTF8)) self.radioAdd.setText(QtGui.QApplication.translate("Dialog", "Add", None, QtGui.QApplication.UnicodeUTF8)) self.radioDivide.setText(QtGui.QApplication.translate("Dialog", "Divide", None, QtGui.QApplication.UnicodeUTF8)) self.radioSubtract.setText(QtGui.QApplication.translate("Dialog", "Subtract", None, QtGui.QApplication.UnicodeUTF8)) self.radioMultiply.setText(QtGui.QApplication.translate("Dialog", "Multiply", None, QtGui.QApplication.UnicodeUTF8)) Let’s import the code as a header file in the Python script that you are going to create next to invoke the user interface design. In the Python script, you will also write code to perform the arithmetic operation on the basis of the radio button selected by the user. Name the source file callradios.pyw; its code is shown here: callradios.pyw from __future__ import division import sys from radiobtn import * class MyForm(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.ComputeButton, QtCore.SIGNAL('clicked()'), self.calculate) self.ui.radioAdd.setChecked(1) def calculate(self): if len(self.ui.lineFirstNumber.text())!=0: a=int(self.ui.lineFirstNumber.text()) else: a=0 if len(self.ui.lineSecondNumber.text())!=0: b=int(self.ui.lineSecondNumber.text()) else: b=0 if self.ui.radioAdd.isChecked()==True: result=a+b if self.ui.radioSubtract.isChecked()==True: result=a-b if self.ui.radioMultiply.isChecked()==True: result=a*b if self.ui.radioDivide.isChecked()==True: result=a/b self.ui.labelResult.setText("Result: " +str(result)) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_()) The clicked()event of ComputeButtonis connected to the calculate()method, which will do the desired calculation. In the calculate()function, you set the default value of the LineEdits to 0, so if the user leaves either of the LineEdit widgets blank, its default value will be 0. The values entered in the two LineEdit widgets lineFirstNumberand lineSecondNumberare retrieved, converted into integers, and assigned to the variables aand b, respectively. After that, the state of the radio buttons is tested. Hence, if radioAddis selected, the values in the variables aand bare added, and the addition is stored in the resultvariable. Similarly, if radioSubtractis selected, the values in variables aand bare subtracted, and the result is stored in result. Similarly, multiplication and division operations are performed when radioMultiplyand radioDivideare selected. Finally, the result of the computation stored in resultis displayed via labelResult. Figure 8.2 displays the addition and division operations applied to the number values entered in the LineEdit widgets. Figure 8.2. (a) The addition operation applied to two numbers on selection of the Add radio button. (b) The division operation applied to the numbers on selection of Divide radio button. Radio buttons display mutually exclusive options. You can select only one option from a set of available options. Selecting another option automatically deselects the earlier selected option. What if you want to select more than one option? Let’s see. Using Checkboxes Where radio buttons allow only one option to be selected in a group, checkboxes allow you to select more than one option. That is, selecting a checkbox will not affect other checkboxes in the application. Checkboxes are displayed with a text label as an instance of the QCheckBox class. A checkbox can be in any of three states: selected (checked), unselected (unchecked), or tristate (unchanged). Tristate is a no change state; the user has neither checked or unchecked the checkbox. The methods provided by QCheckBoxare shown in Table 8.3. Table 8.3. Methods Provided by the QCheckBox Class Method Use isChecked() Returns true if the checkbox is checked; otherwise returns false. setTristate()Pass Boolean value true to this method to use the “no change” state of the checkbox. With this state, you give the user the option of neither checking nor unchecking a checkbox. setIcon() Used to display an icon with the checkbox. setText() Used to set the text of the checkbox. To specify a shortcut key for the checkbox, precede the preferred character with an ampersand in the text. setChecked() Pass Boolean value true to this method to make the checkbox checked by default. The signals emitted by QCheckBoxare shown in Table 8.4. Table 8.4. Signals Emitted by the QCheckBox Class Signal Description toggled() The signal is emitted whenever a checkbox changes its state from checked to unchecked or vice versa. clicked() The signal is emitted when a checkbox is activated (i.e. pressed and released) or when its shortcut key is typed. stateChanged() The signal is emitted whenever a checkbox changes its state from checked to unchecked or vice versa. Note The QAbstractButtonclass is the abstract base class of button widgets and provides functionality common to buttons. It provides support for pushbuttons, checkboxes, and radio buttons. To understand the Checkbox widget, let’s assume that you run a Food Corner where several food items such as pizzas, hot dogs, french fries, and chicken burgers are sold. The price of the food item is also mentioned with it. The user can select one or more food items. What you want is that when a food item is selected, the total price of the selected food items will be displayed. Begin by creating a new application based on the Dialog without Buttons template. Drag and drop two Label widgets, one LineEdit widget, four checkboxes, and a push button onto the form. Set the textproperty of the two Label widgets to XYZ Food Cornerand Total Amount. Through the Property Editor, increase the font size of the first Label and make it bold to make it appear as a header in the application. Also, disable the LineEdit by unchecking its enabled property from the Property Editor because you will be displaying the result of computation with it and don’t want it to be editable. Set the text of the four checkboxes to Pizza $20, Hot Dog $5, French Fries $10, and Chicken Burger $15. Also, set the text of the push button to Calculate Amount. The default objectNames of the four checkboxes are checkBox, checkBox_2, checkBox_3, and checkBox_4. Change these to checkPizza20, checkHotDog5, check-Fries10, and checkBurger15, respectively. Also set the objectNameof the push button and LineEdit to CalculateButtonand lineAmount, respectively. The form will appear as shown in Figure 8.3. Figure 8.3. Form with four checkboxes, a push button, and a LineEdit widget in disabled mode. Save the application with the name checkbx.ui. The.ui(XML) file is then converted into Python code through the pyuic4command utility. The Python code is shown here: checkbx.py # Form implementation generated from reading ui file 'checkbx.ui' from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(328, 270) Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) self.label = QtGui.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(110, 10, 141, 20)) font = QtGui.QFont() font.setPointSize(11) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setText(QtGui.QApplication.translate("Dialog", "XYZ Food Corner", None, QtGui.QApplication.UnicodeUTF8)) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(40, 210, 81, 16)) self.label_2.setText(QtGui.QApplication.translate("Dialog", "Total Amount", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setObjectName(_fromUtf8("label_2")) self.lineAmount = QtGui.QLineEdit(Dialog) self.lineAmount.setEnabled(False) self.lineAmount.setGeometry(QtCore.QRect(120, 210, 131, 20)) self.lineAmount.setObjectName(_fromUtf8("lineAmount")) self.checkPizza20 = QtGui.QCheckBox(Dialog) self.checkPizza20.setGeometry(QtCore.QRect(110, 40, 91, 17)) self.checkPizza20.setText(QtGui.QApplication.translate("Dialog", "Pizza $20", None, QtGui.QApplication.UnicodeUTF8)) self.checkPizza20.setObjectName(_fromUtf8("checkPizza20")) self.checkHotDog5 = QtGui.QCheckBox(Dialog) self.checkHotDog5.setGeometry(QtCore.QRect(110, 70, 111, 17)) self.checkHotDog5.setText(QtGui.QApplication.translate("Dialog", "Hot Dog $5", None, QtGui.QApplication.UnicodeUTF8)) self.checkHotDog5.setObjectName(_fromUtf8("checkHotDog5")) self.checkFries10 = QtGui.QCheckBox(Dialog) self.checkFries10.setGeometry(QtCore.QRect(110, 100, 121, 17)) self.checkFries10.setText(QtGui.QApplication.translate("Dialog", "French Fries $10", None, QtGui.QApplication.UnicodeUTF8)) self.checkFries10.setObjectName(_fromUtf8("checkFries10")) self.checkBurger15 = QtGui.QCheckBox(Dialog) self.checkBurger15.setGeometry(QtCore.QRect(110, 130, 121, 17)) self.checkBurger15.setText(QtGui.QApplication.translate("Dialog", "Chicken Burger $15", None, QtGui.QApplication.UnicodeUTF8)) self.checkBurger15.setObjectName(_fromUtf8("checkBurger15")) self.CalculateButton = QtGui.QPushButton(Dialog) self.CalculateButton.setGeometry(QtCore.QRect(100, 170, 141, 23)) self.CalculateButton.setText(QtGui.QApplication.translate("Dialog", "Calculate Amount", None, QtGui.QApplication.UnicodeUTF8)) self.CalculateButton.setObjectName(_fromUtf8("CalculateButton")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): pass Let’s import the code as a header file in our program to invoke the user interface design and to write code to calculate the total cost of food items selected and display the cost through a LineEdit widget when the user selects the push button. Let’s name the program callchecks.pyw; its code is shown here: callchecks.pyw import sys from checkbx import * class MyForm(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.CalculateButton, QtCore.SIGNAL('clicked()'), self.calculate) def calculate(self): amt=0 if self.ui.checkPizza20.isChecked()==True: amt=amt+20 if self.ui.checkHotDog5.isChecked()==True: amt=amt+5 if self.ui.checkFries10.isChecked()==True: amt=amt+10 if self.ui.checkBurger15.isChecked()==True: amt=amt+15 self.ui.lineAmount.setText(str(amt)) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_()) The clicked()event of CalculateButtonis connected to the calculate()function, which will calculate the cost of the food items selected. In the calculate()function, you check the status of the checkboxes to know if they are checked or unchecked. The cost of the food items whose checkboxes are checked is added and stored in the amtvariable. Finally, the addition of the amount stored in amtis displayed via lineAmount. To avoid any alterations in the amount displayed via LineEdit, LineEdit is disabled. On running the application, you get a dialog prompting you to select the food items that you want to order. Figure 8.4(a) shows the total cost for Hot Dog and French Fries, and Figure 8.4(b) shows the total for all food items. Figure 8.4. (a) The cost of two food items is displayed. (b) The cost of all four food items is displayed. [View full size image] Initiating Action Without Using a Push Button In the previous application, you saw that the total cost of the food items selected by the user appears only when the CalculateButtonpush button is selected by the user. It is so because the calculate()function that does the computation is connected to the push button’s clicked()signal. Now let’s modify the application slightly. Instead of selecting the push button for getting the result, you want the amount to be displayed when the user checks or unchecks any checkbox, without the need to select the push button. It also means that you want the calculate()function to be fired every time the status of any checkbox changes and not on selecting the push button. To apply these modifications, you will remove the push button and connect the clicked()signal of each checkbox to the calculate()method. As a result, the total amount will be displayed via the lineAmountLineEdit, as soon as any checkbox is checked or unchecked. The application will appear as shown in Figure 8.5. Figure 8.5. Form with the push button removed and LineEdit disabled. Save the modified application with a different name, checkbx2.ui. When the.ui(XML) file is converted into Python code through the pyuic4command utility, it will appear as shown here: checkbx2.py # Form implementation generated from reading ui file 'checkbx2.ui' from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectN