0% found this document useful (0 votes)
15 views

Python Unit1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Unit1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

PYTHON PROGRAMMING

UNIT I
 What is Python?
 Python is an example of a high-level language; other high-level languages you might have
heard of are C++, PHP, and Java.

 Multi-purpose (Web, GUI, Scripting, etc.)

• • Object Oriented

• • Interpreted

• • Strongly typed and Dynamically typed

• • Focus on readability and productivity


• 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 Netherland

 Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, 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 was released in November 1994. In 2000, Python 2.0 was released. Python
 2.7.11 is the latest edition of Python 2.
 • Meanwhile, 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.5.1 is the latest version of Python 3
 Features of python:
 Python's features include-

 • Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a 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

 4 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. A 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.
 Interpreter VS Compiler
 Two kinds of applications process high-level languages into low-level languages:
interpreters and compilers.

 An interpreter reads a high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately reading lines and
performing computations.

 ----------------------------------------------------------------------------------------------------------------------------

 A compiler reads the program and translates it into a low-level program, which can then
be run.
 In this case, the high-level program is called the source code, and the translated
program is called the object code or the executable. Once a program is compiled, you
can execute it repeatedly without further translation.
 Many modern languages use both processes. They are first compiled into a lower
 level language, called byte code, and then interpreted by a program called a virtual
machine. Python uses both processes, but because of the way programmers interact
with it, it is usually considered an interpreted language
 ----------------------------------------------------------------------------------------------------

 There are two ways to use the Python interpreter: shell mode and script mode.
 In shell mode, you type Python statements into the Python shell and the interpreter
immediately prints the result.
 In this course, we will be using an IDE (Integrated Development Environment) called
IDLE. When you first start IDLE it will open an interpreter window.1

 The first few lines identify the version of Python being used as well as a few other
messages; you can safely ignore the lines about the firewall. Next there is a line
identifying the version of IDLE. The last line starts with >>>, which is the Python
prompt. The interpreter uses the prompt to indicate that it is ready for instructions.
 If we type print 1 + 1 the interpreter will reply 2 and give us another prompt.2

 Running Python program:

 There are three different ways to start Python-

 (1) Interactive Interpreter


 You can start Python from Unix, DOS, or any other system that provides you a command line
interpreter or shell window.
 Enter python the command line.

 (2) Script from the Command-line

 (3) Integrated Development Environment


 What is Debugging ?
 Programming is a complex process, and because it is done by human beings, programs
often contain errors. For whimsical reasons, programming errors are called bugs and the
process of tracking them down and correcting them is called debugging.
 Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic
errors. It is useful to distinguish between them in order to track them down more quickly
--------------------------------------------------------------------------------------------------------------------
 Syntax errors
 Python can only execute a program if the program is syntactically correct; otherwise, the
process fails and returns an error message. Syntax refers to the structure of a program
and the rules about that structure. For example, in English, a sentence must begin with a
capital letter and end with a period. this sentence contains a syntax error.
 So does this one For most readers, a few syntax errors are not a significant problem,
which is why we can read the poetry of e. e. cummings without spewing error messages.
Python is not so forgiving. If there is a single syntax error anywhere in your program,
Python will print an error message and quit, and you will not be able to run your
program.
 During the first few weeks of your programming career, you will probably spend a lot of
time tracking down syntax errors. As you gain experience, though, you will make fewer
syntax errors and find them faster.
 Runtime errors
 The second type of error is a runtime error, so called because the error does not appear
until you run the program. These errors are also called exceptions because they usually
indicate that something exceptional (and bad) has happened. Runtime errors are rare in
the simple programs you will see in the first few chapters, so it might be a while before
you encounter one.

 Semantic errors
 The third type of error is the semantic error. If there is a semantic error in your
program, it will run successfully, in the sense that the computer will not generate any
error messages, but it will not do the right thing. It will do something else.
 Specifically, it will do what you told it to do.
 The problem is that the program you wrote is not the program you wanted to write. The
meaning of the program (its semantics) is wrong. Identifying semantic errors can be
tricky because it requires you to work backward by looking at the output of the program
and trying to figure out what it is doing.
 Formal and Natural Languages:
 Natural languages are the languages that people speak, such as English, Spanish, and French. They
were not designed by people (although people try to impose some order on them); they evolved
naturally.
 Formal languages are languages that are designed by people for specific applications. For example, the
notation that mathematicians use is a formal language that is particularly good at denoting relationships
among numbers and symbols.

 Programming languages are formal languages that have been designed to express
computations.

 ----------------------------------------------------------------------------------------------------------------------
 Although formal and natural languages have many features in common—tokens, structure, syntax, and
