Python 101: First Steps

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 21 minutes

 

Learn Python

Hi. Welcome to Python 101. In the first chapter of this course, I'll go over the ins and outs of the Python programming language. I'll also give you my introduction. We'll end the chapter by making our first program in Python. Here is an overview of contents:


About the course

Python 101 helps you to learn Python by building. Whether you are new to programming or an experienced programmer, this series will be of use to you. At the start of each chapter, we will go over what you will be able to do after you have completed the chapter, by showing you programs you will be able to make. Then we will cover the conceptual building blocks of these programs one by one. What will we be covering? As much as we can.

We'll cover everything in a laid-back, smooth fashion, touching on things mentioned in the program(s) leading into the chapter, contrary to the traditional method where a tutor will tell you everything about a particular topic before implementing them. Rest assured, we will cover every single basic building block by the end of this course. You will find end-of-chapter exercises as well, to strengthen your command and enhance your problem-solving skills.

About the Tutor

Skip this and jump to Python

Lakshay Arora @ djangoSpin

I am Lakshay Arora, and I work as a System Analyst for Amdocs. When I am on my own, I spend my time exploring various technologies. Over the past 5 years, ever since I started college, I have worked with HTML, CSS, javascript, AJAX, Perl, Java, Servlets and JSPs, Flash, Unix, SQL, Python among other things.

I had huge help from Mr John W Purcell, from Hungary, who runs the famous website Cave of Programming. I should state that while I am not proficient in most of these languages, I do have the required working knowledge. You can view my work at www.lakshayarora.com. I hosted many of my fundamental projects here, before I started this blog with a friend of mine, at djangoSpin, to share all that we know about anything and everything. I have been interested in Python mainly because of its emphasis on readability and succinctness.

I didn’t really like the machine-level work involved with C/C++. Things like pointers, memory management, and other concepts were difficult for me to comprehend, much less effectively apply. Java, as my first programming class in college, was a start but its object-oriented programming (OOP) concepts gave me fits. While I can work with many languages, I never thought to myself that I am proficient in anything other than HTML, but I wanted to devote my career to one major language. I have always been in awe of developers who spend so many years to develop a programming language, so that the general folk can use it for the good of mankind. Hence, my desire to excel in at least one of them, so that I can apply it in real-life situations, to save effort and maximize productivity.

Then I learnt that Google employs Python extensively, and I was fascinated how it could power the most powerful search engine of the world. I researched about it a bit and found that it has a massive footprint all over the internet, and how versatile it is. Then I thought to myself, maybe this is the language for me. As I studied about it, I realized that it is incredibly easy to grasp because of its emphasis on readability, and thought I would share my knowledge with the rest of the world.

Currently, I am working in Django, which is a web framework in Python. Django is an open-source framework that takes the complexity out of web development and at the same time, it gives you control over as much as you want.


All about PythonPython @ DjangoSpin

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java. The language provides constructs intended to enable clear programs on both a small and large scale. - Wikipedia


Why Python?

