0% found this document useful (0 votes)
101 views54 pages

Chapter 1 Python

The document provides an overview of installing and using Python. It discusses: 1) How to download and install Python on Windows and Linux, including using packages or PPAs. 2) Using the interactive interpreter either through the command line or IDLE. Basic commands like print are demonstrated. 3) Creating and running Python files in script mode, and viewing outputs in the shell window or files. Variables in Python are declared by assigning a value, unlike other languages where the type must be specified.

Uploaded by

Amit Mamgai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
101 views54 pages

Chapter 1 Python

The document provides an overview of installing and using Python. It discusses: 1) How to download and install Python on Windows and Linux, including using packages or PPAs. 2) Using the interactive interpreter either through the command line or IDLE. Basic commands like print are demonstrated. 3) Creating and running Python files in script mode, and viewing outputs in the shell window or files. Variables in Python are declared by assigning a value, unlike other languages where the type must be specified.

Uploaded by

Amit Mamgai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

Chapter - 1

Basics of Python Programming


What is Python

Python is a powerful modern computer programming language. It bears some similarities to


Fortran, one of the earliest programming languages, but it is much more powerful than
Fortran. Python allows you to use variables without declaring them (i.e., it determines types
implicitly), and it relies on indentation as a control structure. You are not forced to define
classes in Python (unlike Java) but you are free to do so when convenient.

Python was developed by Guido van Rossum, and it is free software. Free as in “free cola,” in
that you can obtain Python without spending any money. But Python is also free in other
important ways, for example you are free to copy it as many times as you like, and free to
study the source code, and make changes to it. There is a worldwide movement behind the
idea of free software, initiated in 1983 by Richard Stallman.

Installing Python

Before you can start programming, you need some new software. What follows is a short
description of how to download and install Python. If you want to jump into the installation
process without detailed guidance, you can simply visit http://www.python.org/download to
get the most recent version of Python.

Windows

To install Python on a Windows machine, follow these steps:

1. Open a web browser and go to http://www.python.org.


2. Click on the download and download the Python 3.6.5 for windows.
3. Click on the file python-3.6.5 which is in the download folder of your system.
4. Click on install now.

5. Close when setup was complete.


Install Python: Linux

how to install Python 3.6 on Ubuntu Linux machines.

To see which version of Python 3 you have installed, open a command prompt and run

$ python3 --version

If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the
following commands:

$ sudo apt-get update

$ sudo apt-get install python3.6

If you‟re using another version of Ubuntu (e.g. the latest LTS release), we recommend using
the deadsnakes PPA to install Python 3.6:

$ sudo apt-get install software-properties-common

$ sudo add-apt-repository ppa:deadsnakes/ppa

$ sudo apt-get update

$ sudo apt-get install python3.6

If you are using other Linux distribution, chances are you already have Python 3 pre-installed
as well. If not, use your distribution‟s package manager. For example on Fedora, you would
use dnf:

$ sudo dnf install python3


Note that if the version of the python3 package is not recent enough for you, there may be
ways of installing more recent versions as well, depending on you distribution. For example
installing the python36 package on Fedora 25 to get Python 3.6. If you are a Fedora user, you
might want to read about multiple Python versions available in Fedora.

The Interactive Interpreter

Python is a flexible and dynamic language that you can use in different ways. You can use it
interactively when you simply want to test a code or a statement on a line-by-line basis or
when you‟re exploring its features. You can use it in script mode when you want to interpret
an entire file of statements or application program.

To use Python interactively, you can use either the Command Line window or the IDLE
Development Environment.

Command Line Interaction

The command line is the most straightforward way to work with Python. You can easily
visualize how Python works as it responds to every completed command entered on the >>>
prompt. It may not be the most preferred interaction with Python, but it is the simplest way
to explore how Python works. When you start up Python IDLE(Python 3.6 32-bit) you get a
prompt similar to the following:
There are different ways to access Python‟s command line depending on the operating system
installed on your machine:

 If you‟re using Windows, you can start the Python command line by clicking on its icon
or menu item on the Start menu.
 You may also go to the folder containing the shortcut or the installed files and click on
the Python command line.
 If you‟re using GNU/Linux, UNIX, and Mac OS systems, you have to run the Terminal
Tool and enter the Python command to start your session.

We use commands to tell the computer what to do. When you want Python to do something
for you, you have to instruct it by entering commands that it is familiar with. Python will then
translate these commands to instructions that your computer or device can understand and
execute.

To see how Python works, you can use the print command to print the universal program

“Hello Class”

1. Open Python‟s command line.

2. At the >>>prompt, type the following: print(“Hello Class”)print is use to print anything on
the console.

3. Press enter to tell Python that you‟re done with your command. Very quickly, the
command line window will display Hello Class on the following line:
Python responded correctly because you gave it a command in a format that it requires. To
see how it responds when you ask it to print the same string using a wrong syntax for the print
command, type and enter the following command on the Python command prompt:

Print(“Hello Class”)

This is how Python will respond:

Syntax error: invalid syntax

You‟ll get syntax error messages whenever you enter invalid or incomplete statements. In his
case, you typed print with a capital letter which is a big no to a case-sensitive language like
Python.

If you‟re just using Python interactively, you can do away with the print command entirely by
just typing your statement within quotes such as “Hello, World!”