semantics—there are many differences:
 ambiguity: Natural languages are full of ambiguity, which people deal with by using contextual clues and
other information. Formal languages are designed to be nearly or completely unambiguous, which means
that any statement has exactly one meaning, regardless of context.
 redundancy: In order to make up for ambiguity and reduce misunderstandings, natural languages
employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and
more concise.
 literalness: Natural languages are full of idiom and metaphor. If someone says, “The penny dropped”,
there is probably no penny and nothing dropped. Formal languages mean exactly what they say.
 People who grow up speaking a natural language—everyone—often have a hard time
adjusting to formal languages. In some ways, the difference between formal and natural
language is like the difference between poetry and prose, but more so:
 Poetry: Words are used for their sounds as well as for their meaning, and the whole poem
together creates an effect or emotional response. Ambiguity is not only common but often
deliberate.
 Prose: The literal meaning of words is more important, and the structure contributes
 12 more meaning. Prose is more amenable to analysis than poetry but still often
ambiguous.
 Programs: The meaning of a computer program is unambiguous and literal, and can be
understood entirely by analysis of the tokens and structure.
• The Difference Between Brackets, Braces, and Parentheses:
 Braces are used for different purposes. If you just want a list to contain some elements
and organize them by index numbers (starting from 0), just use the [] and add elements
as necessary. {} are special in that you can give custom id's to values like a = {"John":
14}. Now, instead of making a list with ages and remembering whose age is where, you
can just access John's age by a["John"].
 The [] is called a list and {} is called a dictionary (in Python).
 Dictionaries are basically a convenient form of list which allow you to access data in a
much easier way.
 However, there is a catch to dictionaries. Many times, the data that you put in the
dictionary doesn't stay in the same order as before. Hence, when you go through each
value one by one, it won't be in the order you expect. There is a special dictionary to get
around this, but you have to add this line from collections import OrderedDict and
replace {} with OrderedDict(). But, I don't think you will need to worry about that for
now.
 Variables and Expressions:
 Values and Types:
 A value is one of the fundamental things—like a letter or a number—that a program
manipulates. The values we have seen so far are 2 (the result when we added 1 + 1),
and “Hello, World!”. These values belong to different types: 2 is an integer, and “Hello,
World!” is a string. You (and the interpreter) can identify strings because they are
enclosed in quotation marks.
 The print statement also works for integers.
• Variables:
• One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value. The assignment
statement creates
• new variables and assigns them values:

----------------------------------------------------------------------------------------------------
Programmers generally choose names for their variables that are meaningful—they
document what the variable is used for. Variable names can be arbitrarily long. They can
contain both letters and numbers, but they have to begin with a letter. Although it is legal to
use uppercase letters, by convention we don’t. If you do, remember that case matters.
Bruce and bruce are different variables. The underscore character ( ) can appear in a name.
It is often used in names with multiple words, such as myname or priceofteainchina. If you
give a variable an illegal name, you get a syntax error:
Keywords define the language’s rules and structure, and they cannot be used as
variable names. Python has thirty-one keywords:
• Type conversion:
 Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type-name as a function.

 There are several built-in functions to perform conversion from one data type to another.
• Operators and Operands:
• Operators are special symbols that represent computations like addition and
multiplication. The values the operator uses are called operands. The following are all
legal Python expressions whose meaning is more or less clear:
• A+B here A and B are operands and + is operator
• --------------------------------------------------------------------------------------------------
• Expressions:
• An expression is a combination of values, variables, and operators. If you type an
expression on the command line, the interpreter evaluates it and displays the result:

The evaluation of an expression produces a value, which is why expressions can appear
on the right hand side of assignment statements. A value all by itself is a simple
expression, and so is a variable.
• Interactive Mode and ScriptMode:
 Interactive Mode Programming
 Invoking the interpreter without passing a script file as a parameter brings up the
following prompt-
• Script Mode Programming
• Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no
longer active.
• Let us write a simple Python program in a script. Python files have the extension.py. Type
the following source code in a test.py file-

Hello, Python!
 Order of Operations:
 When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence. Python follows the same precedence rules for its mathematical operators
that mathematics does. The acronym PEMDAS is a useful way to remember the order of
operations:
 1. Parentheses have the highest precedence and can be used to force an expression to evaluate