So, why would you be interested in taking up Python? Well, here's why:

  • Easiest-to-learn & Most-enjoyable-to-use: Python is arguably the easiest-to-learn programming language, and the most enjoyable to use.
  • Powerful: Python has all the power you'd expect from a modern programming language. By the end of this course, you'll learn how to process files, how to employ a variety of data structures. If you choose to opt for creating a graphical user interface for your program, you could do that as well. You could create an online blog using Django, create a 2D game with PyGame, create a visual novel, carry out web scraping etc.
  • Main Emphasis: The main emphasis of Python is readability, reusability & maintainability of code and enhancing productivity. We will see this as we proceed further.
  • General-purpose nature: Being a general purpose language implies allowing its user to write software in a wide variety of application domains. You could automate a simple task of mailing yourself a file on your desktop every Thursday at 9 pm, or you could create a visual novel with it, pursue GUI development, make web apps with it, make a blog with Django, so on and so forth.
  • Used frequently to glue projects together: It has bindings for C/C++ and Java so it is common to blend large projects together using interfaces built in Python.
  • Interactivity: Python can be used interactively in the command line to execute one statement at a time. It also comes with IDLE, its own text editor which has an inbuilt interpreter, where you can execute commands one by one, and view the result immediately. The interactivity enables us to create scripts in a flash, which can be used for rapid prototyping. Prototyping, in programming terms is a rough draft of the final product that companies deliver to their customers, with limited features and core functionality intact. Python can also be used in a realtime interpreter for testing code snippets before adding bundling into an executable file.
  • No braces and semi-colons: One of the most popular characteristics of Python is its use of white space to differentiate between statements. Although it is not a genuine reason for anyone to learn Python, but people who have experience with Java, C++, C# will find it a pleasant change to work without braces and semi-colons. Braces in these languages are used to separate blocks of code, and semi-colons are statement delimiters, i.e. to create a barrier between consecutive statements. Python uses indentation for separating blocks of code and carriage return as statement delimiter. This feature has been derived from the language ABC, from which Python itself was largely derived.
  • Cross-platform: Python can be run on Windows and Unix-like systems all the same.
  • It is a Scripting Language: Meaning that it’s not compiled to create the machine-readable code, like a programming language called C++.
  • Enjoyment: Due of Python’s ease of use and built-in toolset, programming can seem like pleasure rather than a tedious chore. Although this may not sound very convincing, it does have a significant impact on the productivity.
  • High Level Language: Now, what that means is that it takes care of a lot of things that will usually throw off a beginner. According to Wikipedia, "In computer science, a high-level programming language is a programming language with strong abstraction from the details of the computer. In comparison to low-level programming languages, it may use natural language elements, be easier to use, or may automate (or even hide entirely) significant areas of computing systems (e.g. memory management), making the process of developing a program simpler and more understandable relative to a lower-level language." "There are three general modes of execution for modern high-level languages: compiled, interpreted, trans-compiled." We have briefly discussed the first two, with C++ being a compiled language, and Python being an interpreted language. The third kind simply means that the code is translated to another language that is much more widely used, like C.
  • Dynamic Typing/Duck Typing: Python is a dynamic-typed or duck-typed language. Many other languages, like C++, Java etc. are static typed. Meaning that they require the programmer to explicitly mention what type of data each variable is. For beginners, variables are containers for different values that are used in the program. For example, name of a person is of type string (combination of characters), and his age is of type integer. In static typing, you explicitly mention that the variable name is of type string, whereas dynamic typing indicates that if a variable behaves like a string, it is a string, and we need not mention it that it is a string. The reason it is also called duck typing, is that it refers to the duct test, which is attributed to Mr James Whitcomb Riley, and it is as follows "When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck." If this doesn't make sense to you right now, it will in time, when we dive into the language.
  • Fairly small keywords list: Keywords are reserved words, they have special meaning in the language. Python has the following keywords:
    False     class     finally     is     return
    None    continue    for    lambda    try
    True     def     from    nonlocal    while
    and       del       global       not       with
    as         elif          if          or          yield
    assert    else    import    pass    break
    except    in    raise
  • Choice of paradigm: Procedural & Object-oriented Programming: Do not be put off by these terms, they only look ponderous. Procedural Programming paradigm suggests a step-by-step process of a developing program, calling procedures/functions/methods/subroutines to perform some processing, then control returns back to the main program. Examples of procedural languages are C and BASIC.
    Object-Oriented Programming (OOP) paradigm deals with making classes. A Class is a prototype of similar objects e.g. a car is a class and Mercedes and BMW are its objects. Each class will have variables and methods (that's what they call functions in this OOP terms) which each of its objects will inherit e.g. variables(properties/attributes) of a car could be its engine power, its top speed, and methods could be ignite(which triggers the ignition of the car) brake, accelerate. Aside from these, the objects can have variables and methods of their own, which are characteristic of these objects only e.g one object may have airbag method, whereas another object may have spoiler variable. I hope you get the gist. I have only scratched the surface here, if you are interested in OOPs, you could try googling it a bit, it is an extremely widely used paradigm. We, at djangoSpin, have a course on Object Oriented Python.
    Python employs both of these paradigms, it in fact offers a choice to the developer, whether to tackle a program step-by-step using functions or creating classes to achieve the same. You could start with procedural approach, which is much easier in my view. Then you could move onto OOP, which can be daunting at first, but Python is a great language to get to grips with the OOP paradigm. Object Oriented programming is widely acclaimed for developing large projects. In this course, we will be following the procedural way of programming.
  • Many lines of interest: You could develop 2D games with PyGame library, you could take up GUI development with Tkinter & PyQT, choose to make web apps with frameworks like Flask, Django etc.
  • Extensive Standard Library: One of Python’s great attributes is that it comes with an extensive standard library — this enables us to do tasks like download an image or any file for that matter from the Internet, start a web server, or manipulate a compressed archive file all with just one or a few lines of code.
  • Strong Community: Python has a huge and strong community. Not only does it have a dedicated newsgroup, but it also has Python Tutor mailing list, especially for beginners. It is located at http://mail.python.org/mailman/listinfo/tutor. The mailing list is not limited to beginners, anyone can ask questions here. Something that is evident is that the community by and large is extremely open and friendly, just like the language is user-friendly.
  • Versatility: Generally speaking, all languages are versatile, but its bindings to C, its readability, its general-purpose nature, wide community, list of libraries available, and a very good development team led by Guido van Rossum, all this makes Python versatile.
  • Well-paid jobs: Python jobs are generally very well-paid. In fact it is one Google's recruiting tactics to see if a person is googling Python terms frequently, and if he is, he may even receive a call from Google, just like this guy here.
  • It is open source: Not only is Python free, but Python's license allows you to even modify it and resell it. By allowing this freedom, Python has epitomized the ideals of open source software and this is one of the many reasons that Python is so popular.
  • Succinctness: One of the features that attracted me towards Python was that you could get a lot done in a few lines of code, as compared to many other languages. Programming languages like Java, C, C# are verbose, but Python is succinct. For example, here's a program in C, C#, Java and Python to achieve the same purpose.
  • /* C Program to generate Fibonacci Series*/
    
    #include <stdio.h>
    
    int main() {
      int n, number1 = 0, number2 = 1, next, c;
      printf("Enter the number of terms\n");
      scanf("%d",&n);
      printf("First %d terms of Fibonacci series are :-\n",n);
    
      for ( c = 0 ; c < n ; c++ ) {
        if ( c <= 1 )
          next = c;
        else {
          next = number1 + number2;
          number1 = number2;
          number2 = next;
        }
        printf("%d\n",next);
      }
    
      return 0;
    }
    
    /* C# program to generate Fibonacci Series */
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace fibonacci {
     class Program {
     static void Main(string[] args) {
     int i, count, number1 = 0, number2 = 1, number3 = 0;
     Console.Write("Enter the number of fibonacci numbers: ");
     count = int.Parse(Console.ReadLine());
     Console.WriteLine(number1);
     Console.WriteLine(number2);
     
     for (i = 0; i <= count; i++) {
     number3 = number1 + number2;
     Console.WriteLine(number3);
     number1 = number2;
     number2 = number3;
     }
     Console.ReadLine();
     }
     }
    }
    // Java Program to generate Fibonacci Series
    
    class Fibonacci {
        public static void main(String args[]){
          int number1=0,number2=1,number3,i,count=10;
          System.out.print(number1+" "+number2);
    
          for(i = 2; i < count; ++i) {
            number3 = number1 + number2;
            System.out.print(" " + number3);
            number1 = number2;
            number2 = number3;
          }
       }
    }
    
    # Python program to generate Fibonacci Series
    
    def fib(n):
        a, b = 0, 1
            while a < n:
                print(a, end=' ')
                a, b = b, a+b
                print()
    
    fib(1000)
    

All these features of this language, not only do they make Python a great first language to learn, but it has also lured a lot of high-level programmers.

You have seen why any person may decide to learn Python. However, it is my duty to discuss with you why someone may decide against it.


Why not Python?

Every coin has a flip side, and as per my knowledge, the only flip side to this coin is the speed of execution. The speed of execution of Python programs is not as fast as some of the compiled languages like C and C++. However, Python has been optimized several times, and to be realistic, it is fast enough not to be considered a slow language.


History of Python

  • Designed by Guido van Rossum in December 1989
  • Named after Monty Python’s Flying Circus, a popular British sketch series created by the comedy group Monty Python
  • Developed by Python Software Foundation
  • Successor of ABC language with capability of exception handling
  • Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator for Life (BDFL) - Wikipedia
  • Python 2 was released on October 16, 2000
  • Python 3 came out on December 3, 2008

Difference between Python 2 and 3

Python 3 is the latest version of Python, and Python 2 is still very widely used due to the fact that many libraries are not yet available for Python 3, so Python 2 still runs of plenty of systems out there. In fact, many linux distributions come with Python 2.6 or 2.7 pre installed.

However, Guido van Rossum, the creator has made it clear that Python 2 will not be maintained after 2020, to carry out mass adoption of Python 3. So, if you are a beginner, it's safe to start with Python 3.

Just so you know, there is a program called 2to3 to convert the source code of a Python 2 program to the source code of a Python 3 program.

Here are a few notable alterations in Python 3:

  • print() is a function and not a statement
  • long data type not present anymore
  • greater support for unicode text
  • xrange() became range()
  • raw_input() became input(), which always returns a string

For further reading, visit this page & this page.


Use of Python in today's world:

  • Google makes extensive use of Python in its web search systems, and employed Python’s creator, Guido van Rossum for 7 years till 2012 before he started working for Dropbox.
  • Youtube, the online video service is mostly written in Python.
  • The popular peer-to-peer file sharing system BitTorrent is programmed in Python.
  • Google’s popular App Engine web development framework uses Python as its application language.
  • Quora, the Q & A site, makes extensive use of Python.
  • Maya, a popular 3D modeling and animation system, provides support for Python.
  • Intel, Cisco, Seagate and IBM use Python for hardware testing.
  • Pinterest, the social network is built with Django, a popular web framework of Python.
  • Dropbox has Python foundations as well.
  • Sublime Text, the famous text editor is a Python program.

Other examples include Reddit, Bitbucket, Spotify, Unity 3D and a lot more.It's like Carbon, you use one or more of these services daily without knowing that it's Python in the background.


What can a person do with Python?

  • Automate Tasks: To state a few examples, you could have Python mail particular backup files periodically to your email address, pull text off a web page, search through thousands of excel records looking for ones that you need to update, rename thousands of .jpeg files to .png files etc.
  • Systems Programming: Python comes with a module called os, which is included in the standard installation, using which Python programs can search files and directories, launch other programs, do parallel processing with threads and processes, and so on. Python’s standard library comes with POSIX bindings and support for all the familiar OS tools: environment variables, files, sockets, pipes, processes, multiple threads, regular expression, command-line arguments etc.
  • GUI, Desktop Apps: Using Tkinter, you can easily design neat and sophisticated graphical interfaces to your programs. You may also want to research  on PyQT, which is also a popular Python graphical toolkit.
  • Prototyping: It is fairly common to prototype complete projects in Python, and then move the selective components to a compiled language like C or C++ for delivering to the customer. In fact, many components remain coded in Python for easy maintenance and re-usability.
  • Create 2D games with Pygame: Pygame is a very popular python library that was designed so that programmers can utilize it to create games.
  • Create Web Apps: There are many web frameworks built in Python, and you can use them to create full fledged web applications. They support quick construction of full-featured and production-quality websites with Python. Many of these frameworks come with features such as object-relational mappers and are often based on a Model-View-Controller architecture. Examples of such frameworks include: Django, TurboGears, web2py, Flask
  • Hacking Tools: I am not encouraging it, but Python has been well known for its hacking qualities. In fact, many companies carry out penetration testing of their systems by hiring hackers skilled in Python. Penetration testing is a type of testing that exposes the vulnerabilities of a system, network or web applications.
  • Internet/Network Programming: Python's libraries make it incredibly simple to communicate over sockets, process information to CGI scripts, parse XML files, transfer files via FTP protocol and much more. To name a few Python modules used for internet/network programming: httplib, urllib, xmlrpclib, ftplib, smtplib, poplib and telnetlib
  • Cryptanalysis: Cryptanalysis simply means decrypting a cipher, or coded text. Python has been very prominently used for breaking ciphers.
  • Scientific programming using numpy, matplotlib and scipy: The SciPy module is an open source module used by scientists and analysts for carrying out scientific computing, it is powered by Numpy module, which provides multidimensional arrays to facilitate the complex operations. Numpy also powers Matplotlib. Matplotlib is a plotting library, and provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like wxPython, Qt, or GTK+.
  • Big Data Analysis: Many data-intensive industries carry out the analysis of big data using pandas library, i.e. Python Data Analysis Library, it is an open source library for Python which provides easy-to-use data structures, data manipulation and data analysis tools.
  • Glue large projects together: As I said earlier, it has bindings for C/C++ and Java so it can be used to blend large projects together using interfaces built in Python.
  • Embedded Python: There are many tiny and affordable computers out there, which understand Python commands and translate them into mechanical actions, e.g. Raspberry Pi, Arduino to name two. You could make a toy train move in forward and backward directions just by calling forward and backward methods.
  • Database Access:  Python provides interfaces to all commonly used relational database systems - Sybase, Oracle, Microsoft SQL Server 2000, ODBC, MySQL, PostgreSQL, SQLite. To use any of these, one would have to install it using Python package manager pip, and then import it in the program. For example, if you want to use MySQL database with your program, you will install it using pip, and then write something like import MySQLdb in your program. For more on installing modules using pip, refer to this article.
  • Testing: Python has a strong affinity for test-driven development. Test-driven development means you write test cases first before you actually start developing your program/project. Python is often used to test components written in other languages. To achieve this, the unittest module is imported into the program. Then there are doctests to verify that each method is behaving as expected.

Why yet another course

So why have I decided to make a Python course when there are plenty of similar ones online....

It's true, there are many Python tutorials, courses & books out there which are aimed at teaching Python, all of which are very well designed. That being said, we at djangoSpin have followed a practical approach towards teaching Python. You will learn to build constructive programs. That's how I learnt it, and it has stuck pretty well in my head.

Because at the end of the day, just typing away at the computer, making non-productive is not enough, we need to be able to use programming languages to solve real-life problems, automate tasks that take human effort, leverage the power of technology. Like Mark Zuckerberg did, with facebook, or Larry Page with Google. Granted we won't reach the level they did by taking a basics course, but is surely a step in the right direction by following a hands on approach.


Where to get help

In case you hit a roadblock, these are a few places where you could seek help. However, do not be limited to these links, there are plenty of doors you could knock.

As I said, there are plenty more on the web. If you do a bit of googling, I am sure you'll find that there are plenty of other programmers who stumbled like you did, and there is a good chance that you will find a solution page, because as I mentioned, Python has a large and strong community, much like other popular programming languages. If you want, you could post your doubts in the comments below, and we at djangoSpin, will have a look at it for you.


How to run Python online

If you have wondered if you can run Python online, then the answer is, yes, you can. There are many interpreters online, two of the most popular are:

  • Python.org: Go to Python.org, click on the yellow button with a chevron and an underscore (>_ ). It will launch an interpreter from pythonanywhere.com. You can execute your statements here like you do in IDLE (Python's own text editor) or in command line.
  • Repl.it: Go to Repl.it. As of January 2017, its homepage provides a language search bar. Search for Python3. Here you will find a textpane where you can write your statements and then click on run button to execute them. REPL in the programming world stands for Read-Eval-Print-Loop. The interpreter reads the commands, evaluates it, prints the requisite and this goes on. The pane on the right gives you the Python interpreter where you execute commands one by one.

Installing Python

Before you can write your first program, you need to get the language installed on your computer. To do so:

  • Go to Python's official website.
  • Click on the Downloads tab. You'll see a page similar to the one presented below.
  • The page tries to guess your Operating System and provides you suitable choices. Download the latest version of Python using the button provided.
  • Alternatively, scroll down and click on the topmost item in Release version list. This opens another page with version details, new features etc. Scroll to the bottom of this page to a section called Files. You will see a screen similar to below.
  • Choose the correct version for your Operating System, using the following instructions:
    • For Mac users, click on Mac OS X 64-bit/32-bit installer link. This will download a .dmg file on your system. Once the download completes, execute the file by double-clicking it. As of January 2017, a window should pop-up with 4 icons. Right-click on Python.mpkg and click Open in the dialog box. Follow through the installer by clicking Continue a couple of times, and click Install. Upon completion, this will install Python as /usr/local/bin/python3. If your system already had Python 2 installed, it will remain installed along with newly installed Python 3.
    • For Windows users, download either Windows x86-64 executable installer or Windows x86 executable installer, based on whether your computer is 32-bit or 64-bit. You can find out whether your computer is 64-bit or 32-bit by Right-clicking Computer on your desktop > Properties > System-type attribute in System values. After the executable has finished downloading, execute it by double-clicking. As of January 2017, the Python installer shows you two options: Install Now and Customize Installation. If you click on Customize Installation (don’t click it for now), you’ll find five checkboxes: Documentation (.chm file for when you press F1), pip (installing new packages from the web), tcl/tk and IDLE (for GUI development), Python test suite (unittests, doctests), py launcher (Python shortcut) and an option to install Python for all users on your computer. Experienced programmers can go ahead with tweaking details in Customize Installation, but we will go with the Install now option, and let Python install the complete package. Make sure that the Add Python x.x to PATH is checked, this way the installer appends the path to Python executable (C:\Pythonxx\python.exe or C:\Users\xxxxxx\AppData\Local\Programs\Python\Pythonxx-xx\python.exe) in your PATH environment variable. This Python executable is executed upon python command in command line. Once the install wizard is done, click on the Close button.
    • For Linux and Unix users, download either XZ compressed source tarball or Gzipped source tarball. Decompress the downloaded file using tar command, and then run the extracted shell script.
To verify the installation, enter into the command line: python -V. If everything in the installation went smoothly, this statement should return the current version of Python on your system.

Python's IDE: IDLE

Once you have installed Python successfully, find IDLE (Python GUI) in the list of programs installed on your system. Run it.

IDLE is Python's Integrated Development and Learning Environment.

  • It is coded in 100% Python, using the GUI toolkit called Tkinter.
  • IDLE, works the same on Windows, Unix and Mac OS X, meaning that it is cross-platform.
  • It has built in shell, where you can execute commands interactively.
  • The text editor opens when you go to File > New File. Alternatively, you will see a Edit with IDLE context menu option upon right-clicking a .py file.
  • Like modern IDEs, it suggests tab completion and provides color coding.
  • It also has a debugger, which we will see how to use in the miscellaneous/goodies section.

Executing your first statement: Interactive Shell (console) and Scripts

Enough about IDLE, it's about time that you make Python do something. One way of running Python commands is in the interpreter. So, run IDLE (All programs on your computer > IDLE Python GUI), and in front of the three chevrons (>>>) type in

print("Hello from IDLE")

Take a look at what you just typed. Without much knowledge of Python syntax, you would have guessed what this statement does. That's Python in a nutshell. The print() function simply spits the text inside quotation marks onto the console. I'll go over it in the next section, and we will use it extensively in the subsequent chapters. Let's execute this by pressing enter. You would have expected this already, it says "Hello from IDLE" like this:

>>> print("Hello from IDLE")
Hello from IDLE
The three chevrons (>>>) is what is called a prompt.  Once you see the output, the prompt reappears, letting you know that Python is ready for executing more commands.

This is the interactive shell in action.

If you want to write a script that does the same, click on File > New File, type the same statement again and save it anywhere on your system, using a .py extension. Click on Run menu > Run module or press F5, it produces the same result.

Outside of IDLE, if you execute a .py by double clicking on it, say the one you just created with a single print statement, then you will notice that a console window opens for a brief moment, and then it vanishes. In fact, it would have vanished too quickly for you to read anything printed on the screen. There are two ways for making the screen stay till you have read the message in the print statement, both of which lie beyond the scope of this chapter. Having said that, I'll go over these very quickly.
First, after the print statement, in a new line, type input(). I'll tell you more about the input function when the time is right. For now, suffice it to say that we have typed this in order to wait for the user to press any key before the program terminates. Save the file and execute the .py by double-clicking on it.
Second, create a batch file i.e. a .bat file (Windows users), type in python file_name.py, replacing the file_name by your file name and in the second line, type pause. Save this file, and execute it by double-clicking on it. It will produce the same result.

The difference between the scripting method and the interactive shell is that the interactive shell allows you to type in one statement at a time, where as in the script, you can type in as many as you want before you ask the interpreter to process them in bulk. Scripts help you save time by not having to type the same statements over and over again.


Command line execution

You might have noticed that when you were saving the script, the file was saved with a .py extension, that's the extension for Python files. This is the fact that we use to execute Python files from the command line. So, let's do that.

  • For Windows, press Windows + R for the run dialog, type in cmd and press enter.
  • The command line dialog pops up, now, type python complete_path_to_file.py e.g. python C:\DirOne\file1.py.
  • A handy way to do this entire process is, go into the directory that contains your .py file. Press shift + right click on your mouse > open command window here, then python file.py.
  • You'll see the same output.

The way this works is that the Python keyword invokes the python.exe interpreter which executes your .py file. If you want an interactive Python shell in the command window, type in python and press enter. As you can see, it provides the same window as in IDLE.

  • For Mac users, go into the terminal, navigate into your working directory (that is, the directory you have chosen to keep your learning Python files in)
  • Type in touch file.py, edit it with vi or nano by vi name_of_file.py or nano name_of_file.py
  • Give permissions to your user to execute the script by chmod 777 file.py
  • Then typing python file.py in the terminal will execute it.

The location of Python interpreter in Mac and linux distributions is normally /usr/local/bin/python3. In Windows, it is something like C:\Pythonxx\python.exe if you accepted defaults, this address may vary if you installed it somewhere else and/or if you installed a different version of Python.
When you are executing the Python script from terminal or command line or IDLE, it is safe to assume that they will find the Python interpreter. But it is a good practice to include shebang/hashbang in the first line of your scripts i.e. #!C:\Python35\python.exe for Windows, again depending on the installation directory, and #!/usr/local/bin/python3 for Mac.

If you don't like the simplistic look and feel of IDLE, you can always go for a text-editor, like the one I use every now and then, Sublime Text. I really like the IDLE interface, because it is a native Python coded software, but I have worked in Sublime Text for almost 2 years now, I have grown fond of it. You can choose text-editor of your choice.
I have mentioned this before, you can even execute Python statements online, on the Python.org, or on Repl.it > Python3 in language search bar (according to its homepage as of January 2017). REPL in the programming world stands for Read-Eval-Print-Loop. The interpreter reads the commands, evaluates it, prints the requisite and this goes on.


Arithmetic in IDLE

What's 9 times 8.2? You'd probably need a calculator, and if you are smart like my brother, you can work it out in your mind, but that's not the point. You can have the Python console do the math for you. So how does that work? Just put the expression that you would like Python to evaluate at the prompt (>>>) e.g.

>>> 9 * 8.2
73.8

... and it will give you the result. Granted this is not a ground-breaking feature, it just helps to know this.


Your first Python Program

Okay then, time for your first Python program (finally, huh?).

 

# Program to print the complete mailing address of a person

print("Sherlock Holmes")
print("Consulting Detective")
print("221B Baker Street")
print("London")
print("UK")

Try to run it here.

What does this program do? These lines print the complete mailing address of a person. It is a bunch of print functions, which execute one after the other and throw text onto the console. By default, each print statement ends with a new line, that is, whatever you type inside the quotes of a single print function is printed in the new line. We will see how to use multiple print functions and still have the text on the same line. The print function is extensively used for debugging purposes, that is, checking where the control of the program has reached. You will see this in action as you build complex programs.

The statements beginning with a hash, are known as comments. These lines are completely ignored by the interpreter. But the usefulness of comments is felt when you trying to make your code readable and well documented. However, keep in mind that you use them for important information only. Redundant comments only contribute to the size of the Python script, and not to readability of code. Takeaway: Do NOT use comments for conveying trivial information. Only use them to convey important information.

If you type the print function with an uppercase P, or alter its case in any way, and then execute it, you will notice that the interpreter doesn't execute the statement and throws a syntax error. This highlights the case sensitivity in Python. You have to type these keywords in small case only, with a few exceptions such as True, False etc.

Try typing these statements and executing them in one of the five methods we discussed earlier:

  • interactive interpreter in IDLE
  • interactive interpreter in command line
  • running a script in IDLE
  • running a script in command line
  • executing statements online

Next Chapter

In the next chapter, we will learn about variables (in particular, strings, integer numbers, floating point numbers, boolean), about input/output, operators, and how to control the flow of the program with statements. We will build 3 programs by the end of the chapter, namely: Fill the form, Leap Year, Even or Odd. See you then!


Exercises

  • Write a script to print your name, age, place of residence.

    Expand the below snippet for solution.

    print("My name is...")
    print("I am ... years old.")
    print("I live in ...")
    
  • Execute the above script by Run > Run Module (F5) option in IDLE as well as in command line using the python command.
  • Use the interpreter in IDLE to compute a few mathematical expressions such as 100 - 30, 23 * 5 etc.


See also:


Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply