Learn Python in 7 Days - Mohit, Bhaskar N. Das - E-Book

Learn Python in 7 Days E-Book

Mohit, Bhaskar N. Das

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Python is a great language to get started in the world of programming and application development. This book will help you to take your skills to the next level having a good knowledge of the fundamentals of Python.
We begin with the absolute foundation, covering the basic syntax, type variables and operators. We'll then move on to concepts like statements, arrays, operators, string processing and I/O handling. You’ll be able to learn how to operate tuples and understand the functions and methods of lists. We’ll help you develop a deep understanding of list and tuples and learn python dictionary. As you progress through the book, you’ll learn about function parameters and how to use control statements with the loop. You’ll further learn how to create modules and packages, storing of data as well as handling errors. We later dive into advanced level concepts such as Python collections and how to use class, methods, objects in python.
By the end of this book, you will be able to take your skills to the next level having a good knowledge of the fundamentals of Python.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 204

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Title Page

Learn Python in 7 Days
Get up-and-running with Python
Mohit
Bhaskar N. Das

       BIRMINGHAM - MUMBAI

Copyright

Learn Python in 7 Days

Copyright © 2017 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.

First published: May 2017

Production reference: 1190517

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham 
B3 2PB, UK.

ISBN 978-1-78728-838-6

www.packtpub.com

Credits

Authors  

Mohit

Bhaskar N. Das 

Copy Editor

Muktikant Garimella

Reviewer

Rejah Rehim

Project Coordinator

Ulhas Kambali 

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Denim Pinto 

Indexer

Pratik Shirodkar 

Content Development Editor

Anurag Ghogre

Graphics

Abhinash Sahu

Technical Editor

Hussain Kanchwala

Production Coordinator

Deepika Naik

  

About the Authors

Mohit ([email protected]) is a Python programmer with a keen interest in the field of information security. He has completed his bachelor's degree in technology in computer science from Kurukshetra University, Kurukshetra, and master’s in engineering (2012) in computer science from Thapar University, Patiala. He is a C|EH, ECSA from EC-Council USA and a former IBMer. He currently works in Sapient. He has published several articles in national and international magazines. He is the author of  Python Penetration Testing Essentials and Python: Penetration Testing for Developers, also by Packt.

His LinkedIn profile is https://www.linkedin.com/in/mohit-990a852a/.

First of all, I am grateful to the Almighty for helping me to complete this book. I would like to thank my mother for her love and encouraging support and my father for raising me in a house with desktops and laptops. A big thanks to the co-author, Bhaskar Das. I would also like to thank everyone who has contributed to the publication of this book, including the publisher, especially the technical reviewers and also the editors, Denim and Anurag. Last but not least, I'm grateful to my i7 Dell XPS laptop, without which it would not have been possible to write this book.

Bhaskar N. Das ([email protected]) is an application developer with a keen interest in the field of analytics and financial markets. He completed his Bachelor of Technology in Mechanical Engineering from Dehradun Institute of Technology, India and his master's degree in science (2014) in CSR and ethical management from FH BFI, Vienna, Austria. He has eight years of experience with IBM and has worked on several web and analytics-related technologies. He has published technical articles in leading magazines.

His LinkedIn profile is https://www.linkedin.com/in/bhaskar-das-093a2012/.

It has been my pleasure to work with the Packt team, and I am thankful to them for providing me with such a wonderful opportunity. I am also thankful to my co-author Mohit for his invaluable help. Finally, I am thankful to my family who just helped me to timely complete the work. Well, this work would not have been possible without the newly devised CDP tool, so a great thanks should be given to it and also to all the resources that helped in the timely completion of this book.

About the Reviewer

Rejah Rehim is currently a security architect with Faya Innovations, India and is a long-time preacher of open source and has authored a book titled, Effective Python Penetration Testing. He is a steady contributor to the Mozilla Foundation and his name has been featured in the San Francisco Monument made by the Mozilla Foundation.

He is a part of the Mozilla add-on review board and has contributed to the development of several node modules. He has also been credited with the creation of eight Mozilla add-ons, including the highly successful Clear Console add-on which was selected as one of the best Mozilla add-ons of 2013. With a user base of more than 44,000, it has registered more than 6,50,000 downloads till date. He has successfully created the world's first one-of-a-kind security testing browser bundle, PenQ, an open source Linux-based penetration testing browser bundle preconfigured with tools for spidering, advanced web searching, fingerprinting, and so on.

Rejah is also an active member of the OWASP and a chapter leader of OWASP Kerala. He is also an active speaker at Coffee@DBG, one of the most premier monthly tech rendezvous in Technopark, Kerala. Besides being a part of the Cyber Security division of Faya currently and QBurst in the past, Rejah is also a fan of process automation and has implemented it in Faya.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/Learn-Python-7-days-Mohit/dp/1787288382/.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Getting Started with Python

Why Python?

Python applications

Versions

Implementations of Python

Installation

Installation on Windows platform

Installation on Linux platform

Installation on Mac OS

Notepad++ installation

Python file formats

Python interactive shell

System or environment variables

Setting environment variables in Windows

Setting environment variables in Linux

