Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
97 views

Python UNIT 1

This document provides an overview of Python programming and algorithmic problem solving. It discusses that a program is a set of instructions that tells a computer how to solve a problem. Algorithms are used to design the logic and steps to solve problems, and programming implements algorithms using a language like Python. The document outlines key aspects of algorithms like inputs, outputs, effectiveness, and characteristics. It also describes different algorithm design techniques and strategies like control structures, pseudocode, and flowcharts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

Python UNIT 1

This document provides an overview of Python programming and algorithmic problem solving. It discusses that a program is a set of instructions that tells a computer how to solve a problem. Algorithms are used to design the logic and steps to solve problems, and programming implements algorithms using a language like Python. The document outlines key aspects of algorithms like inputs, outputs, effectiveness, and characteristics. It also describes different algorithm design techniques and strategies like control structures, pseudocode, and flowcharts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Python Programming

UNIT I

1.1 Algorithmic Problem Solving


INTRODUCTION

A program is a set of instructions that tells the computer how to solve a particular problem. Various
program design tools like algorithms, pseudocdes and flowcharts are used to design the blueprint of the
solution (or the program to be written). Computer programming goes a step further in problem solving
process. Programming means writing computer programs. While programming, the programmers take
an algorithm and code the instructions in a particular programming language so that it can be executed
by a computer. These days, there are many programming languages available in the market. The
programmer can choose any language depending on his expertise and the problem domain.

ALGORITHMS

In computing, we focus on the type of problems categorically known as algorithmic problems, where
their solutions are expressible in the form of algorithms. The term ‘algorithm’ was derived from the
name of Mohammed al-Khwarizmi, a Persian mathematician in the nineth century (Al-Khwarizmi →
Algorism (in Latin) → Algorithm). The typical meaning of an algorithm is a formally defined procedure for
performing some calculation. If a procedure is formally defined, then it must be implemented using
some formal language, and such languages are known as programming languages. The algorithm gives
the logic of the program, that is, a step-by-step description of how to arrive at a solution.

In general terms, an algorithm provides a blueprint to writing a program to solve a particular problem. It
is considered to be an effective procedure for solving a problem in a finite number of steps. That is, a
well-defined algorithm always provides an answer, and is guaranteed to terminate

Algorithms are mainly used to achieve software reuse. Once we have an idea or a blueprint of a solution,
we can implement it in any language, such as C, C++, Java, and so on. In order to qualify as an algorithm,
a sequence of instructions must possess the following characteristics:

• Effectiveness: The algorithm should designed in such a way that it should be the most effective among
many different ways to solve a problem.

• Input: The algorithm must receive an input.

• Output: After the algorithm gets terminated, the desired result must be obtained.

• Generality: The algorithm can be applied to various set of inputs.


An algorithm starts from an initial state with some input. The instructions/statements describe the
processing that must be done on the input to produce the final output (the final state). Note that an
instruction is a single operation which when executed converts one state to other.

In the course of processing, data is read from an input device, stored in computer’s memory for further
processing, and then the result of the processing is written to an output device. The data is stored in the
computer’s memory in the form of variables or constants.

The state of an algorithm is defined as its condition regarding current values or contents of the stored
data.

An algorithm is a list of precise steps and the order of steps determines the functioning of the algorithm.
The flow of control (or the control flow) of an algorithm can be specified as top-down or bottom-up
approach. Thus, the flow of control specifies the order in which individual instructions of an algorithm
are executed.

1.1.1 Subcharts/Subroutine/Predefined Process

A subroutine (or procedure or function or routine) is a sequence of instructions that performs a specific
task. These instructions are packaged as a single unit and can be used (or invoked or called) wherever
that particular task needs to be performed. After performing its defined task, the sub-routine branches
back (or returns) to the next instruction after the one that invoked it.

A subroutine may be designed to accept one or more data values (also known as parameters) from the
calling code. It may also return a value to its caller.

A subroutine can also be written in such a way that it calls itself repeatedly. The subroutine symbol is
used to write steps for procedures. These procedures can be called from anywhere in the code. This
means that once the flowchart for a process is drawn, it can be referenced and used from anywhere in
the code.
1.4 ALGORITHMIC PROBLEM SOLVING STEPS