For exiting from IDLE(Python 3.6 32-bit) you just simply type

exit()

quit()

or Ctrl + Z then press enter on >>> prompt


IDLE: Python’s Integrated Development Environment (IDE)

The IDLE (Integrated Development and Learning Environment) tool is included in Python‟s
installation package but you can choose to download more sophisticated third party IDEs.

The IDLE tool offers a more efficient platform to write your code and work interactively with
Python. You can access IDLE on the same folder where you found the command line icon or on
the start menu. As soon as you click on the IDLE icon, it will take you to the Python Shell
window.

The Python Shell Window

The Python Shell Window has dropdown menus and a >>>prompt that you have seen earlier in
the command line window. Here you can type and enter statements or expressions for
evaluation in the same way that you used the command line earlier. This time however,
IDLE‟s editing menu allows you to scroll back to your previous commands, cut, copy, and
paste previous statements and make modifications. IDLE is quite a leap from the command
line interaction.
The Python Shell window has the following menu items: File, Edit, Shell, Debug, Options,
Windows, and Help. The Shell and Debug menus provide capabilities you would find useful
when creating larger programs.

The Shell menu allows you to restart the shell or search the shell‟s log to find the most recent
reset.

The Debug Menu has useful menu items for tracing the source file of an exception and
highlighting the erring line. The Debugger option will usher in an interactive debugger window
that will allow you to step through the running program. The Stack Viewer option displays the
current Python stack through a new window.

The Options window allows you to configure IDLE to suit your Python working preferences.
The Help option opens Python Help and documentation.

The File Window

The items on the File menu allows you to create a new file, open an old file, open a module,
and/or save your session.

When you click on the „New File‟ option, you will be taken to a new window, a simple and
standard text editor where you can type or edit your code.
Initially, this file window is named „untitled‟ but its name will soon change as you save your
code.

The File window‟s menu bar varies only slightly with the Shell Window. It doesn‟t have the
„Shell‟ and „Debug‟ menu found in the Shell Window but it introduces two new menus: the
Run and the Format menu.

When you choose to Run your code on the file window, you can see the output on the Shell
Window.

The output will be shown on the shell window of python


The Script Mode

When working in script mode, you won‟t automatically see results the way you would in
interactive mood. To see an output from a script, you‟ll have to run the script and/or invoke
the print() function within your code.

First you have to create a file like we have created with the same print function which we
have run on the command line. Then save the file with .py extension and click on run -> run
module or just press F5 to run the program then the control will be transfer to the python
3.6.5 shell and output will be displayed.

Variables

A variable is like a container that stores values that you can access or change. It is a way of
pointing to a memory location used by a program. You can use variables to instruct the
computer to save or retrieve data to and from this memory location.

Python differs significantly from languages such as Java, C, or C++ when it comes to dealing
with variables. Other languages declare and bind a variable to a specific data type. This
means that it can only store a unique data type. Hence, if a variable is of integer type, you
can only save integers in that variable when running your program.

Python is a lot more flexible when it comes to handling variables. If you need a variable,
you‟ll just think of a name and declare it by assigning a value. If you need to, you can change
the value and data type that the variable stores during program execution.

To illustrate these features:

In Python, you declare a variable by giving it a value:

my_variable = 10

Take note that when you are declaring a variable, you are not stating that the variable
my_variable is equal to 10. What the statement actually means is “my_variable is set to 10”.

To increase the value of the variable, you can enter this statement on the command line:

>>>my_variable = my_variable + 10

To see how Python responded to your statement, invoke the print command with this

statement:

>>>print(my_variable)

You‟ll see this result on the next line:

20

To use my_varibale to store a literal string “yellow” which is already be declared as integer
but we can also change the data type just to de, you‟ll simply set the variable to “yellow”:

>>>my_variable = “yellow”

To see what‟s currently store in my_variable, use the print command:

>>>print(my_variable)

On the next line, you‟ll see:

Yellow
Data Types

Python recognizes several different types of data. It has four built-in numeric data types.
Python 3 supports three types: integer, floating-point numbers, and complex numbers. Long
integers („long‟) no longer form a separate group of integers but are included in the „int‟ or
integer category. Integers is use to store the real numbers or whole numbers like 23 and −75.
While 5.0 and −23.09 are floats or floating point numbers use to store rational number or
decimal numbers. The type float is (roughly) the same as a real number in mathematics.
Python can readily tell one data type from another when you write and run your statement.

1. Number
Number data type stores Numerical Values. This data type is immutable i.e. value of its
object cannot be changed (we will talk about this aspect later). These are of three different
types:

1. Integer(int)

2. Floating point number

3. Complex number

1.1 Integer (int)

Integers are whole numbers without decimal point. They can be positive or negative as long
as they don‟t contain a decimal point that would make a number a floating number, a distinct
numeric type. While writing a large integer value, don‟t use commas to separate digits. Also
integers should not have leading zeros. When we are working with integers, we need not to
worry about the size of integer as a very big integer value is automatically handled by Python.

>> a=5

>> b=654321

>>type(b)

<type ‘int’>

Integer has binary, octal, decimal and hexadecimal representation in integer data type
number. Python interprets a sequence of decimal digits without any prefix to be a decimal
number.

>>>

>>> print(10)

10
The following strings can be prepended to an integer value to indicate a base other than 10:

Prefix Interpretation Base


0b (zero + lowercase letter 'b') Binary 2
0B (zero + uppercase letter 'B')
0o (zero + lowercase letter 'o') Octal 8
0O (zero + uppercase letter 'O')
0x (zero + lowercase letter 'x') Hexadecimal 16
0X (zero + uppercase letter 'X')
For example:

>>> print(0o10)

>>> print(0x10)

16

>>> print(0b10)

Boolean

Comparisons in Python can only generate one of two possible responses: True or False. These
data types are called Booleans. To illustrate, you can create several variables to store
Boolean values and print the result.

Example

>>> boolean = True

>>> type(boolean)

<type 'bool'>
>>>boolean_1=4==3*2

>>>boolean_2=10>2*2**3

>>>boolean_3=4==8/2

>>>print(boolean_1)

False

>>>print(boolean_2)

False

>>>print(boolean_3)

True

1.2 Floating-point numbers

Also known as floats, floating-point numbers signify real numbers. Floats are written with a
decimal point that segregates the integer from the fractional numbers.

>>>6.5

6.5
They may also be written in scientific notation where the uppercase or lowercase letter „e‟
signifies the 10th power:

>>>6.2e2

620.0

>>>6.2e3

6200.0

1.3 Complex numbers

Complex numbers are pairs of real and imaginary numbers. The syntax of complex method is
complex(real, imaginary). They take the form „a + bJ‟ where „a‟ is a float and the real part of
the complex number. On the other side is bJ where „b‟ is a float and J or its lowercase
indicates the square root of an imaginary number, -1. This makes „b‟ the imaginary part of
the complex number.

>>2j -4

(-4+2j)

>> type(2j -4)

<class „complex‟>
2. None

This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None.

3. Sequence

A sequence is an ordered collection of items, indexed by positive integers. It is combination


of mutable and non mutable data types. Three types of sequence data type available in
Python are Strings, Lists & Tuples.

3.2 String

String is an ordered sequence of letters/characters. They are enclosed in single quotes („ „) or


double (“ “). The quotes are not part of string. They only tell the computer where the string
constant begins and ends. They can have any character or sign, including space in them.
These are immutable data types. We will learn about immutable data types while dealing
with third aspect of object i.e. value of object.

Example

>>> a = “Hello Class”

A string with length 1 represents a character in Python. Conversion from one type to another
If we are not sure, what is the data type of a value, Python interpreter can tell us:

>>>”Hello Class”

„Hello Class‟

>>>‟Hello Class‟

„Hello Class‟

>>> type (“Hello Class”)

<type „str’>
>>> type („Hello Class‟)

<type „str’>

It is possible to change one type of value/ variable to another type. It is known as type
conversion or type casting. The conversion can be done explicitly (programmer specifies the
conversions) or implicitly (Interpreter automatically converts the data type).

For explicit type casting, we use functions (constructors):

int ()

float ()

str ()

bool ()

Example

>>> a= 12.34

>>> b= int(a)

>>> print b

12
Example

>>>a=25

>>>y=float(a)

>>>print y

25.0

A string is a sequence of Unicode characters that may be a combination of letters, numbers,


and special symbols. To define a string in Python, you can enclose the string in matching
single or double quotes:
If a literal string enclosed in single quotes contains a single quote, you‟ll have to place a
backslash (\) before the single quote within the string to escape the character. You‟ll have to
place a backslash before a double quote if your string is enclosed in double quotes:

>>>txt = “He said: \“You should get the same results no matter how you choose to enclose a
string.\””

The output will He said: “You should get the same results no matter how you choose to
enclose a string.”

Strings may be indexed or subscripted. In Python, indexing starts from 0 (zero) instead of 1.
Hence, a string‟s first character has a zero index.

To illustrate how string indexing works in Python, define the string “Hello Python” on the
command line:

>>>s = “Hello Students”

This is how Python would index the string:

-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1


H e l l o S t u d e n t s
0 1 2 3 4 5 6 7 8 9 10 11 12 13
To access the first character on the string you just created, type and enter the variable name
s and the index 0 within square brackets. Accessing the first character is easy because you
know that its index number is zero. You do not have this advantage when you want to access
the last character on the string. To access the last character, you can use this expression
s(len(s)-1).

The expression introduces you to the len() function. That is actually an easier way to access
the last item on the string. Besides indexing, you can use other functions and mathematical
operators on a string.

3.2 Lists

List is also a sequence of values of any type. Values in the list are called elements / items.
These are mutable and indexed/ordered. List is enclosed in square brackets.

Example

l = [„spam‟, 20.5,5]

3.3 Tuples

Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable. Tuples are enclosed in (). We have already seen a tuple, in Example 2 (4, 2).

4. Sets

Set is an unordered collection of values, of any type, with no duplicate entry. Sets are
immutable.

Example

s = set ([1,2,34])
5. Mapping

This data type is unordered and mutable. Dictionaries fall under Mappings.

5.1 Dictionaries

Directory can store any number of python objects. What they store is a key – value pairs,
which are accessed using key. Dictionary is enclosed in curly brackets.

Example

d = {1:'a',2:'b',3:'c'}

Python Basic Operators

Python operators allow programmers to manipulate data or operands. Here are the types of
operators supported by Python:

Arithmetic Operators
Assignment Operators
Relational or Comparison Operators
Logical Operators
Identity Operators
Bitwise Operators
Membership Operators

Arithmetic Operators

Python does a good job of processing mathematical expressions with its basic arithmetic
operators. You can easily make programs to automate tasks such as computing tax, tips,
discounts, or rent.

Operator Name Function


+ Addition adds the value of the left and right operands
- Subtraction subtracts the value of the right operand from the value of the left
operand
* Multiplication multiplies the value of the left and right operand
/ Division divides the value of the left operand by the right operand
** Exponent performs exponential calculation
% Modulus returns the remainder after dividing the left operand with the right
operand
// Floor Division division of operands where the solution is a quotient left after removing
decimal numbers

Addition, subtraction, multiplication, and division are the most basic operators and are
invoked by entering the following expressions:
Example

Addition operator is use to add two numbers like a+b.

>>> 1+2

Subtraction operator is use subtract two numbers like a-b.

>>>2-1

Multiplication operator is use to multiply two numbers like a*b.

>>> 2*1

Division operator is use to divide two numbers like a/b.

>>>2/1

2.0

Exponent operator is use to calculate power of a number like a**b we have to calculate power
of a exponent b.

>>>2**2

Modules operator is use to find the remainder like a%b. The result of modules is remainder
after dividing a by b.

>>>7%3

1
Example

Using Basic Operators to compute simple interest and principal amount on your account

To put your knowledge of variables, data types, and operators to good use, you can design a
simple program that will compute the simple interest and principal amount of account.

Principal Amount 10000

Rate of interest 10%

Time 5 years

First, set up a variable principal amount:

principal_amount =10000

Next, set up the rate_of_interest and time variables. Assign variable the decimal value of the
percentages given. You can do this by using 100 as divisor.

rate_of_interest =10/100

time=5

Your interest is based on principal amount and the rate of interest so you need to get the
interest amount of the principal for a fixed time period. One way to do this is by simply
creating a new variable to store the interest amount of the principal: interest =
principal_amount * rate_of_interest * time
Now that you have reassigned principal amount after computing simple interest. You can use
the same variable to store principal amount value: principal_amount = principal_amount +
interest.

Here‟s your code to compute for the total principal amount:

If you‟re using the file editor in IDLE, you can save the file in a filename of your choice and
Python automatically appends the .py extension. As you may have noticed, the file editor will
always prompt you to save your file before it does anything about your code.

Just like when naming other data files and types, you should use a filename that‟s descriptive
of the file. In this case, a filename like simple interest should do the trick. To get the total
amount, go to the Python Shell and type total:

Now you have Interest Amount= 5000.0

And Principal Amount after 5 Years = 15000.0


If you‟re using the line command window, you can simply enter the above code on a per line
basis.

This simple program shows how straightforward Python programming is and how useful it
could be in automating tasks. Next time you eat out, you can reuse the program by simply
changing the figures on your bill calculator. Think forward and visualize how convenient it
could be if you could put your code in a bigger program that will simply ask you to input the
bill amount instead of accessing the original code. You can do that with Python.

Example

Let us take another example using arithmetic operator

The output of the this program is 0.33333335 because first we have to the brackets like (40-
12) the answer is 28 then (3*4) result is 12 then 28 / 12 have to solve the result is 2.3333335
and at last modules 2 have to solve and final result is 0.3333335.
Assignment Operators

These operators are useful when assigning values to variables:

Operators Function
= assigns the value of the right operand to the left operand
+= add and adds the value of the right and left operand and assigns the total to the
left operand
-= subtract and deducts the value of the right operand from the value of the left
operand and assigns the new value to the left operand
*= multiply and multiplies the left and right operand and assigns the product to the
left operand
/= divide and divides the left operand with the value of the right operand and
assigns the quotient to the left operand
** = exponent performs exponential operation on the left operand and assigns the
result to the left operand
// = floor division and performs floor division on the left operand and assigns the
result to the left operand

Examples:

Assignment operator is use to assign value to any variable or any container. Left side of
assignment operator is container and right of the operator is content.

>>>a=10

>>>print(a)

10
Addition and assign operator a+=10 can be rewrite like a=a+10. This operator is use to add
and store the result into that variable itself like whatever the last value a have that value will
be added by 10.The pervious value of a is 10 and after a+=10 is 20.

>>>a+=10

>>>print(a)

20

Subtract and assign operator a-=10 can be rewrite like a=a-10. This operator is use to subtract
and store the result into that variable itself like whatever the last value a have that value will
be subtract by 10.The pervious value of a is 20 and after a-=10 is 10.

>>>a-=10

>>>print(a)

10

Multiplication and assign operator a*=2 can be rewrite like a=a*2. This operator is use to
multiplication and store the result into that variable itself like whatever the last value a have
that value will be multiplication by 2.The pervious value of a is 10 and after a*=2 is 20.

>>>a*=2

>>>print(a)

20

Division and assign operator a*=2 can be rewrite like a=a*2. This operator is use to division
and store the result into that variable itself like whatever the last value a have that value will
be divide by 2.The pervious value of a is 20 and after a/=2 is 10.