Setting environment variables in Mac OS (OS 10.9)

Writing a simple Hello World! program

Basic Python syntax

Comments in Python

Triple, double and single quotes

Python back slash

String inside the quotes

Escape sequence in Python

String concatenation

Formatted output

Indentation

Summary

Type Variables and Operators

Variables

Single assignment

Multiple assignment

Data types in Python

Numeric data types or numbers

Integers and long integers

Floating point numbers

Complex numbers

Boolean data type

String data types

American Standard Code for Information Interchange (ASCII) character sets

Conversion functions

Arithmetic expressions

Mixed mode arithmetic

Mixed Mode Conversion

Type conversions

Operators

Arithmetic operators

Comparison operators

Variants of assignment operator

Bitwise operators

Logical operators

Membership operators

Identity operators

Operator precedence

Summary

Strings

Python strings

The subscript operator

Slicing for substrings

Python string methods

String case methods

String strip methods

String split methods

String justify methods

String Boolean methods

String functions

Tuple

Creating an empty tuple

Creating tuple with elements

Indexing tuple

Slicing of tuple

Unpacking the items of tuples

Tuple functions

Operations of tuples

Exercise

Summary

Lists

Creating a list

Creating a list with values

Unpacking list values

List operations

Accessing list values

Slicing the list

Updating the list

Deleting values from a list

Addition of Python lists

Multiplication of lists

in operator

List functions

len()

max ()

list ()

sorted ()

List methods

append ()

extend ()

Difference between append and extend.

count ()

index ()

insert()

remove()

pop()

reverse()

List comprehensions

Exercises

Summary

Dictionary

Overview of dictionary

Operations on the dictionary

Accessing the values of dictionary

Deleting an item from the dictionary

Updating the values of the dictionary

Adding an item to the dictionary

Dictionary functions

len()

str()

max()

min()

dict()

Dictionary methods

copy()

get()

setdefault()

has_key()

keys()

values()

update()

items()

clear()

Python dictionary with for loop

Practical program

Exercise

Summary

Control Statements and Loops

Control statements

The if and if...else statement

The if...elif...else statement

Loops

Types of loops

Definite loop

Indefinite loop

The while True and break statement

The break statement

Nested loops

The continue and pass statements

The pass statement

Summary

Function and Scope of Variable

Functions

Categories of functions

Built-in functions

User-defined functions

Function definition

Calling a function

Function with arguments

Function with an argument and return type

Function with default argument

Function with variable length argument

Key-value pair as variable length argument

Pass by reference versus pass by value

Scope of variables

Memory management

Summary

Modules and Packages

Modules

The import statement

Locating Python modules

Compiled Python files

The Python package

Summary

File Handling and Exceptions

Reading text from a file

The read() method

The readline() method

The readlines() method

Exercise

Writing text to a file

Examples

Pickling

Unpickling

Exceptions

The try statement with an except clause

Multiple exception blocks

The try...finally statement

The exception argument

Raising exceptions

User-defined exceptions

Summary

Collections

Collections

Counter

Update function

Usage of counters

Operations of Python collection counter

Deque

Populating deque

Deque consumption

Deque rotation

Ordered dictionary

Sorting of ordered dictionary based upon keys

Sorting of ordered dictionary based upon values

Default dictionary

Sample problem solved by the default dictionary - scenario one

Sample problem solved by the default dictionary - scenario two

Named tuple

Adding values and creating a dictionary

Summary

Class and Objects

Object-oriented programming overview

Key concepts

Creating a class

Instance variables

The __init__ method

Class variables

Class inheritance

Multiple inheritance

Multilevel inheritance

Overriding methods

Operator overloading

The class method

The static method

The private variable

Summary

Preface

Python was initially developed by Guido Von Rossum as a fun project and was named after his favorite show Monty Python's Flying Circus. It was developed in 1991, but it started becoming popular around 2008. A major contributor to this popularity was Google, which has developed a number of platforms using Python. Recently, Python has been popularized by cloud, DevOps, data science, data analytics, machine learning, and natural language processing. With more and more data harvesting and data processing, people want to get into new types of job roles, which require basic programming skills, and Python perfectly suits all the categories of job work. Learn Python in 7 Days has been designed to give such people an easy way to learn and master the basics of Python in 7 days. The book covers the basic and necessary concepts that are required to understand the working of the Python language. The book is for all types of readers and learners. It also acts as a refresher for experienced people. We believe that we have covered as much as possible for making it a book to be finished in seven days; however, we believe that merely reading the book is not sufficient to master programming skills. It will take more than that to achieve mastery. We hope you enjoy reading the book and use it as a good learning book.

What this book covers

Chapter 1, Getting Started with Python, gives you the background of Python programming language, along with installation instructions and basic commands.

Chapter2, Type Variables and Operators, gives you an idea of variable types and the various types of operators used in Python.

Chapter 3, Strings, sheds light on various strings and string operations in Python.

Chapter 4, Lists, gives the idea of one of the important collection types, called lists, available in Python and all the relevant operations that could be done on lists.

Chapter 5, Dictionary, covers another important collection type available in Python and deals with the basics of dictionary and the various operations on a dictionary.