in the order you want. Since expressions in parentheses are evaluated first, 2*(3-1) is 4, and
(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in
(minute*100)/60, even though it doesn’t change the result.
 2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3
and not 27.
 3. Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1
is -1, not 1 (remember that in integer division, 2/3=0).
 Operators with the same precedence are evaluated from left to right. So in the expression
minute*100/60, the multiplication happens first, yielding 5900/60, which in turn yields 98. If
the operations had been evaluated from right to left, the result would have been 59*1, which is
59, which is wrong. Similarly, in evaluating 17-4-3,
 22
 17-4 is evaluated first.
 If in doubt, use parentheses.
• Conditional Statements:
• . IF statement:
• The IF statement is similar to that of other languages. The if statement contains a
logical expression using which the data is compared and a decision is made based
on the result of the comparison.

• Syntax:
• if expression: statement(s)

• If the boolean expression evaluates to TRUE, then the block of statement(s) inside
the if statement is executed. In Python, statements in a block are uniformly
indented after the : symbol. If boolean expression evaluates to FALSE, then the first
set of code after the end of block is executed.
• nested if statements You can use one if or else if statement inside another
if or else if statement(s).
• Guess the output?
• 3 is a positive number. This is always printed.
• ---------------------------------------------------------------------------------------------------
• IF ELSE Statements:
• An else statement can be combined with an if statement.
• An else statement contains a block of code that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
• The else statement is an optional statement and there could be at the most only one else statement
following if.
• Syntax
• The syntax of the if...else statement is
• if expression:
• statement(s)
• else: statement(s)
• Nested IF -ELSE Statements:
• There may be a situation when you want to check for another condition after a condition
resolves to true. In such a situation, you can use the nested if construct. In a nested if
construct, you can have an if...elif...else construct inside another if...elif...else construct.
• Syntax The syntax of the nested if...elif...else construct may be
• if expression1:
• statement(s)
• if expression2:
• statement(s)
• elif expression3:
• statement(s)
• else:
• statement(s)
• elif expression4:
• statement(s)
• else: statement(s)
• Output 1
• Enter a number: 5
• Positive number
• Output 2
• Enter a number: -1
• Negative number
• Output 3
• Enter a number: 0
• Zero Divisible by 3 and 2
• enter number5
• not Divisible by 2 not divisible by 3
• Looping:
• For:
• The for loop in Python is used to iterate over a sequence (list, tuple,
string) or other iterable objects. Iterating over a sequence is called
traversal.

• Syntax of for Loop:

• for val in sequence:


• Body of for

• Note :Here, val is the variable that takes the value of the item inside the sequence on each
iteration. Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
• Example: Python for Loop

• # Program to find the sum of all numbers stored in a list


• # List of numbers
• numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
• # variable to store the sum
• sum = 0
• # iterate over the list
• sum = sum+val
• # Output: The sum is 48
• print("The sum is", sum)
• for val in numbers:

• when you run the program, the output will be: The sum is 48
• 2. While Loop
• The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true. We generally use this loop when we don't know
beforehand, the number of times to iterate.
• -----------------------------------------------------------------
• Syntax of while Loop in Python
• while test_expression:
• Body of while
• --------------------------------------------------------------
• Note: In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False.
• In Python, the body of the while loop is determined through indentation. Body starts with
indentation and the first unindented line marks the end. Python interprets any non-zero
value as True. None and 0 are interpreted as False.
• Example: Python while Loop
• # Program to add natural
• # numbers upto
• # sum = 1+2+3+...+n
• #To take input from the user,
• n = int(input("Enter n: ")) n = 10
• # initialize sum and counter
• sum = 0
• i=1
• while i <= n:
• sum = sum + I
• i = i+1
• # update counter
• # print the sum
• print("The sum is", sum) output: Enter n: 10
• The sum is 55
• 3. Nested loops:
• Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
• Python Nested if Example
• # In this program, we input a number
• # check if the number is positive or
• # negative or zero and display
• # an appropriate message
• # This time we use nested if
• num = float(input("Enter a number: "))
• if num >= 0:
• if num == 0:
• print("Zero")
• else:
• print("Positive number")
• else:
• print("Negative number")

• Special note: while using nested if else statement make sure inner block has proper
indentation prior to outer block .
• Control statements:
• 1. Terminating loops:
• The break statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.

• If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.

• Syntax of break
• break
• 2. Skipping specific conditions:
• The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.
• Syntax of Continue
• continue
• --------------------------------------------------------------------------------------------------------
• Example: # Program to show the use of continue statement inside loops
• for val in "string":
• if val == "i":
• continue
• print(val) print("The end")
• Output :
• s
• t
• r
• n
• g
• The end
 This program is same as the above example except the break statement has been
replaced with continue. We continue with the loop, if the string is "i", not executing the
rest of the block. Hence, we see in our output that all the letters except "i" gets printed.

 NOTE: while performing practicals keep proper indentation in between program


For better experience use editiors like jyupiter notebook or anaconda navigator .

You might also like