As mentioned earlier, algorithms are solutions to problems. They are not solutions themselves. They just
list specific instructions that need to be performed for getting the solution. In computer science,
emphasis is laid on writing a good and effective algorithm and this emphasis makes computer science
distinct from other disciplines. For example, computer science is distinct from theoretical mathematics
because those practitioners are typically satisfied with just proving the existence of a solution to a
problem but in computer science, the problem is not solved until the algorithm is used to implement the
solution. We will now discuss about the sequence of steps one must typically follow for designing an
effective algorithm.

1. Understanding the problem

2. Determining the capabilities of the computational device

3. Exact/approximate solution

4. Select the appropriate data structure

5. Algorithm design techniques

6. Methods of specifying an algorithm

7. Proving an algorithms correctness

8. Analysing the performance of an algorithm

Understanding the problem

The problem given should be clearly and completely understood. It is compared with earlier problems
that have already been solved to check if it is similar to them and a known algorithm exists. If the
algorithm is available, it is used, otherwise a new one has to be developed.

Determining the capabilities of the computational device

After understanding the problem, the capabilities of the computing device should be known. For this,
the type of the architecture, speed and memory availability of the device are noted.

Exact/approximate solution
The next step is to develop the algorithm. The algorithm must compute correct output for all possible
and legitimate inputs. This solution can be an exact solution or an approximate solution. For example,
you can only have an approximate solution in case of finding square root of number or finding the
solutions of non-linear equations.

Select the appropriate data structure

A data type is a well-defined collection of data with a welldefined set of operations on it. A data
structure is basically a group of data elements that are put together under one name, and which defines
a particular way of storing and organizing data in a computer so that it can be used efficiently. The
elementary data structures are as follow

1 List: Allows fast access of data.

2 Sets: Treats data as elements of a set. Allows application of operations such as intersection, union,
and equivalence.

3 Dictionaries: Allows data to be stored as a key-value pair.

Algorithm design techniques

Developing an algorithm is an art which may never be fully automated. By mastering the design
techniques, it will become easier for you to develop new and useful algorithms. Examples of algorithm
design techniques include dynamic programming.

Methods of specifying an algorithm

An algorithm is just a sequence of steps or instructions that can be used to implement a solution. After
writing the algorithm, it is specified either using a natural language or with the help of pseudocode and
flowcharts.

Proving algorithms correctness

Writing an algorithm is not just enough. You need to prove that it computes solutions for all the possible
valid inputs. This process is often referred to as algorithm validation. Algorithm validation ensures that
the algorithm will work correctly irrespective of the programming language in which it will be
implemented.

Analysing the performance of algorithms

When an algorithm is executed, it uses the computer’s resources like the Central Processing Unit (CPU)
to perform its operation and to hold the program and data respectively. An algorithm is analysed to
measure its performance in terms of CPU time and memory space required to execute that algorithm.
This is a challenging task and is often used to compare different algorithms for a particular problem. The
result of the comparison helps us to choose the best solution from all possible solutions. Analysis of the
algorithm also helps us to determine whether the algorithm will be able to meet any efficiency
constraint that exits or not.

1.5 SIMPLE STRATEGIES AND NOTATIONS FOR DEVELOPING ALGORITHMS

An algorithm is a step–by–step procedure for solving a task or problem. However, these steps must be
ordered, unambiguous and finite in number. Basically, an algorithm is nothing but English-like
representation of logic which is used to solve the problem. For accomplishing a particular task, different
algorithms can be written. The different algorithms differ in their requirements of CPU time and memory
space. The programmer selects the best suited algorithm for the given task to be solved.

Various strategies and notations used for developing and designing algorithms are discussed in the
following sections.

1.5.1 Control Structures Used in Algorithms

An algorithm has a finite number of steps and some steps may involve decision making and repetition.
Broadly speaking, an algorithm may employ three control structures, namely, sequence, decision, and
repetition.

Sequence

Sequence means that each step of the algorithm is executed in the specified order. An algorithm to add
two numbers is given as follows. This algorithm performs the steps in a purely sequential order.

Step 1 : Start Step 2 : Input first number as A


Step 3 : Input second number as B

Step 4 : Set Sum = A + B

Step 5 : Print Sum Step 6 :

End

Decision

Decision statements are used when the outcome of the process depends on some condition. For
example, if x = y, then print "EQUAL". Hence, the general form of the if construct can be given as
follows:

IF condition then process

A condition in this context is any statement that may evaluate either to a true value or a false value. In
the preceding example, the variable x can either be equal or not equal to y. However, it cannot be both
true and false. If the condition is true then the process is executed.

A decision statement can also be stated in the following manner:

IF condition

then process1  

ELSE process2

This form is commonly known as the if-else construct. Here, if the condition is true then process1 is
executed, else process2 is executed. An algorithm to check the equality of two numbers is shown below
1.2.1 FLOW CHART

A flowchart is a graphical or symbolic representation of a process. It is basically used to design and


document virtually complex processes to help the viewers to visualize the logic of the process, so that
they can gain a better understanding of the process and find flaws, bottlenecks, and other less obvious
features within it.

When designing a flowchart, each step in the process is depicted by a different symbol and is associated
with a short description. The symbols in the flowchart (refer Figure 1.1) are linked together with arrows
to show the flow of logic in the process. The symbols used in a flowchart include the following:

1 Start and end symbols are also known as the terminal symbols and are represented as circles, ovals, or
rounded rectangles. Terminal symbols are always the first and the last symbols in a flowchart.

2 Arrows depict the flow of control of the program. They illustrate the exact sequence in which the
instructions are executed.

3 Generic processing step, also called as an activity, is represented using a rectangle. Activities include
instructions such as add a to b or save the result. Therefore, a processing symbol represents arithmetic
and data movement instructions. When more than one process has to be executed simultaneously, they
can be placed in the same processing box. However, their execution will be carried out in the order of
their appearance.

• Input/Output symbols are represented using a parallelogram and are used to get inputs from the users
or display the results to them.

• A conditional or decision symbol is represented using a diamond. It is basically used to depict a Yes/No
question or a True/False test. The two symbols coming out of it, one from the bottom point and the
other from the right point, corresponds to Yes or True, and No or False, respectively. The arrows should
always be labelled. A decision symbol in a flowchart can have more than two arrows, which indicates
that a complex decision is being taken.

• Labelled connectors are represented by an identifying label inside a circle and are used in complex or
multi-sheet diagrams to substitute for arrows. For each label, the ‘outflow’ connector must have one or
more ‘inflow’ connectors. A pair of identically labelled connectors is used to indicate a continued flow
when the use of lines becomes confusing.

• A pre-defined process symbol is a marker for another process step or series of process flow steps that
are formally defined elsewhere. This shape commonly depicts sub-processes (or subroutines in
programming flowcharts).

Significance of Flowcharts
A flowchart is a diagrammatic representation that illustrates the sequence of steps that must be
performed to solve a problem. It is usually drawn in the early stages of formulating computer solutions.
It facilitates communication between programmers and users. Once a flowchart is drawn, programmers
can make users understand the solution easily and clearly.

Flowcharts are very important in the programming of a problem as they help the programmers to
understand the logic of complicated and lengthy problems. Once a flowchart is drawn, it becomes easy
for the programmers to write the program in any high-level language. Hence, the flowchart has become
a necessity for better documentation of complex programs

Advantages of flowchart:
1.Communication: - Flowcharts are better way of communicating the logic of
a system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
3.Proper documentation: - Program flowcharts serve as a good
program documentation, which is needed for various purposes.
4.Efficient Coding: - The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6.Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put
efforts more efficiently on that part.
 Disadvantages of flow chart:
1. Complex logic: - Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart
may require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction
of flowchart becomes a problem.
4.Cost: For large application the time and cost of flowchart drawing
becomes costly.

1.5.3 Pseudocodes
Pseudocode is a compact and informal high-level description of an algorithm that uses the structural
conventions of a programming language. It facilitates designers to focus on the logic of the algorithm
without getting bogged down by the details of language syntax. An ideal pseudocode must be complete,
describing the entire logic of the algorithm, so that it can be translated straightaway into a programming
language.

It is basically meant for human reading rather than machine reading, so it omits the details that are not
essential for humans. Such details include variable declarations, system-specific code, and subroutines.

Pseudocodes are an outline of a program that can easily be converted into programming statements.
They consist of short English phrases that explain specific tasks within a program’s algorithm. They
should not include keywords in any specific computer language.

The sole purpose of pseudocodes is to enhance human understandability of the solution. They are
commonly used in textbooks and scientific publications for documenting algorithms, and for sketching
out the program structure before the actual coding is done. This helps even non-programmers to
understand the logic of the designed solution. There are no standards defined for writing a pseudocode,
because a pseudocode is not an executable program. Flowcharts can be considered as graphical
alternatives to pseudocodes, but require more space on paper.
1.3 PROGRAMMING LANGUAGE

A programming language is a language specifically designed


to express computations that can be performed by a
computer. Programming languages are used to create
programs that control the behavior of a system, to express
algorithms, or as a mode of human communication.

Usually, programming languages have a vocabulary of


syntax and semantics for instructing a computer to perform
specific tasks. The term programming language refers to
high-level languages such as BASIC (Beginners’ All-purpose
Symbolic Instruction Code), C, C++, COBOL (Common
Business Oriented Language), FORTRAN (Formula
Translator), Python, Ada, and Pascal, to name a few. Each of
these languages has a unique set of keywords (words that it
understands) and a special syntax for organizing program
instructions

Though high-level programming languages are easy for


humans to read and understand, the computer can
understand only machine language, which consists of only
numbers. Each type of central processing unit (CPU) has its
own unique machine language.

In between machine languages and high-level languages,


there is another type of language known as assembly
language. Assembly languages are similar to machine
languages, but they are much easier to program because
they allow a programmer to substitute names for numbers.

However, irrespective of the language that a programmer


uses, a program written using any programming language
has to be converted into machine language so that the
computer can understand it. There are two ways to do this:
compile the program or interpret the program.

When planning a software solution, the software


development team often faces a common question— which
programming language to use? Many programming
languages are available today and each one has its own
strengths and weaknesses. Python can be used to write an
efficient code, whereas a code in BASIC is easy to write and
understand; some languages are compiled, whereas others
are interpreted; some languages are well known to the
programmers, whereas others are completely new. Selecting
the perfect language for a particular application at hand is a
daunting task.

The selection of language for writing a program depends on


the following factors:

• The type of computer hardware and software on which the


program is to be executed.

• The type of program.


• The expertise and availability of the programmers.

• Features to write the application.

• The built-in features that support the development of


software that are reliable and less prone to crash.

• Lower development and maintenance costs.

• Stability and capability to support even more than the


expected simultaneous users.

• Elasticity of a language that implies the ease with which


new features (or functions) can be added to the existing
program.

• Portability.

• Better speed of development that includes the time it takes


to write a code, time taken to find a solution to the problem
at hand, time taken to find the bugs, availability of
development tools, experience and skill of the programmers,
and testing regime.

For example, FORTRAN is a particularly good language for


processing numerical data, but it does not lend itself very
well to organizing large programs. Pascal can be used for
writing well-structured and readable programs, but it is not
as flexible as the C programming language. C++ goes one
step ahead of C by incorporating powerful object oriented
features, but it is complex and difficult to learn. Python,
however is a good mix of the best features of all these
languages.

UNIT 1

1.2 PYTHON DATA, EXPRESSIONS, STATEMENTS


In programming language terminology, an “expression” is a combination of values and

functions that are combined and interpreted by the compiler to create a new value, as

opposed to a “statement” which is just a standalone unit of execution and doesn't return

anything.

Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually
classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric
value can be integer, floating number or even complex numbers. These values are
defined as int, float and complex class in Python.
 Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fraction or decimal). In Python there is no limit
to how long an integer value can be.
 Float – This value is represented by float class. It is a real number with
floating point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
 Complex Numbers – Complex number is represented by complex class. It
is specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.

# Python program to 

# demonstrate numeric value

  
a =5

print("Type of a: ", type(a))

  

b = 5.0

print("\nType of b: ", type(b))

  

c = 2 + 4j

print("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

Python Expressions:
Expressions are representations of value. They are different from statement in the fact that statements do
something while expressions are representation of value. For example any string is also an expressions
since it represents the value of the string as well.

Python has some advanced constructs through which you can represent values and hence these
constructs are also called expressions.

1 .3.1 Python interpreter:


Python is a general-purpose interpreted, interactive, object-oriented, and highlevel programming
language. It was created by Guido van Rossum during 1985- 1990. Python got its name from “Monty
Python’s flying circus”. Python was released in the year 2000.
Python is interpreted: Python is processed at runtime by the interpreter. You do not need to compile
your program before executing it.

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 beginnerlevel programmers and
supports the development of a wide range of applications.

Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is very
simple. It uses few keywords.

Easy-to-maintain: Python's source code is fairly easy-to-maintain. Portable: Python can run on a wide
variety of hardware platforms and has the same interface on all platforms.

Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile a
program before executing it. You can simply run the program.

Extensible: Programmers can embed python within their C,C++,Java script ,ActiveX, etc.

Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.

High Level Language: When writing programs, programmers concentrate on solutions of the current
problem, no need to worry about the low level details.

Scalable: Python provides a better structure and support for large programs than shell scripting.

Applications:
Bit Torrent file sharing

Google search engine, Youtube

Intel, Cisco, HP, IBM

i–Robot

NASA

Facebook, Drop box


1.3. Python interpreter
An interpreter is a computer program that executes instructions written in a
programming language. It can either execute the source code directly or translate
the source code in a first step into a more efficient representation and executes this
code.
 

1.4 MODES OF PYTHON INTERPRETER:

2.VALUES AND DATA TYPES

2.1Numbers:

2.2 Sequence:

Sequence Type
In Python, sequence is the ordered collection of similar or different data types.
Sequences allows to store multiple values in an organized and efficient fashion.
There are several sequence types in Python –
 String
 List
 Tuple

2.2.1 Strings:

1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is
a collection of one or more characters put in a single quote, double-quote or triple
quote. In python there is no character data type, a character is a string of length
one. It is represented by str class.
 
Creating String
Strings in Python can be created using single quotes or double quotes or even
triple quotes.

# Python Program for 

# Creation of String 

    

# Creating a String  

# with single Quotes 

String1 = 'Welcome to the Geeks World'

print("String with the use of Single Quotes: ") 

print(String1) 

    

# Creating a String 

# with double Quotes 

String1 = "I'm a Geek"

print("\nString with the use of Double Quotes: ") 

print(String1) 

print(type(String1))

    

# Creating a String 
# with triple Quotes 

String1 = '''I'm a Geek and I live in a world of "Geeks"'''

print("\nString with the use of Triple Quotes: ") 

print(String1) 

print(type(String1))

  

# Creating String with triple 

# Quotes allows multiple lines 

String1 = '''Geeks 

            For 

            Life'''

print("\nCreating a multiline String: ") 

print(String1) 

Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek
<class 'str'>

String with the use of Triple Quotes:


I'm a Geek and I live in a world of "Geeks"
<class 'str'>

Creating a multiline String:


Geeks
For
Life
 
Accessing elements of String
In Python, individual characters of a String can be accessed by using the method
of Indexing. Indexing allows negative address references to access characters
from the back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character and so on.

# Python Program to Access 

# characters of String 

    
String1 = "GeeksForGeeks"

print("Initial String: ") 

print(String1) 

    

# Printing First character 

print("\nFirst character of String is: ") 

print(String1[0]) 

    

# Printing Last character 

print("\nLast character of String is: ") 

print(String1[-1]) 

Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


s
2.2.2 Lists

2) List
Lists are just like the arrays, declared in other languages which is a ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type.
 
Creating List
Lists in Python can be created by just placing the sequence inside the square
brackets[].

# Python program to demonstrate  

# Creation of List  

    

# Creating a List 

List = [] 

print("Intial blank List: ") 

print(List) 

    

# Creating a List with  

# the use of a String 

List = ['GeeksForGeeks'] 

print("\nList with the use of String: ") 


print(List) 

    

# Creating a List with 

# the use of multiple values 

List = ["Geeks", "For", "Geeks"] 

print("\nList containing multiple values: ") 

print(List[0])  

print(List[2]) 

    

# Creating a Multi-Dimensional List 

# (By Nesting a list inside a List) 

List = [['Geeks', 'For'], ['Geeks']] 

print("\nMulti-Dimensional List: ") 

