Python Fundamentals

Python Fundamentals

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Authors: Ryan Marvin, Mark Ng'ang'a, and Amos Omondi

Managing Editor: Taabish Khan

Acquisitions Editor: Koushik Sen

Production Editor: Nitesh Thakur

Editorial Board: David Barnes, Ewan Buckingham, Simon Cox, Manasa Kumar, Alex Mazonowicz, Douglas Paterson, Dominic Pereira, Shiny Poojary, Saman Siddiqui, Erol Staveley, Ankita Thakur, and Mohita Vyas

First Published: October 2018

Production Reference: 1311018

ISBN: 978-1-78980-732-5

Table of Contents

Preface

Introducing Python

Introduction

Python 2 Versus Python 3

Working with the Python Interactive Shell

Exercise 1: Checking our Python Installation

Exercise 2: Working with the Python Interpreter

Activity 1: Working with the Python Shell

Writing and Running Simple Scripts

Exercise 3: Creating a Script

Running a File Containing Invalid Commands

Exercise 4: Passing User Arguments to Scripts

Activity 2: Running Simple Python Scripts

Python Syntax

Variables

Values

Exercise 5: Checking the Type of a Value

Type Conversion

Exercise 6: Assigning Variables

Exercise 7: Using Variables

Multiple Assignment

Activity 3: Using Variables and Assign Statements

Naming Identifiers and Reserved Words

Exercise 8: Python Keywords

Python Naming Conventions

Activity 4: Variable Assignment and Variable Naming Conventions

User Input, Comments, and Indentations

User Input from the Keyboard

Passing in a Prompt to the input Function

Using Different Input Data Types in your Program

Exercise 9: Fetching and Using User Input

Comments

Indentation

Exercise 10: The Importance of Proper Indentation

Activity 5: Fixing Indentations in a Code Block

Activity 6: Implementing User Input and Comments in a Script

Summary

Data Types

Introduction

Numerical Data

Types of Numbers

Exercise 11: Converting Between Different Types of Number Systems

Operators

Order of Operations

Activity 7: Order of Operations

Activity 8: Using Different Arithmetic Operators

Strings

String Operations and Methods

Indexing

Slicing

Activity 9: String Slicing

Length

String Formatting

String Methods

Activity 10: Working with Strings

Escape Sequences

Exercise 12: Using Escape Sequences

Activity 11: Manipulating Strings

Lists

List Operations

Exercise 13: List References

Activity 12: Working with Lists

Booleans

Comparison Operators

Logical Operators

Membership Operators

Activity 13: Using Boolean Operators

Summary

Control Statements

Introduction

Control Statements

Program Flow

Control Statement

The if Statement

Exercise 14: Using the if Statement

Activity 14: Working with the if Statement

The while Statement

Exercise 15: Using the while Statement

Exercise 16: Using while to Keep a Program Running

Activity 15: Working with the while Statement

while Versus if

Loops

The for Loop

Exercise 17: Using the for Loop

Using else

The range Function

Activity 16: The for loop and the range Function

Nesting Loops

Exercise 18: Using Nested Loops

Activity 17: Nested Loops

Breaking Out of Loops

The break Statement

The continue Statement

The pass Statement

Activity 18: Breaking out of Loops

Summary

Functions

Introduction

Built-In Functions

User-Defined Functions

Calling a Function

Global and Local Variables

Exercise 19: Defining Global and Local Variables

Function Return

Using main()

Function Arguments

Required Arguments

Keyword Arguments

Default Arguments

Variable Number of Arguments

Activity 19: Function Arguments

Anonymous Functions

Exercise 20: Creating a Lambda Function

Activity 20: Using Lambda Functions

Summary

Lists and Tuples

Introduction

List Syntax

List Methods

list.append(item)

list.extend(iterable)

list.insert(index, item)

list.remove(item)

list.pop([index])

list.clear()

list.index(item [, start [, end]])

list.count(item)

list.sort(key=None, reverse=False)

list.reverse()

list.copy()

Activity 21: Using the List Methods

List Comprehensions

Tuple Syntax

Exercise 21: Creating a Tuple

Accessing Tuple Elements

Indexing

