Introduction to Python Programming

Introduction to Python Programming

In this article. We will explorer some of the reasons why people pick python for their programming task. We will discuss about the common ways to launch python programs: by running code typed at interactive Python shell. by executing python scripts and IDE GUIs such as IDLE. This article will equip you with enough information to enable you to start writing some code.

Learning outcomes: 

  • Describe why python is known as powerful language.
  • Understand and comprehend the basics of Python programming. 
  • Use python shell and python IDLE to write simple programs. 
  • Make use of variables, literal constants in code. 
  • Handle strings and indentation in python. 

What is Python? 

Python is a high level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It frequently uses simple English keywords, where as other languages use punctuations, and it requires fewer syntactical constructions in comparison to other languages. Python allows a programmer to concentrate on the solution to the problem rather than the syntax and structure of the language. We are programming in. 

  • Python is Interpreted. 
  • Python is Interactive. 
  • Python is Object Oriented. 
  • Python is a Beginner’s language. 

Let us describe one by one. 

  1. Python is Interpreted: Python is processed at runtime by the interpreter. This is similar to PERL and PHP. 
  1. Python is interactive: We just need to sit at a Python prompt in order to interact with the interpreter directly by writing statements on prompt.  
  1. Python is Object Oriented: Python supports Object-Oriented styles or technique of programming that encapsulates code with objects. Python is strongly objected-oriented in the sense that everything is an object, including numbers, strings, and even functions. 
  1. Python is a Beginner’s Language: It is a very simple programming language. for the beginner-level programmers and supports the development for wide range of applications from simple text processing to WWW browsers to games. 

Officially Python is introduced like this: 

Python is an easy to learn, powerful programming language. It has efficient high- level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature make it an ideal language for scripting and rapid application development in many areas on most platforms.

History of Python. 

Guido van Rossum, the creator of the Python language, named the language after the BBC show “Monty Python’s Flying Circus”. It is not named after the Python snake. He started implementing Python in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. 

Python is derived from many other languages including ABC, Modula-3, C, C++, Algol-68, Small Talk and Unix shell and other scripting languages. 

Python is copyrighted Like Perl, Python source code is now available under the GNU General Public License (GPL). 

Python is now maintained by a core development team at the institute, although Guido van Rossum Still holds a vital role in directing its progress. 

Python 1.0 version was released in November 1994. In 2000, python version 2.0 was released. Python 3.0 was released in 2008. 

Python 3 is not backward compatible with Python 2. The emphasis in Python 3 had been on the removal of duplicate programming constructs and modules, so that “There should be one and preferably only one obvious way to do it”. Python 3.8.1 is the latest version of Python 3. 

Why to do study Python

There are so many reasons to study/learn Python. Few of them are listed below:

  1. Python is Simple and Easy to Learn
  2. Python is Portable and Extensible
  3. Python for web development 
  4. Python is used in Machine Learning and Artificial Intelligence. 
  5. Python is used for building GUI
  6. Python is used in data science

Let us discuss one by one in brief. 

  1. Python is Simple and Easy to Learn: 

Python is extremely simple and easy to learn. It closely resembles English language. Python is simple because it is open source, high-level, interpreted and blessed with large community.

If we want to print ‘hello world’ in Java, we have to write above three lines whereas in Python, just one line is sufficient to print “hello world”. 

2. Python is portable and extensible: 

Python is supported by most platforms present in the industry today ranging from Windows to Linux to Macintosh, Solaris and Play stations, among others. 

3. Python for web development:

Python has an array of frameworks for developing websites. The popular frameworks are Django, Flask, Pylons etc. 

4. Python is used in machine learning and artificial intelligence:

Python is a popular language in machine learning as it can be used to build algorithms using statistics to allow computers to perform different actions. Some of the Python modules that are used to support machine learning are Theano, Scikit-learn, Tensorflow, etc. Also, Python is quite, useful in Artificial intelligence with libraries such as Keras that deals with neural network experimentation. 

5. Python is used for building GUI: 