print(List) 

Output:
Intial blank List:
[]

List with the use of String:


['GeeksForGeeks']

List containing multiple values:


Geeks
Geeks

Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
 
Accessing elements of List
In order to access the list items refer to the index number. Use the index operator [
] to access an item in a list. In Python, negative sequence indexes represent
positions from the end of the array. Instead of having to compute the offset as
in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means
beginning from the end, -1 refers to the last item, -2 refers to the second-last item,
etc.

# Python program to demonstrate  

# accessing of element from list 

    

# Creating a List with 

# the use of multiple values 

List = ["Geeks", "For", "Geeks"] 

    

# accessing a element from the  

# list using index number 

print("Accessing element from the list") 

print(List[0])  

print(List[2]) 
  

# accessing a element using 

# negative indexing 

print("Accessing element using negative indexing") 

    

# print the last element of list 

print(List[-1]) 

    

# print the third last element of list  

print(List[-3]) 

Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

2.2.4Tuple:

3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e. tuples cannot be
modified after it is created. It is represented by tuple class.
 
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data sequence.
Tuples can contain any number of elements and of any datatype (like strings,
integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having
one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to
make it a tuple.

# Python program to demonstrate  

# creation of Set 

    

# Creating an empty tuple 

Tuple1 = () 

print("Initial empty Tuple: ") 

print (Tuple1) 

    

# Creating a Tuple with  

# the use of Strings 

Tuple1 = ('Geeks', 'For') 

print("\nTuple with the use of String: ") 

print(Tuple1) 
    

# Creating a Tuple with 

# the use of list 

list1 = [1, 2, 4, 5, 6] 

print("\nTuple using List: ") 

print(tuple(list1)) 

  

# Creating a Tuple with the 

# use of built-in function 

Tuple1 = tuple('Geeks') 

print("\nTuple with the use of function: ") 

print(Tuple1) 

  

# Creating a Tuple  

# with nested tuples 

Tuple1 = (0, 1, 2, 3) 

Tuple2 = ('python', 'geek') 

Tuple3 = (Tuple1, Tuple2) 

print("\nTuple with nested tuples: ") 


print(Tuple3) 

Output:
Initial empty Tuple:
()

Tuple with the use of String:


('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))
 
Note – Creation of Python tuple without the use of parentheses is known as Tuple
Packing.
Accessing elements of Tuple
In order to access the tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple. The index must be an integer. Nested
tuples are accessed using nested indexing.

# Python program to 

# demonstrate accessing tuple

  
tuple1 = tuple([1, 2, 3, 4, 5])

  

# Accessing element using indexing

print("Frist element of tuple")

print(tuple1[0])

  

# Accessing element from last

# negative indexing

print("\nLast element of tuple")

print(tuple1[-1])

  

print("\nThird last element of tuple")

print(tuple1[-3])

Output:
Frist element of tuple
1

Last element of tuple


5

Third last element of tuple


3
3.Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And Indentation, Quotation
In Python, Tuple Assignment:

3.4 STATEMENTS AND EXPRESSIONS:

Interpreter: To execute a program in a high-level language by translating it one line at a

time. Compiler: To translate a program written in a high-level language into a low-level

language all at once, in preparation for later execution.


Python Programming/Interactive mode

Python has two basic modes: script and interactive. The normal mode is the mode where the scripted and

finished  .py  files are run in the Python interpreter. Interactive mode is a command line shell which gives

immediate feedback for each statement, while running previously fed statements in active memory

 Advantages
Readability
High level language is closer to natural language so they are easier to learn
and understand
Machine independent
High level language program have the advantage of being portable between
machines.
Easy debugging
Easy to find and correct error in high level language
 Disadvantages
Less efficient
The translation process increases the execution time of the program.
Programs in high level language require more memory and take more
execution time to execute.

 
1.1.5 Values and Data Types
Value:
 Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong
to different datatypes.)
 Data type:
 Every value in Python has a data type.
 It is a set of values, and the allowable operations on those values.
 Python has four standard data types:

Numbers:
 Number data type stores Numerical Values.
 This data type is immutable [i.e. values/items cannot be changed].
 Python supports integers, floating point numbers and complex
numbers. They are defined as,

You might also like