0% found this document useful (0 votes)
3 views11 pages

Python Material 1

The document provides an introduction to Python programming, detailing its history, features, and applications. It emphasizes Python's ease of use, readability, and versatility for various programming tasks, including GUI applications and web development. Additionally, it covers basic concepts such as keywords, identifiers, statements, indentation, comments, and input/output operations in Python.

Uploaded by

wipahib114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Python Material 1

The document provides an introduction to Python programming, detailing its history, features, and applications. It emphasizes Python's ease of use, readability, and versatility for various programming tasks, including GUI applications and web development. Additionally, it covers basic concepts such as keywords, identifiers, statements, indentation, comments, and input/output operations in Python.

Uploaded by

wipahib114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

PYTHON PROGRAMMING

UNIT – I:
Introduction:

History of Python:

 Python was developed by Guido van Rossum 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,
SmallTalk, 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.

Need of Python Programming:

If you’re a professional software developer, you may have to work with several C/C++/Java
libraries but find the usual write/compile/test/re-compile cycle is too slow. Perhaps you’re writing
a test suite for such a library and find writing the testing code a tedious task. Or maybe you’ve
written a program that could use an extension language, and you don’t want to design and
implement a whole new language for your application.

Python is just the language for you.

You could write a Unix shell script or Windows batch files for some of these tasks, but shell
scripts are best at moving around files and changing text data, not well-suited for GUI applications
or games. You could write a C/C++/Java program, but it can take a lot of development time to get
even a first-draft program. Python is simpler to use, available on Windows, Mac OS X, and Unix
operating systems, and will help you get the job done more quickly.

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is


designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.

1|Page
 Python is Interpreted: Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

Python's features include:

 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh,
and the X window system of Unix.
 Scalable: Python provides a better structure and support for large programs than shell
scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed
below:

 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 supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Applications:

 Simple text processing to WWW browsers to games.

1. 3D CAD/CAM
2. Audio/Video Applications
3. Console Applications
4. Enterprise Applications
5. File Formats
6. Image Applications
2|Page
7. Internet Applications
8. Mobile Applications
9. Office Applications
10. Personal Information Managers
11. Science and Education Applications
12. Software Development
13. System Administration Applications
14. X-Window Manager

Basics of Python Programming Using the REPL (Shell):

REPL stands for Read-Evaluate-Print-Loop is a simple, interactive computer programming


environment that takes single user inputs (i.e. single expressions), evaluates them, and returns the
result to the user.

Python Shell:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on
win32

Type "copyright", "credits" or "license ()" for more information.

>>> a = 10 # reading a value


>>>b = 20 # reading a value
>>> a + b # reading single user input and evaluates them
30 # returns the result
>>>

Running Python Scripts:

To run the python scripts the following are the steps to be followed:

Step1: Open IDLE (Python Shell)

Step2: Select File->New


File and type the following script, save with example1.py
3|Page
Step3: Select Menu Run->Run Module

Step4: The output after executing the python script – example1.py

Python Keywords
and Identifiers:
4|Page
Python keywords are reserved words and identifiers are names given to variables, functions etc.

Python Keywords:

 Keywords are the reserved words in Python.


 We cannot use a keyword as variable name, function name or any other identifier. They are
used to define the syntax and structure of the Python language.
 In Python, keywords are case sensitive.
 There are 33 keywords in Python 3.3. This number can vary slightly in course of time.
 All the keywords except True, False and None are in lowercase and they must be written as
it is.

The list of all the keywords is given below.

Keywords in Python programming language


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

If you want to have an overview, here is the complete list of all the keywords with examples.

Python Identifiers:

Identifier is the name given to entities like class, functions, variables etc. in Python. It helps
differentiating one entity from another.

Rules for writing identifiers

1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore (_).
2. Names like myClass, var_1 and print this_to_screen, all are valid example._
3. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly
fine.
4. Keywords cannot be used as identifiers.

5|Page
5. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
6. Identifier can be of any length.

Things to care about:

 Python is a case-sensitive language. This means, Variable and variable are not the same.
Always name identifiers make that sense.
 While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier to
figure out what it does even when you look at your code after a long gap.
 Multiple words can be separated using an underscore, this_is_a_long_variable.
 We can also use camel-case style of writing, i.e., capitalize every first letter of the word
except the initial word without any spaces. For example: camelCaseExample

Python Statement, Indentation and Comments

Python Statement:

Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an
assignment statement. if statement, for statement, while statement etc. are other kinds of
statements which will be discussed later.

Multi-line statement:

In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\).

For example:

This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as

6|Page
Here, the surrounding parentheses ( ) do the line continuation implicitly.

We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; c = 3

Python Indentation:

 Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
 A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line.
 The amount of indentation is up to you, but it must be consistent throughout that block.
 Generally four whitespaces are used for indentation and is preferred over tabs.

Here is an example.

 The enforcement of indentation in Python makes the code look neat and clean. This results
into Python programs that look similar and consistent.
 Indentation can be ignored in line continuation. But it's a good idea to always indent. It
makes the code more readable.

For example:
if True:
print('Hello')
a = 5
and if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer.

 Incorrect indentation will result into IndentationError.

Python Comments:

 Comments are very important while writing a program. It describes what's going on inside
a program so that a person looking at the source code does not have a hard time figuring it

7|Page
out. You might forget the key details of the program you just wrote in a month's time. So
taking time to explain these concepts in form of comments is always fruitful.
 In Python, we use the hash (#) symbol to start writing a comment.
 It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.

#This is a comment
#print out Hello
print('Hello')

Multi-line comments:

If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line.

For example:
#This is a long comment
#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used as multi-line
comment as well. Unless they are not docstrings, they do not generate any extra code.

Docstring in Python

 Docstring is short for documentation string.


 It is a string that occurs as the first statement in a module, function, class, or method
definition. We must write what a function/class does in the docstring.
 Triple quotes are used while writing docstrings.

For example:

def double(num):
"""Function to double the value"""
return 2*num
Docstring is available to us as the attribute __doc__ of the function. Issue the following code in
shell once you run the above program.
>>> print(double.__doc__)
Function to double the value
Python Input, Output

Python provides numerous built-in functions that are readily available to us at the Python prompt.

Some of the functions like input() and print() are widely used for standard input and output
operations respectively. Let us see the output section first.

Python Output Using print() function:

 We use the print() function to output data to the standard output device (screen).
 We can also output data to a file, but this will be discussed later.

8|Page
 In the second print() statement, we can notice that a space was added between the string
and the value of variable a. This is by default, but we can change it.

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

 Here, objects are the value(s) to be printed.


 The sep separator is used between the values. It defaults into a space
character.
 After all values are printed, end is printed. It defaults into a new line.
 The file is the object where the values are printed and its default value is
sys.stdout (screen).

Here are the examples to illustrate this:

Output formatting:

Sometimes we would like to format our output to make it look attractive. This can be done
by using the str.format() method. This method is visible to any string object.

9|Page
Here the curly braces {} are used as placeholders. We can specify the order in which it is printed
by using numbers (tuple index).

 We can even use keyword arguments to format the string.

 We can also use format string like % operator.

Python Input:

10 | P a g e
 Up till now, our programs were static. The value of variables were defined or hard coded
into the source code.
 To allow flexibility we might want to take the input from the user. In Python, we have the
input() function to allow this.
The syntax for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.

Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.

This same operation can be performed using the eval() function. But it takes it further. It
can evaluate even expressions, provided the input is a string.

11 | P a g e

You might also like