Python can be used to build graphical user interfaces or desktop applications. Tkinter is the standard Python GUI that is included with the standard MAC OS X, Linux and Microsoft Windows install of Python. There are multiple cross-platform GUI toolkits available like PyQt, PySide, wx Python, kivy, etc. 

6. Python Adjusting Data Science:

Python is the leading language of many data scientists. For years, academic scholars and private researchers were using the MATLAB language for scientific research but it all started to change with the release of Python numerical engines such as ‘Numpy’and ‘Pandas’. Python also deals with the tabular, matrix as well as statistical data and it even visualizes it with popular libraries such as ‘Matplotlib’ and Seaborn’

1.4 Features of Python

Pythons features include: 

  • Readable. 
  • Easy to learn. 
  • Cross platform. 
  • Open source. 
  • Large standard library. 
  • Free. 
  • Supports exception handling. 
  • Automatic memory management. 

Let us describe one by one. 

  1. Readable: Python is a readable language as it closely resembles English Language. 
  1. Easy to learn: Python has few keywords, simple structure, and a clearly defined syntax. 
  1. Cross platform: Python is available and can run on various operating systems such as Mac, Windows, Linux, Unix, etc. This makes it a cross platform and portable language. 
  1. Open source: Python is an open source programming language. 
  1. Large standard library: Python comes with a large standard library that has some handy codes and functions which we can use while writing code in Python. 
  1. Free: Python is free to download and use. 
  1. Supports exception handling: Python supports exception handling, which means we can write, less error prone code and can test various scenarios that can cause an exception later on. 
  1. Automatic memory management: In Python, the memory is cleared and freed automatically, We do not have to bother about clearing the memory. 

Apart from the above mentioned features: 

  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications. 
  • It provides very high-level dynamic data types and supports dynamic type checking. 
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA and Java. 

1.5 How to install Python? 

Python is pre-installed on most UNIX system, including Linux and MAC OS X. But for Windows operating systems, users can download from http://www.python.org/downloads/ From the above link, download the latest version of Python. 

1.6 PYTHON – SHELL (INTERPRETER)

As we know, Python is an interpreted language, which means python executes the code line by line. There are two ways to use the interpreter (Python Shell) in Python: (a) Command-line mode (b) Script mode

(a) Command-line mode: It is used to execute single Python command and get the result. Python Shell waits for an input from the user. As the user enters the input (Command), it executes it and displays the result. To open the Python Shell on Windows, open the command prompt, write Python and press enter. 

Diagram: Python Shell

Example: We just input a simple expression like 2+6, press enter and it will display the result in the next line, as shown below.

Diagram: Command execution on python shell

(b) Script mode: Script is used to execute multiple statements (also known as python scripts) unlike command line mode which executes a single statement at a time. To execute python scripts, create a Python file with extension.py and write statements in a file which we want to execute.  

1.7 Python – IDLE

IDE stands for Integrated Development Environment. It is GUI (Graphical User Interface) based software which allows the programmers to write, debug and deploy their codes. Or we can simply say that, an IDE combines all essential tools needed for software development and testing which helps the programmer to produce good output.

IDLE (Integrated Development and Learning Environment) is an IDE for python. IDLE is free, easy to use, portable and automatically available on most platforms. IDLE is a python program that uses the standard library’s tkinter GUI toolkit (also known as Tkinter in 2.6). This makes IDLE portable, but it also means that you will need to have tkinter support in your python to use IDLE. The window version of python has this by default, but some Linux and Unix users may need to install appropriate tkinter support.

IDLE can be used to execute a single just like Python shell and also to create, modify and execute Python scripts. IDLE provides a fully-featured text editor to create Python scripts that includes features like syntax highlighting, auto-completion and smart indent. It also has a debugger with stepping and breakpoints features.

1.8 PROGRAMMING CYCLE FOR PYTHON

Programming cycle for Python program is as follows:

Step 1: Start with writing a program or editing (i.e. change/modify) the existing program using any text editor (Example: Notepad). 

Step 2: After writing or editing, we run this code with some input. There is no separate compilation steps required in python because it is an interpreted language (unlike C, C++, Java).  

Step 3: After running a code, if the output is not correct, we need to return to the editing step.

Step 4: Repeat Step 2 and 3 for other inputs if available otherwise end the cycle. 

1.9 INTERACTING WITH PYTHON PROGRAMS

There are lot of things which we need to know before we start writing complex programs in Python. We will Start learning from very basic things and grow our learning gradually in coming article beginning with letter its core things. 

1.9.1 Variables

A Variable is a memory space reserved in computer memory to store a value, and that value can be changed further if needed. This means that when we create a variable, we reserve some space in memory depending upon the type of value. Each value assigned to a variable has a data type. Variables are used by just assigning them a value. In Python, we do not need to define type of variable while declaring it. The interpreter implicitly binds the value with its type because python is a dynamically typed language.  

1.9.2 Constants 

A Constant is a type of variable whose value cannot be changed. Constants act as a container that holds information which can not be changed later.Or we can define constants as constants are symbols/labels that represents literal values that we assign to them.

In reality, we don’t use constants in Python. In python, constants are usually declared and assigned in a module. We generally name constants in all capital letters to separate them from variables; however, it does not actually prevent reassignment.

1.9.3 Literals

A literal or literal constant is a value, such as a number or string that may be assigned to a variable or symbolic constant, used as an operand in an arithmetic or logical operation, or as parameter to a function. For example-the number 5,1.23, or a string like “It’s a string!” all these are referred to as literal constants because there value cannot be changed. A literal always represent itself, nothing else (like the number 5 always represent the quantity of five only). In Python there are various types of literals, they are as follows:

(a) Numeric Literals: Numeric Literals are unchangeable. Numeric literals are of three types that is integer, float and complex

Integer– Represents positive or negative whole numbers with no decimal point (example -5, -2). Integer values can be further represented in 4 ways which are as follows: 

  • Decimal values (Base 10): Sequence of digits (0 to 9) unless start with Zero (example -4,-9).
  • Binary values (Base 2): Sequence of only 1 and 0, starts with 0B or 0b (example- 0b1011). 
  • Octal values (Base 8): Sequence of digits (0 to 7), starts with 0O or 0o (Zero-O) (example- 0o123). 
  • Hexadecimal values (Base 16): Sequence of (0 to 9, a to f, A to F) preceded by 0X or ox (example-0xFace, 0xA2B)

NOTE: One more numerical literal is Long which is used in 2.x but removed from python 3.

(b) String Literals: A string is collection of one or more characters kept into a single quote, double quote or triple quote.

(b) Boolean literals: A boolean literal can have any of the two values: True or False

(C) Special Literals: In Python, we have one special literal that is None. We use it to specify that the field has not been created.

1.9.4 Python is a Dynamically Typed Language

Python is a dynamically typed language whereas C, C++ and Java are statically typed languages. Because in Python there is no need to declare data type for the variables, it internally creates types, referring to the values.

Here is the example:

x=2 # python automatically assigns x as an integer
x=2.1 # python now accept x as float
x=”Hi” # python accept it as string now

What it means is: if we assign value of some other type to x, Python will not complain (show no error) but in C, C++or even in java, if we declare x as int then we can’t use it for float or string value, if we do this they will throw an error. Because in python, x (Variable) don’t have type but the value it points to have the type. That’s why we can make variable to points to a value or different type as shown below through diagram. 

Diagram dynamically typed variables in Python

1.9.5 Data types in Python

A data type represents the type of data stored into a variable or memory. The data types which are already available in Python language are called built-in data types. The data types which are created by the programmers are called user-defined data types. Data types are used to define the operations possible on particular kind of data and the storage method for each of them.  

Note: Everything in Python programming is an object. So, data types are actually the classes and variables are (objects) of these classes. We can use the type() function to know which class a variable or a Value belongs to. Similarly, the is instance() function can be used to check whether an object belongs to a particular class or not. The various standard data types defined in Python are given below. 

Diagram: Data Types defined in Python

  1. Number Data Type: Stores numeric values. Python creates number objects when a number is assigned to a variable. For example: age = 5 and weight = 23.5, here age and weight are numeric objects. It is an immutable data type which means that changing the value of a number data type results in a newly allocated object. Python support three types of numeric values. (a) Integer (b) Float (c) Complex
  1. String Data Type: A string is a sequence of characters. A string is basically a collection of one or more characters put into a single quote, double quote or triple quote. There is no separate char data type in Python. A character is also string of length one. It is represented by str class. As we will be using strings in almost every Python program that we write, one must may pay attention to the following part. Here’s how we use strings in Python: 
  • Using Single Quotes (‘): We can specify strings using single quotes such as ‘Hello Learner’. All white space (i.e. space and tabs) in string are preserved as it is. 
  • Using Double Quotes (”): Strings in double quotes work exactly the same way as strings in single quotes. For example- “What’s your name?” 
  • Using Triple Quotes (”’ or “””): We can specify multi-line strings using triple quotes. We can also use single quotes and double quotes freely within the triple quotes. For example: ‘”This is a multi-line string. Here we also use single and double quotes inside the triple quotes. ‘Hello Learner’. “What’s your name?”, I asked.”‘
  • Strings are immutable: In Python, change or deletion of characters from a string is no allowed. This means that once we have created a string, we cannot change it. Only new strings can be reassigned to the same name. 
  • String literal Concatenation: When we place two string literals side by side, they are automatically concatenated by Python. For example: ‘What\’s’ ‘your name?’ is automatically converted into ‘What’s is your name?’.
  • Escape Sequences:

(a) If we have a string which contains a single quote (‘), then how will we specify this string? For example, this string is What’s your name? We cannot specify it using single quotes because Python will be confused as to whether the string starts and ends, So we will have to specify that this single quotes does not indicate the end of the string. This can be done with the help of what is called an escape sequence (/’). Now, we can specify the string as ‘What\’s your name?’. 

(b) Another way of specifying this specific string would be “What’s your name?” i.e. using double quotes.

(c) What If we want to specify a two-line string? one way is to use a triple quoted string as discussed above or we can use an escape sequence for the new line character -\n to indicate the start of a new line. For example – ‘This is the first line.\n This is the second line’. Another useful escape sequence to know is the tab \t. There are many more escape sequences but these two are very commonly used. 

(d) In a string, a single backslash at the end of the line indicates that the string is continued in the next line, but no new line is added. For example -“This is the first sentences.\ This is the second sentence. ” is equivalent to “This is the first Sentence. This is the second sentence.”

3. List Data type:

List is an ordered sequence of items. It is one of the commonly used data type in Python and is very versatile. A list contains items separated by commas and enclosed with square brackets ([ ]). To some extent, lists are similar to arrays in C. One difference between them is that all the items in a list do not need to be of the same type. Lists are mutable data types, which means the value of elements of a list can be altered. The value stored in a list can be accessed using the slice operator ([ ] or [:]) with indexes starting at 0 in the beginning of the string and working there way form -1 at the end. The plus (+) is the list concatenation operator and the asterisk (*) sign is the repetition operator. Declaring a list is also quite straight forward. Declaring a list is also quite straight forward.

Elements can be added as per our need to the list by using Built-in append () function. We can add only one item at a time to the list by using append () function. To insert more than one element at a time to the List using append () method, Loops are used. 

  • Tuple Data Type: A tuple is an ordered sequence of items same as list. A tuple consists of a number of values separated by commas and enclosed with in parentheses (( )).

For example: Tup = (1,2.2, “Hiii”, 2+3j). The main difference between list and tuples are:

  • Lists are enclosed in brackets ([ ]) and their elements and size can be changed.
  • Tuples are enclosed in parentheses ( ( ) ) and cannot be changed i.e. Tuples are immutable. Tuples can be thought of as read-only lists. 

Tuples are used to write protect data and are usually faster than lists as they cannot change dynamically. We can apply the slicing operators ([ ]) to extract items from a tuple but we cannot change its value. If we do this it will throw an error. 

4. Set Data Type:

Set is an unordered collection of distinct elements. Set is defined by values separated by comma inside braces { }. We can perform operations on two sets like union, intersection. Set contain only unique values. They eliminate duplicate automatically. Since, sets are unordered collections of elements, indexing has no meaning. Hence the slicing operator [] does not work on sets. 