Chapter 6, Control Statements and Loops, discusses about various control statements, such as if statement, and loops (for, while, and so on), which could be used to write a piece of code in Python.

Chapter 7, Function and Scope of Variable, gives you an idea about functions that could be user-defined or built in. The chapter talks about the basics of a function and various operations. Also, the chapter gives you an idea about the validity of a variable within the particular scope of the code block.

Chapter 8, Modules and Packages, discusses about various modules and packages that are available in Python and also how to create your own package and module.

Chapter 9, File Handling and Exceptions, is divided into two parts; the first part deals with different file handling operations and the second part deals with exception handling.

Chapter 10, Collections, gives you the primer for different types and subtypes of collections in Python and explains the basic operations that could be done on them.

Chapter 11, Class and Objects, finally gives you an idea about some object-oriented programming concepts that are available in Python.

What you need for this book

For this book, you need to install Python 2.7x version on your machine, along with a simple text editor (Notepad or Notepad++). All the examples are meant to be run on the Python 2.7 version and will not work in Python 3.x versions.

Who this book is for

This book is intended for people who have zero to some background in computer programming. It is also intended for people who want to have some refresher in Python programming.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The next step is to editbuild.propertiesfile."

A block of code is set as follows:

print "Name Marks Age" print ( "%s %14.2f %11d" % ("John Doe", 80.67, 27)) print ( "%s %12.2f %11d" %("Bhaskar" ,76.901, 27))print ( "%s %3.2f %11d" %("Mohit", 56.98, 25))

Any command-line input or output is written as follows:

$ brew install python

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Once done, click on Activate."

Warnings or important notes appear in a box like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at https://github.com/PacktPublishing/Learn-Python-in-7-days. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Java-9-Programming-By_Example. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Getting Started with Python

The Python language had a humble beginning in the late 1980s when a Dutchman Guido Von Rossum started working on a fun project, which would be a successor to ABC language with better exception handling and capability to interface with OS Amoeba at Centrum Wiskunde and Informatica. It first appeared in 1991. Python 2.0 was released in the year 2000 and Python 3.0 was released in the year 2008. The language was named Python after the famous British television comedy show Monty Python's Flying Circus, which was one of Guido's favorite television programmes. Here we will see why Python has suddenly influenced our lives and the various applications that use Python and its implementations. In this chapter, you will be learning the basic installation steps that are required to perform on different platforms (that is Windows, Linux, and Mac), about environment variables, setting up of environment variables, file formats, Python interactive shell, basic syntaxes and finally printing out formatted output.

Why Python?

Now you might be suddenly bogged with the question, why Python? According to  Institute of Electrical and Electronics Engineers (IEEE) 2016 ranking Python ranked third after C and Java. As per Indeed.com's data of 2016, the Python job market search ranked fifth. Clearly, all the data points to the ever rising demand in the job market for Python. Its a cool language if you want to learn just for fun or if you want to build your career around Python, you will adore the language. At school level, many schools have started including Python programming for kids. With new technologies taking the market by surprise Python has been playing a dominant role. Whether it is cloud platform, mobile app development, BigData, IoT with Raspberry Pi, or the new Blockchain technology, Python is being seen as a niche language platform to develop and deliver a scalable and robust applications.

Some key features of the language are:

Python programs can run on any platform, you can carry code created in Windows machine and run it on Mac or Linux

Python has inbuilt large library with prebuilt and portable functionality, also known as the standard library

Python is an expressive language

Python is free and open source

Python code is about one third of the size of equivalent C++ and Java code

Python can be both dynamically and strongly typed--dynamically typed means it is a type of variable that is interpreted at runtime, which means, in Python, there is no need to define the type (

int

 or 

float

) of the variable

Python applications

One of the most famous platforms where Python is extensively used is YouTube. The other places where you will find Python being extensively used are the special effects in Hollywood movies, drug evolution and discovery, traffic control systems, ERP systems, cloud hosting, e-commerce platform, CRM systems, and whatever field you can think of.

Versions

At the time of writing this book, two main versions of the Python programming language were available in the market, which are Python 2.x and Python 3.x. The stable release as of writing the book were Python 2.7.13 and Python 3.6.0.

Implementations of Python

Major implementations include CPython, Jython, IronPython, MicroPython, and PyPy.

Installation

Here we will look forward to the installation of Python on three different OS platforms, namely, Windows, Linux, and Mac OS. Let's begin with the Windows platform.

Installation on Windows platform

Python 2.x can be downloaded from https://www.python.org/downloads. The installer is simple and easy to install. Perform the following steps to install the setup:

Once you click on setup installer, you will get a small window on your desktop screen as shown here; click on

Next

:

Provide a suitable installation folder to install Python. If you don't provide the installation folder, then the installer will automatically create an installation folder for you, as shown in the following screenshot. Click on

Next

:

After completion of step 2, you will get a window to customize Python as shown in the preceding screenshot. Notice that the 

Add python.exe to Path

option has been marked

x

. Select this option to add it to system path variable (which will be explained later in the chapter), and click on

Next

:

Finally, click on 

Finish

to complete the installation: