Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learn Python in 7 Days
Learn Python in 7 Days

Learn Python in 7 Days: Begin your journey with Python

eBook
S$32.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Learn Python in 7 Days

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:

  1. Once you click on setup installer, you will get a small window on your desktop screen as shown here; click on Next:
  1. 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:
  1. 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:
  1. Finally, click on Finish to complete the installation:

Installation on Linux platform

These days most of the Linux-based systems come preloaded with Python, so in most cases, you do not need to install it separately. However, if you do not find your desired version of Python on the Linux platform, you can download your desired version for a particular Linux platform from the site https://www.python.org/downloads/source/. Perform the following steps:

  1. Extract the compressed file using the tar -xvzf python_versionx.x command.
  2. Browse the directory of the compressed file as shown in the screenshot:
  1. Run the following commands:
      [root@localhost Python-2.7.12]# ./configure
[root@localhost Python-2.7.12]# make
[root@localhost Python-2.7.12]# make install
  1. Use the command as shown in screenshot to ensure that Python is running:

Installation on Mac OS

For Mac OS, you will get the installer from the site https://www.python.org/downloads/mac-osx/

For the new Mac OS X, Sierra comes loaded with Python 2.7 and it's good for learning but the same cannot be used to develop advanced-level programs. You do not need to separately install Python on the new Mac OS X. However, a word of caution is that the version of Python packed with the Mac OS could be out of date and might require updating. If you still want to install a separate version, you can follow the simple steps mentioned as follows:

  1. First of all, you might require to install Xcode, Xcode is the IDE for  platform and can be downloaded from the Apple appstore.
  2. Once Xcode is installed, you need to install the command-line tools, which can be installed by running the xcode-select --install command on the terminal found under /Applications/Utilities/, as shown in the following screenshot:
  1.  A pop-up window appears with three different options as shown here:
  1. Once you click on Install and agree to their terms and conditions, the command-line tools will start to download and will be installed in few minutes depending on the Internet connection.
  1. The next step in the process would be to install Homebrew, which is a package manager for Mac OS and handles the Python package. In order to install Homebrew, simply provide the following inputs to the terminal:

      /usr/bin/ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)"
  1. To install the latest python2 version, simply type brew install python on the terminal:
      $ brew install python
In order to install python3, you need to use brew install python3.

Notepad++ installation

Notepad++ is one of the easy-to-use text editors and is a free open source software program, which could be easily downloaded from https://notepad-plus-plus.org/. We will be using this text editor to create simple programs.

Python file formats

Every language understands a file format, for example, like the C language file extension is .c likewise java language has a file extension .java. The Python file extension is .py while bytecode file extension is .pyc.

Python interactive shell

Python interactive shell is also known as Integrated Development Environment (IDLE). With the Python installer, two interactive shells are provided: one is IDLE (Python GUI) and the other is Python (command line). Both can be used for running simple programs.

For complex programs and executing large files, the windows command prompt is used, where after the system variables are set automatically, large files are recognized and executed by the system.

The preceding screenshot is what we call Python IDLE, which comes bundled with the Python installation. The next screenshot is of the command line that also comes bundled with the Python installation, or we can simply launch the Python command through the windows command line and get Python command line. For most of our programming instructions, we will be using the Python command line:

System or environment variables

If you remember the installation steps explained earlier, you might be still thinking what are system variables? They are a set of predefined variables, which are available to all programming units. If it's not set, then each and every time you want to run your program or execute a Python file, you will have to manually provide path for each Python executable, but if python.exe is set as a system variable, then the system automatically recognizes your programming instruction and starts executing.

Setting environment variables in Windows

Here, if python.exe is not provided to the path variable, then the system does not recognize python as a command, as shown in the following screenshot:

The Windows command prompt does not recognize python as shown in the previous screenshot. Once Python has been updated in the path variables or system variables, the windows command line recognizes the python command and executes as shown here: 

During installation, the installer provides an option to set system variables, which we have seen in our installation steps. But in case you missed that out, you need not worry. You can manually set the system variables. Simply follow these steps:

  1. Just right-click on My Computer (older version of Windows PC) or Computer (win 7 onwards) and select Properties. Once you have selected the properties, you will get the following screenshot where you need to select Advanced system settings:
  1. After you have clicked on Advanced system settings, you will get System Properties. Click on the Environment Variables button. 
  2. After completing Step 2, a window will pop up. From the System variables pane, select Path and click on the Edit button.
  3. Your Python installation will look something like the following screenshot, where you need to right-click on the address bar and select the Copy address as text option:
  1. Add the Python installation folder path to the Path variable.
  2. Click on OK and then again on OK to close all the windows. Our system variable is set:

Setting environment variables in Linux

Linux comes with different types of shells and the Python directory path is usually /usr/local/bin/python:

  • csh shell: Open the terminal and enter setenv PATH "$PATH:/usr/local/bin/python" followed by pressing Enter
  • bash shell: On the terminal, enter export PATH="$PATH:/usr/local/bin/python" followed by pressing Enter
  • sh or ksh shell: Enter PATH="$PATH:/usr/local/bin/python" followed by pressing Enter

Setting environment variables in Mac OS (OS 10.9)

Here, simply you need to edit the launchd.conf file and add the path variable to the file:

$ sudo edit /etc/launchd.conf
setenv PYTHONPATH /Users/vesper/temp:/Users/vesper/misc

Writing a simple Hello World! program

Congratulations on your successful installation. Now you can start programming. Open Notepad++ and create a new file. In the new file, type the following:

print "Hello World!" 

Save the file as hello.py.

Open the command prompt and traverse to the folder where your file is located using cd and then the path of the folder. For executing the file, the command will be python hello.py as shown in the following screenshot:

It is quite easy, isn't it? Likewise, you can execute all the Python files. Once you start working on projects and large files, it's always good to remain organized by creating a folder structure.

Basic Python syntax

Basic syntaxes can be referred to as simple guidelines that every programming language requires. Let's try to understand from our daily lives. Let's say you can't eat your food without having it dressed and placed properly on the platter. You need to have proper dressing of food before you can consume it. You prepare a special drink comprising three measures of Gordon gin, one of vodka, half of Kina Lillet, and follow the process to mix in steps. The process is necessary to have a perfect blend. These are sort of syntaxes when we talk in terms of programming languages.

Kina Lillet-Lillet (French pronunciation: [li'le]), classed as an aromatized wine within EU law, is a French aperitif wine from Podensac, a small village south of Bordeaux. It is a blend of 85% Bordeaux region wines (Semillon for the Blanc and for the Rosé, Merlot for the Rouge) and 15% macerated liqueurs, mostly citrus liqueurs (peels of sweet oranges from Spain and Morocco and peels of bitter green oranges from Haiti). The mix is then stirred in oak vats until blended. During the aging process, Lillet is handled as a Bordeaux wine (undergoing fining, racking, filtering, and so on).
The preceding information has been taken from https://en.wikipedia.org/wiki/Lillet.

Comments in Python

In Python, there are two types of comments--one is a single-line comment and the other is multiline comment. For a single-line comment, # is used, while for a multiline comment, triple quotes """ are used:

#This is a single line comment in Python

print "Hello World" #This is a single comment in Python

""" For multi-line
comment use three
double quotes
...
"""
print "Hello World!"

Triple, double and single quotes

Python doesn't care if you use single quotes or double quotes to print a single statement. But, surely, both has some significance while printing complex statements, which we will see soon.

print "Hello World!" and print 'Hello World!' will give the same output Hello World! two times:

How will you print something like this:

I am mad in love  do you think  I am doing the right thing? One way is to enclose the complete thing within the triple quotes as shown here:
print '''I am mad in love
do you think
I am doing
the right thing '''

Alternatively, you can also use double quotes three times to achieve the same thing:

print """I am mad in love
do you think
I am doing
the right thing """
The preceding two examples are not in formatted form, they are just to show how we can achieve multiline printing.

Let's try another example. What should be the outcome of the following statement?

print 'Hey there it's a cow'

The preceding piece of code gives the following results:

C:pydev>python hello.py
File "hello.py", line 1
print 'Hey there it's a cow'
^
SyntaxError: invalid syntax

Python simply interprets that the statement terminated with a single quote after it. The solution is to enclose the complete sentence within double quotes as shown:

print "Hey there it's a cow"

Adding double quotes (") gives an error-free output as shown:

C:pydev>python hello.py
Hey there it's a cow

Python back slash

The Python back slash is used for continuation of the print statement. You can stretch a single statement across multiple lines:

print "Hello
world "

This gives the following output:

C:pydev>python hello.py
Hello world

String inside the quotes

For printing a string, either a pair of single (' ') quotes or pair of double quotes (" ") can be used as shown in the succeeding examples: 

print "Hello World 'Mr' Bond"
print 'old world "but" still good'

This gives the following results:

C:pydev>python hello.py
Hello World 'Mr' Bond
old world "but" still good

Escape sequence in Python

The escape sequence is used to insert the tab, the newline, the backspace, and other special characters into your code. They give you greater control and flexibility to format your statements and code:

Escape Sequence Meaning
b Backspace
a Sound system bell
n Newline
t Horizontal tab
The character
' Single quotation mark
" Double quotation mark
print 'a' 
print 'tHermit'
print "i know , they are 'great'"

The output is as follows:

C:pydev>python hello.py
Hermit
i know , they are 'great'

The preceding code executes with a beep sound. If you did not hear the beep sound, check your speakers.

String concatenation

Two strings can be joined using the + operator:

print "Only way to join" + "two strings"

The following is the output of the preceding code:

C:pydev>python string_concatenation.py
Only way to join two strings

Formatted output

Consider an example where you would want to print the name, marks, and the age of the person:

print "Name", "Marks", "Age" 
print "John Doe", 80.67, "27"
print "Bhaskar", 76.908, "27"
print "Mohit", 56.98, "25"

The output will be as follows:

C:pydev>python hello.py
Name Marks Age
John Doe 80.67 27
Bhaskar 76.908 27
Mohit 56.98 25

You can see the output, but the output that is displayed is not formatted. Python allows you to set the formatted output. If you have done some coding in C language, then you should be familiar with %d, %f, %sIn order to represent an integer %d is used, %f is used for float, and %s is used for string. If you used %5d, it means 5 spaces. If you used %5.2f, it means 5 spaces and .2 means precision. The decimal part of the number or the precision is set to 2. Let's use the formatting on the preceding example:

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))

The output we get is as follows:

C:pydev>python hello.py
Name Marks Age
John Doe 80.67 27
Bhaskar 76.90 27
Mohit 56.98 25

The preceding output is much better than the previous one. You can see Marks 76.901 set to 76.90 automatically.

Indentation

The most unique characteristic of Python, unlike other programming languages, is indentation. Indentation not only makes Python code readable, but also distinguishes each block of code from the other. Let's explain this with an example:

def fun():
pass
for each in "Australia":
pass

While writing the code, a new block of code starts with a colon followed by a tab. Here, after the function fun(), a colon is provided which will start the function body, pass is part of the function fun() and it is placed at one tab space. Likewise, the for loop starts with a colon. Here, most people get confused whether to use a tab or space. It is advisable to stick to only one type and follow the same across the whole code. If the indentation is not strictly implemented, then code execution will throw an error.

Summary

So far, we did a walkthrough of the beginning and the brief history of Python. We looked through various implementations and flavors of Python. We also learned about installation on various platforms. We learned about basic syntaxes that are used in writing the code and also we learned about various escape sequences that would make writing the code simple. We finally learned about the importance of indentation in Python.

In the next chapter, we will see immutable data types.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Make the best of Python features
  • Learn the tinge of Python in 7 days
  • Learn complex concepts using the most simple examples

Description

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.

Who is this book for?

The book is aimed at aspiring developers and absolute novice who want to get started with the world of programming. We assume no knowledge of Python for this book.

What you will learn

  • Use if else statement with loops and how to break, skip the loop
  • Get acquainted with python types and its operators
  • Create modules and packages
  • Learn slicing, indexing and string methods
  • Explore advanced concepts like collections, class and objects
  • Learn dictionary operation and methods
  • Discover the scope and function of variables with arguments and return value

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 25, 2017
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781787287778
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : May 25, 2017
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781787287778
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 269.97
Python: Journey from Novice to Expert
S$134.99
Learn Python in 7 Days
S$59.99
Python Machine Learning By Example
S$74.99
Total S$ 269.97 Stars icon

Table of Contents

11 Chapters
Getting Started with Python Chevron down icon Chevron up icon
Type Variables and Operators Chevron down icon Chevron up icon
Strings Chevron down icon Chevron up icon
Lists Chevron down icon Chevron up icon
Dictionary Chevron down icon Chevron up icon
Control Statements and Loops Chevron down icon Chevron up icon
Function and Scope of Variable Chevron down icon Chevron up icon
Modules and Packages Chevron down icon Chevron up icon
File Handling and Exceptions Chevron down icon Chevron up icon
Collections Chevron down icon Chevron up icon
Class and Objects Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Half star icon Empty star icon Empty star icon Empty star icon 1.5
(2 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 50%
1 star 50%
DNAunion Dec 26, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Although published in 2017, this book does not cover the latest version of Python, and explicitly stated:"For this book, you need to install Python 2.7x version on your machine, along with a simpletext editor (Notepad or Notepad++). All the examples are meant to be run on the Python 2.7version and will not work in Python 3.x versions."This is very strange considering that Python 3 has been out since 2008, and Python.org says "Short version: Python 2.x is legacy, Python 3.x is the present and future of the language "I am getting a big disgusted with Packt books.
Amazon Verified review Amazon
Ann Oct 27, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Very poorly explained and full of errors
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.