Exercise 22: Accessing Tuple Elements Using Indexing

Slicing

Exercise 21: Creating a Tuple

Accessing Tuple Elements

Indexing

Exercise 23: Accessing Tuple Elements Using Slicing

Tuple Methods

Activity 22: Using Tuple Methods

Summary

Dictionaries and Sets

Introduction

Working with Dictionaries

Activity 23: Creating a Dictionary

Exercise 24: Adding Data to a Dictionary

Exercise 25: Reading Data from a Dictionary

Exercise 26: Iterating Through Dictionaries

Checking for the Existence of Particular Keys

Additional Dictionary Attributes

dict.update()

dict.clear() and dict.pop()

dict.copy()

dict.popitem()

dict.setdefault()

dict.fromkeys()

Activity 24: Arranging and Presenting Data Using Dictionaries

Ordered Dictionaries

Activity 25: Combining Dictionaries

The Basics of Sets

Exercise 27: Creating Sets

Exercise 28: Adding Data to a Set

Exercise 29: Reading Data from a Set

Activity 26: Building a Set

Exercise 30: Removing Data from a Set

Set Operations

Union

Intersection

Difference

Subsets

Equality

Update Methods

Frozen Sets

Activity 27: Creating Unions of Elements in a Collection

Summary

Object-Oriented Programming

Introduction

A First Look at OOP

OOP in Python

Defining a Class in Python

Exercise 31: Creating a Class

Instantiating an Object

Exercise 32: Instantiating a Person Object

Adding Attributes to an Object

The __init__ Method

Exercise 33: Adding Attributes to a Class

Activity 28: Defining a Class and Objects

Methods in a Class

Defining Methods in a Class

Exercise 34: Creating a Method for our Class

Passing Arguments to Instance Methods

Exercise 35: Passing Arguments to Instance Methods

Exercise 36: Setting Instance Attributes within Instance Methods

Activity 29: Defining Methods in a Class

Class Versus Instance Attributes

Exercise 37: Declaring a Class with Instance Attributes

Class Attributes

Exercise 38: Extending our Class with Class Attributes

Exercise 39: Implementing a Counter for Instances of a Class

Activity 30: Creating Class Attributes

Class Versus Instance Methods

Exercise 40: Creating Instance Methods

Class Methods

Exercise 41: Testing our Factory Method

Exercise 42: Accessing Class Attributes from within Class Methods

Encapsulation and Information Hiding

Activity 31: Creating Class Methods and Using Information Hiding

Class Inheritance

Exercise 43: Implementing Class Inheritance

Overriding __init__()

Exercise 44: Overriding the __init__ Method to Add an Attribute

Commonly Overridden Methods

Activity 32: Overriding Methods

Multiple Inheritance

Exercise 45: Implementing Multiple Inheritance

Activity 33: Practicing Multiple Inheritance

Summary

Modules, Packages, and File Operations

Introduction

Defining Modules

Exercise 46: Creating Modules

Imports and Import Statements

Exercise 47: Importing Modules

Modules and Packages

The Module Search Path

Standard Python Modules

Activity 34: Inspecting Modules

Packages

Absolute Imports

Relative Imports

Activity 35: Listing the Resources Defined in a Package or Module

Activity 36: Using Resources in a Module

File Operations

The file Object

The file Object Methods

Reading and Writing to Files

The open() Method

Exercise 48: Creating, Reading, and Writing to Files

The with Context Manager

Activity 37: Performing File Operations

Handling Structured Data

Working with CSV Data

Activity 38: Working with Files

Working with JSON Data

Summary

Error Handling

Introduction

Errors and Exceptions in Python

How to Raise Exceptions

Built-In Exceptions

SyntaxError

ImportError

KeyError

TypeError

AttributeError

IndexError

NameError

FileNotFoundError

Activity 39: Identifying Error Scenarios

Handling Errors and Exceptions

Exercise 49: Implementing the try…except Block

Exercise 50: Implementing the try…except…else Block

Exercise 51: Implementing the finally Keyword

Activity 40: Handling Errors

Custom Exceptions

Implementing Your Own Exception Class

Activity 41: Creating Your Own Custom Exception Class

Summary

Appendix A

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.231.194