5. Dictionary Data Type:

Dictionary is an unordered collection of Key: Value pairs. Dictionaries are used when we have a huge amount of data. Python dictionaries are a kind of hash table type. They are defined within braces { } with each item being a pair in the form key: value. Key and value can be of any type. The values can be assigned and accessed using square braces ([ ]). We must know the key to retrieve the value. 

1.9.6 Conversion between data types:

Sometimes, we may need to perform conversions between the built-in data types. In Python, we have several built-in functions to perform conversion from one data type to another like int (), float (), str () etc. These functions return a new object representing the converted value. 

Note:

  • Conversion from float to int will truncate the value (make it closer to zero).
  • Conversion to and from string must contain compatible value otherwise Python shows an error. 

1.9.7 Logical and Physical Lines: 

A Physical line is what we see when we write the program. A logical line is what Python says as a single statement. Python implicitly assumes that each physical line corresponds to a logical line. 

An example of a logical line is a statement like print ‘Hello world’ – if this was on a line by itself (as we see it in an editor), then this also corresponds to a physical line. Implicitly, Python encourages the use of a single statement per line, which makes code more readable. If we want to specify more than one logical line on a single physical line, then we have to explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement.

For example:

i = 5

print(i)

is effectively same as

i = 5; print(i);

or even

i = 5; print(i)

1.9.8 Indentation:

Whitespace at the beginning of the line is important in Python. This is called indentation. Leading whitespace (space and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements. This means that statements which go together must have the same indention. Each such set of statements is called a block.

1.9.9 Writing our first program in Python

As we have discussed earlier about Python shell, its command line mode and script mode in detail. We can now use any of these. Here, we are using Python IDLE for writing and executing programs. Traditionally, the first program written in a new language is called Hello World because all it does is displaced the words, Hello World. To display this is string in Python we just need to write a single statement as shown below. 

This is an example of using the print function, which doesn’t actually print anything on paper. It displays a value on this screen. In this case, the result shown is HELLO WORLD. The quotation marks in the program mark the beginning and end of the value; they don’t appear in the result. 

Frequently Asked Questions (FAQs)

Q.1 What is data type in Python?

Ans.1 A data type represents the type of data stored into a variable or memory. The data types which are already available in Python language are called built-in data types. The data types which are created by the programmers are called user-defined data types. Data types are used to define the operations possible on particular kind of data and the storage method for each of them.  

Q.2 What is the purpose of indentation in Python? 

Ans.2 Whitespace at the beginning of the line is important in Python. This is called indentation. Leading whitespace (space and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements. This means that statements which go together must have the same indention.

Q.3 What is Python IDLE? 

Ans.3 IDLE (Integrated Development and Learning Environment) is an IDE for python. IDLE is free, easy to use, portable and automatically available on most platforms. IDLE is a python program that uses the standard library’s tkinter GUI toolkit (also known as Tkinter in 2.6). This makes IDLE portable, but it also means that you will need to have tkinter support in your python to use IDLE. The window version of python has this by default, but some Linux and Unix users may need to install appropriate tkinter support.

IDLE can be used to execute a single just like Python shell and also to create, modify and execute Python scripts. IDLE provides a fully-featured text editor to create Python scripts that includes features like syntax highlighting, auto-completion and smart indent. It also has a debugger with stepping and breakpoints features.

Q.4 Differentiate between Literals and Constants. 

Ans.4 Literals: A literal is a value, such as a number or string that may be assigned to a variable or symbolic constant, used as an operand in an arithmetic or logical operation, or as parameter to a function. For example-the number 5,1.23, or a string like “It’s a string!” all these are referred to as literal constants because there value cannot be changed. A literal always represent itself, nothing else (like the number 5 always represent the quantity of five only). In Python there are various types of literals, they are as follows:

  • Numeric Literals
  • String Literals
  • Boolean Literals
  • Special Literals

Constants: A Constant is a type of variable whose value cannot be changed. Constants act as a container that holds information which can not be changed later.Or we can define constants as constants are symbols/labels that represents literal values that we assign to them.

In reality, we don’t use constants in Python. In python, constants are usually declared and assigned in a module. We generally name constants in all capital letters to separate them from variables; however, it does not actually prevent reassignment.

Q.5 Explain the different string formats available in Python with examples.  

Ans.5 A string is a sequence of characters. A string is basically a collection of one or more characters put into a single quote, double quote or triple quote. There is no separate char data type in Python. A character is also string of length one. It is represented by str class. As we will be using strings in almost every Python program that we write, one must may pay attention to the following part. Here’s how we use strings in Python: 

  • Using Single Quotes (‘): We can specify strings using single quotes such as ‘Hello Learner’. All white space (i.e. space and tabs) in string are preserved as it is. 
  • Using Double Quotes (”): Strings in double quotes work exactly the same way as strings in single quotes. For example- “What’s your name?” 
  • Using Triple Quotes (”’ or “””): We can specify multi-line strings using triple quotes. We can also use single quotes and double quotes freely within the triple quotes. For example: ‘”This is a multi-line string. Here we also use single and double quotes inside the triple quotes. ‘Hello Learner’. “What’s your name?”, I asked.”‘
  • Strings are immutable: In Python, change or deletion of characters from a string is no allowed. This means that once we have created a string, we cannot change it. Only new strings can be reassigned to the same name. 
  • String literal Concatenation: When we place two string literals side by side, they are automatically concatenated by Python. For example: ‘What\’s’ ‘your name?’ is automatically converted into ‘What’s is your name?’.
  • Escape Sequences:

(a) If we have a string which contains a single quote (‘), then how will we specify this string? For example, this string is What’s your name? We cannot specify it using single quotes because Python will be confused as to whether the string starts and ends, So we will have to specify that this single quotes does not indicate the end of the string. This can be done with the help of what is called an escape sequence (/’). Now, we can specify the string as ‘What\’s your name?’. 

(b) Another way of specifying this specific string would be “What’s your name?” i.e. using double quotes.

(c) What If we want to specify a two-line string? one way is to use a triple quoted string as discussed above or we can use an escape sequence for the new line character -\n to indicate the start of a new line. For example – ‘This is the first line.\n This is the second line’. Another useful escape sequence to know is the tab \t. There are many more escape sequences but these two are very commonly used. 

(d) In a string, a single backslash at the end of the line indicates that the string is continued in the next line, but no new line is added. For example -“This is the first sentences.\ This is the second sentence. ” is equivalent to “This is the first Sentence. This is the second sentence.”

Q.6 Explain in detail about Python shell. 

Ans.6 Python is an interpreted language, which means python executes the code line by line. There are two ways to use the interpreter (Python Shell) in Python:

(a) Command-line mode (b) Script mode

(a) Command-line mode: It is used to execute single Python command and get the result. Python Shell waits for an input from the user. As the user enters the input (Command), it executes it and displays the result. To open the Python Shell on Windows, open the command prompt, write Python and press enter. 

(b) Script mode: Script is used to execute multiple statements (also known as python scripts) unlike command line mode which executes a single statement at a time. To execute python scripts, create a Python file with extension.py and write statements in a file which we want to execute.  

Q.7 What is Python? Also list its Features. 

Ans.7 Python is a high level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It frequently uses simple English keywords, where as other languages use punctuations, and it requires fewer syntactical constructions in comparison to other languages. Python allows a programmer to concentrate on the solution to the problem rather than the syntax and structure of the language. We are programming in. 

  • Python is Interpreted. 
  • Python is Interactive. 
  • Python is Object Oriented. 
  • Python is a Beginner’s language. 

There are following features of python:

  • Readable 
  • Easy to learn
  • Cross platform
  • Open source 
  • Large standard library 
  • Free 
  • Supports exception handling
  • Automatic memory management 

Q.8 Write a python program to add two numbers.

Ans.8

Read More: https://digitalcomputereducation.com/generations-of-computer/

Know More: https://youtu.be/0Sxd8AFqOJc

Read more: Introduction to Python Programming

3 thoughts on “Introduction to Python Programming”

  1. Pingback: Computer Viruses -

Leave a Comment