>>>a/=2

>>>print(a)

10

Exponent and assign operator a**=2 can be rewrite like a=a**2. This operator is use to
calculate the power and store the result into that variable itself like whatever the last value
a have that value will be exponent by 2.The pervious value of a is 10 and after a**=2 is 100.0.

>>>a**=2

>>>print(a)

100.0
Floor division and assign operator a//=2 can be rewrite like a=a//2. This operator is use to
division get the floor value and store the result into that variable itself like whatever the last
value a have that value will be divide by 2.The pervious value of a is 100 and after dividing
100 by 2 the result is 33.333333. but in this operator the result is 33.0 because it takes the
floor value if the result. Floor value means the lower side value of any fractional value like if
normal case if we divide 10/4 the result will be 2.5 and if we say we have to take the sealing
value the result will be 3.0 because the sealing value is the upper side value of any fractional
number but when we talk about floor value it will be the lower side value so the result will be
33.0 not 33.3333335 instead of normal division.

>>>a//=2

>>>print(a)

33.0

Relational or Comparison Operators

Relational operators evaluate values on the left and right side of the operator and return the
relation as either True or False. Here are the relational operators in Python:

Operator Meaning
== is equal to
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
!= is not equal to
Examples:

Logical Operators

Python supports 3 logical operators: or, and & not

These operates are use to compare the statements like (x>y) and/or (y<x). The result of and
is depend on both the statement if both of the statements are true then the result is true if
any of the statement is false the result is a false. The result of or is depend on both of the
statement if both the statements are false then the result is false if any of the statement is
true the result is a true. Examples:

Precedence of Python Operators

Python operators are evaluated according to a set order or priority:

Description Operators
1 Exponentiation **
2 Complement, unary plus, and minus ~, +, -
3 Multiplication, division, modulo, and floor division *, /, %, //
4 addition and subtraction + -
5 Right and left bitwise shift >>, <<
6 Bitwise „AND‟ &
7 Regular `OR‟ and Bitwise exclusive „OR‟ |, ^
8 Comparison operators <= < > >=
9 Equality operators == !=
10 Assignment operators =, +=, -=, *-, /=, %= //= **=
11 Identity operators is, is not
12 Membership operators in, not in
13 Logical operators or, and, not

Input output Statements

Input statment

Programs usually require input that can come from different sources: keyboard, mouse clicks,
database, another computer‟s storage, or the internet. Since the keyboard is the most
common way to gather input, Python provided its users the input() function. This function has
an optional parameter called the prompt string. Once the input function is called, the prompt
string will be displayed on the screen and the program flow stops until the user has entered
an input. The input is then interpreted and the input() function returns the user‟s input as a
string and it stores in the variable which is assigned with the assignment operator.

Syntax of input() is:

Container_variable =input(“ statement”)

Name=input(“Enter your name”)

To illustrate, here is a sample program that collects keyboard input for name and age:

Output statement

Print evaluates the expression before printing it on the monitor. Print statement outputs an
entire (complete) line and then goes to next line for subsequent output (s). Examples:

>>>a=”Hello”

>>>print(a)
„Hello‟

>>>b=”Class”

>>>print(b)

„Class‟

To print more than one item on a single line, comma (,) may be used.

>>>print(a,b)

„Hello Class‟

The print() function can print any number of values within the parentheses; they must be
separated by commas. For example:

The Python shell displayed values with blank spaces between them.

With the help of commas (,) and plus operator (+) we can print the variables with the double
quoted statement like this

Example

The output of this example is


Note : the difference in comma and plus is comma automatically incorporate space with the
statement but plus is not doing it automatically so program have to take care of it.

Python’s Built-in Functions

The range() function

Python has a more efficient way to handle a series of numbers and arithmetic progressions
and this is by using one its built-in functions: range(). The range function is particularly useful
in „for loops‟.

The syntax of the range() function.

>>>range(n)

example

>>>range(5)

range(0,5)

The expression range(5) above generates an iterator that progresses integers from zero and
ends with 4 (5-1). With the help of list function we can see all the values of the range
function.

To show the list of numbers, you can use the command list(range(n)).

>>>list(range(5))

[0, 1, 2, 3, 4]

You can exercise more control over the list output by calling the range() function with two
arguments: range (begin, end)

>>>list(range(5,9))

[5, 6, 7, 8]

Range function can be used with three arguments range(begin, end, iteration) begin and end
works as first and last element of the range and iteration is the difference of previous and
next element of the range

>>>list(range(1,20,2))

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Iteration can be negative if we are moving from higher to lower value

>>>list(range(20,1,-2))
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]

The examples of range() demonstrated an increment of 2. You can change the way Python
increments the number by introducing a third argument, the „step‟. It can be a negative or
positive number, but never zero. The format of this function range(begin, end, step).

The type function

To see the type of some data, use Python‟s built in type function the syntax of type function
is type( value or variable). To see the object type created and stored in the variable x, you
can use and enter the command type():

>>>type(x)

You should get this result:

<class „str‟>

abs() function

The abs() function returns the absolute value of a single number. It takes an integer or float
number as argument and always returns a positive value. Examples:

>>> abs(-15)

15

>>> abs(15)
15

When complex numbers are used as argument, the abs() function returns its magnitude:

>>> abs(4 + 9j)

9.848857801796104

max() function

The max() function takes two or more values as argument and returns the largest one.
Examples:

>>> max(29, 12, 76, 15)

76

>>> max(-12, -71, -35, -54)

-12

min() function

The min() function takes two or more values as arguments and returns the smallest item.
Examples:

>>> min(230, -109, 51, 12)

-109

>>> min(17, 26, 20, 44)

17

len() function

The len() function returns the length of an object or the number of items in a list given as
argument. Examples:

>>> len(“helloclasshowareyoutoday”)

24

>>> s = (“son”, “moon”, “star”)

>>> len(s)

Octal literals (base 8)


To indicate an octal number, you will use the prefix 0o or 0O (zero followed by either a
lowercase or uppercase letter „o‟). Example:

>>>a = 0O7

>>>print(a)

Hexadecimal literals (base 16)

To indicate hexadecimal literals, you will use the prefix „0X‟ or „0x” (zero and uppercase or
lowercase letter „x‟). Example:

>>>hex_lit = 0xed8

>>>print(hex_lit)

3800

Binary literals (base 2)

To signify binary literals, you‟ll use the prefix „0B‟ or „0b‟ (zero and uppercase or lowercase
„b‟). Example:

>>> c = 0b110011

>>> print(c)

51

Converting Integers to their String Representation

Earlier, you have seen how the print command converted literals to their equivalent in
integers. Python makes it possible for you to work the other way around by converting
integers to their literal representation. To convert an integer into its string representation,
you can use the functions hex(), bin(), and oct().

Examples:

To convert the integer 7 to its octal literal, type and enter oct(7) on the command prompt.
You‟ll get the output „0o7‟:

>>>oct(7)

„0o7‟

Here is what happens when you convert the integer 2572 to a hexadecimal literal:

>>>hex(15)
„0xf‟

Finally, see what happens when you use the bin() function to convert the integer 12 to its
binary string:

>>>bin(51)

„0b110011‟

You can store the result to a variable by defining a variable with the hex(), bin(), and oct()
functions: For example:

>>>x = hex(3800)

>>>print(x)

„0xed8‟

Here is a list of Python‟s built-in functions:

abs() all() any()


ascii() bin() bool()
bytearray() bytes() callable()
chr() classmethod() compile()
complex() delattr() dict()
dir() divmod() enumerate()
eval() exec() filter()
float() format() frozenset()
getattr() globals() hasattr()
hash() help() hex()
id() __import__() input()
int() isinstance() issubclass()
iter() len() list()
locals() map() max()
memoryview() min() next()
object() oct() open()
ord() pow() print()
property() range() repr()
reversed() round() set()
setattr() slice() sorted()
staticmethod() str() sum()
super() tuple() type()
vars() zip()

Conditional Statement

Conditional statements are common among programming languages and they are used to
perform actions or calculations based on whether a condition is evaluated as true or false.
The if statement is a compound statement that enables us to conditionally execute blocks of
code. If statements or conditional expressions are essential features of programming
languages and they make programs more useful to users. The if statement in Python has the
following basic structure:

if condition1:

block1_statement

The if statement also has optional else: clauses. Write the code on the file and save it with
the file name abs.py:

The output of the abs.py program:

The if-then-else statement in Python has the following basic structure:

if condition1:

block1_statement

else:
block2_statament

Note : input can take string input only. With the help of type casting we can change the data
type of that input from sting so any other data type.

The output of the program

In this program the output is correct because the ASCII value 7 is grater then the ASCII value
of 5 but we but when we do arithmetic operation on it will not work

Example

The error massage it that two string cannot be subtracted.


The condition in an if: or elif: clause can be any Python expression, in other words, something
that returns a value (even if that value is None). We can understand the function with the
example of greatest of three number:

The output of the program will be like this if you provide the input as 6,7 and 2 respectively
for variable a, b and c.

We can solve greatest of three numbers by another way the code is given below in the
example. In this example a variable naming big declared and the value of „a‟ is assigned to it.
Then „b‟ and „c‟ compare with the big if the big is smaller than the variable „b‟ or „c‟ then
that variable will assign to big else nothing will happen. Finally print the value of big as
greatest.
Let us take another example to understand batter how the if – elif – else works this example is
to find the day of the week if the user provide the number of the day the week starts with
Monday and end with Sunday.

If you enter the number of day as 3 then the output will be Wednesday but as you seen the
this example. As we have discussed earlier the input function takes input in the form of
string. In the previous example we have provide three variables as input a, b and c, user give
three numbers as input but in this example the values are compared as string with the ASCII
value of that number. The int functions take a string as argument and evaluates this string as
a Python expression. The result of an expression is an object which can be used by the
program accordingly. So we can use int function in our program to take integer or number
value from the string.
Let us take another example if – elif. In this example a menu has been created and on the
bases of operators operation will be performed.

If we have entered „–„ then subtraction has performed on „a‟ and „b‟.

If we have not use int function before input function then the code provide one output every
time “ This is a Wrong choice” because a has a string value and we are comparing it with
numeric value so it will run the else case and give the same answer with all the inputs.

The code without int function:


The output of the code without eval function:

Loops

A loop is a programming construct that enables repetitive processing of a sequence of


statements. Python provides two types of loops to its users: the „for loop‟ and the „while
loop‟. The „for‟ and „while‟ loops are iteration statements that allow a block of code (the
body of the loop) to be repeated a number of times.

The For Loop

Python implements an iterator-based „for loop‟. It is a type of „for loop‟ that iterates over a
list of items through an explicit or implicit iterator. The loop is introduced by the keyword
„for‟ which is followed by a random variable name which will contain the values supplied by
the object.

This is the syntax of Python‟s „for loop‟:

for variable in list:

statements
As usual, the action consists of one or more statements, all at the same indentation level.
These statements are also known as the body of the loop. The item is a variable name, and
list is a list. Execution of the for loop works by setting the variable successively to each item
in the list, and then executing the body each time. Here is a simple example to show the
working of for with a simple list given:

The output of the following code is :

Using the range() Function with the for Loop

The range() function can be combined with the „for loop‟ to supply the numbers required by
the loop. In the following example, the range(0, a) provided the numbers start from 0 to the
user input which is entered in the variable a needed by the „for loop‟ to display the numbers
in the list:

The output is as follows:


The While Loop

A Python „while loop‟ repeatedly carries out a target statement while the condition is true.
The loop iterates as long as the defined condition is true. When it ceases to be true and
becomes false, control passes to the first line after the loop.

The „while loop‟ has the following syntax:

while condition

statement

statement

Of course, the action may consist of one or more statements all at the same indentation
level. The statements in the action are known as the body of the loop. Execution of the loop
works as follows. First the condition is evaluated. If True, the body is executed and the
condition evaluated again, and this repeats until the condition evaluates to False. Here we
are using same example as we have discussed in for loop:

The output of this example is:


Let us consider another example of while loop for calculating the factorial of a number take a
number from user and store it in n variable

The output of the program is 120 as have calculate factorial:

Let us consider another example of printing table of a number the output of the program is
depending on the print statement by which we are printing the output. So as per the
requirement we have to write the print statement like in this example the table will print in
the format like

7*1=7

7 * 2 = 14

7 * 3 = 21

and so on, so in the while loop print statement itself we have defined this format

print(n ," * ", i ," = ", total),

because n containing the number for which we are printing the table and i is use to multiply
the number to find the net value of the possession and total has the result after the
multiplication of the number and the possession.
The output of the program if user enter the number as 8:

Debugging

Debugging is a multistep process that involves identifying a problem, isolating the source of
the problem, and then either correcting the problem or determining a way to work around it.
The final step of debugging is to test the correction or workaround and make sure it works.
The use of the word bug as a synonym for error originated in engineering. The term's
application to computing and the inspiration for using the word debugging as a synonym
for troubleshooting has been attributed to Admiral Grace Hopper, a pioneer in computer
programming, who was also known for her dry sense of humor. When an actual bug (a moth)
got caught between electrical relays and caused a problem in the U.S. Navy's first computer,
Admiral Hopper and her team "debugged" the computer and saved the moth. It now resides in
the Smithsonian Museum.
The debugging process

In software development, debugging involves locating and correcting code errors in a


computer program. Debugging is part of the software testing process and is an integral part of
the entire software development lifecycle. The debugging process starts as soon as code is
written and continues in successive stages as code is combined with other units of
programming to form a software product. In a large program that has thousands and
thousands of lines of code, the debugging process can be made easier by using strategies such
as unit tests, code reviews and pair programming.

Once an error has been identified, it is necessary to actually find the error in the code. At
this point, it can be useful to look at the code's logging and use a stand-alone debugger tool
or the debugging component of an integrated development environment (IDE). Invariably, the
bugs in the functions that get most use are found and fixed first.

The standard practice is to set up a "breakpoint" and run the program until that breakpoint,
at which time program execution stops. The debugging component of an IDE typically provides
the programmer with the capability to view memory and see variables, run the program to
the next breakpoint, execute just the next line of code, and, in some cases, change the value
of variables or even change the contents of the line of code about to be executed.

Common debugging tools

Source code analyzers, which include security, common code errors and complexity analyzers,
can also be helpful in debugging. A complexity analyzer can find modules that are so intricate
as to be hard to understand and test. Some tools can actually analyze a test run to see what
lines of code were not executed, which can aid in debugging. Other debugging tools include
advanced logging and simulators that allow the programmer to model how an app on a mobile
device will display and behave.

Some tools, especially open source tools and scripting languages, do not run in an IDE and
require a more manual approach to debugging. Such techniques include dropping values to a
log, extensive "print" statements added during code execution or hard-coded "wait" commands
that simulate a breakpoint by waiting for keyboard input at specific times.

Errors and exceptions

Errors

Errors or mistakes in a program are often referred as bugs. They are almost always the fault
of the programmer. The process of finding and eliminating errors is called debugging. Errors
can be classified into three major groups:

 Syntax errors
 Runtime errors
 Logical errors
Syntax errors

Python will find these kinds of errors when it tries to parse your program, and exit with an
error message without running anything. Syntax errors are mistakes in the use of the Python
language, and are analogous to spelling or grammar mistakes in a language like English: for
example, the sentence would you some tea? does not make sense – it is missing a verb.

Common Python syntax errors include:

 leaving out a keyword


 putting a keyword in the wrong place
 leaving out a symbol, such as a colon, comma or brackets
 misspelling a keyword
 incorrect indentation
 empty block

Python will do its best to tell you where the error is located, but sometimes its messages can
be misleading: for example, if you forget to escape a quotation mark inside a string you may
get a syntax error referring to a place later in your code, even though that is not the real
source of the problem. If you can‟t see anything wrong on the line specified in the error
message, try backtracking through the previous few lines. As you program more, you will get
better at identifying and fixing errors.

Here are some examples of syntax errors in Python:


Runtime errors

If a program is syntactically correct – that is, free of syntax errors – it will be run by the
Python interpreter. However, the program may exit unexpectedly during execution if it
encounters a runtime error – a problem which was not detected when the program was
parsed, but is only revealed when a particular line is executed. When a program comes to a
halt because of a runtime error, we say that it has crashed.

Consider the English instruction flap your arms and fly to Australia. While the instruction is
structurally correct and you can understand its meaning perfectly, it is impossible for you to
follow it.

Some examples of Python runtime errors:

 division by zero
 performing an operation on incompatible types
 using an identifier which has not been defined
 accessing a list element, dictionary value or object attribute which doesn‟t exist
 trying to access a file which doesn‟t exist

Runtime errors often creep in if you don‟t consider all possible values that a variable could
contain, especially when you are processing user input. You should always try to add checks
to your code to make sure that it can deal with bad input and edge cases gracefully. We will
look at this in more detail in the chapter about exception handling.
Logical errors

Logical errors are the most difficult to fix. They occur when the program runs without
crashing, but produces an incorrect result. The error is caused by a mistake in the program‟s
logic. You won‟t get an error message, because no syntax or runtime error has occurred. You
will have to find the problem on your own by reviewing all the relevant parts of your code –
although some tools can flag suspicious code which looks like it could cause unexpected
behavior.

Sometimes there can be absolutely nothing wrong with your Python implementation of an
algorithm – the algorithm itself can be incorrect. However, more frequently these kinds of
errors are caused by programmer carelessness. Here are some examples of mistakes which
lead to logical errors:

 using the wrong variable name


 indenting a block to the wrong level
 using integer division instead of floating-point division
 getting operator precedence wrong
 making a mistake in a Boolean expression
 off-by-one, and other numerical errors

If you misspell an identifier name, you may get a runtime error or a logical error, depending
on whether the misspelled name is defined.

A common source of variable name mix-ups and incorrect indentation is frequent copying and
pasting of large blocks of code. If you have many duplicate lines with minor differences, it‟s
very easy to miss a necessary change when you are editing your pasted lines. You should
always try to factor out excessive duplication using functions and loops.

The example given below is the best example for logical error. In this example the avrage of
three numbers has been calculated but the formula or the loigs of the program is incorect. So
whatever the answer that will be incorrect so, this type of errors are called logical errors.

The output or the result of the program will be 5 but it gives 11.0 because the formula of the
average is not correct, so result is also wrong.
Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an


attempt is made to execute it. Errors detected during execution are called exceptions and
are not unconditionally fatal: you will soon learn how to handle them in Python programs.
Most exceptions are not handled by programs, however, and result in error messages as shown
here:

The last line of the error message indicates what happened. Exceptions come in different
types, and the type is printed as part of the message: the types in the example
are ZeroDivisionError, NameError and TypeError. The string printed as the exception type is
the name of the built-in exception that occurred. This is true for all built-in exceptions, but
need not be true for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception happened, in
the form of a stack traceback. In general it contains a stack traceback listing source lines;
however, it will not display lines read from standard input.

Debugging: pdb and break points

In software development, debugging is the process of looking for and then resolving issues
that prevent the software from running correctly.

The Python debugger provides a debugging environment for Python programs. It supports
setting conditional breakpoints, stepping through the source code one line at a time, stack
inspection, and more.

Working Interactively with the Python Debugger

The module pdb defines an interactive source code debugger for Python programs. It supports
setting (conditional) breakpoints and single stepping at the source line level, inspection of
stack frames, source code listing, and evaluation of arbitrary Python code in the context of
any stack frame. It also supports post-mortem debugging and can be called under program
control. The debugger is extensible – it is actually defined as the class Pdb. The extension
interface uses the modules bdb and cmd.

Exercise

Q.1 Find all the syntax errors in the code given below, and explain why they are errors.

myfunction(x, y):

return x + y

else:

print("Hello!")

if mark >= 50

print("You passed!")

if arriving:

print("Hi!")

esle:
print("Bye!")

if flag:

print("Flag is set!")

Q.2 Find potential sources of runtime errors in this code snippet:

dividend = float(input("Please enter the dividend: "))

divisor = float(input("Please enter the divisor: "))

quotient = dividend / divisor

quotient_rounded = math.round(quotient)

Q. 3 Find potential sources of runtime errors in this code snippet:

for x in range(a, b):

print("(%f, %f, %f)" % my_list[x])

Q.4 Find potential sources of logic errors in this code snippet:

product = 0

for i in range(10):

product *= i

sum_squares = 0

for i in range(10):

i_sq = i**2

sum_squares += i_sq

nums = 0

for num in range(10):

num += num

You might also like