Right now I am in mid of completing this book. Just uploaded first and part of second chapter. Will upload whole once I am done.
Can contact me at nitin_k@outlook.com for more details or to get a copy of this book.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
It includes various types of programming errors: Syntax, Semantic, Logical, Runtime Error with the help of C++ programs. Also, discussed how to fix these errors.
For better understanding, subscribe following YouTube channel:
https://youtu.be/PIOCmaYdSCg
Complete C++ programming Language CourseVivek chan
This is the Complete course of C++ Programming Language for Beginners. All Topics of C++ programming Language are covered in this single power point presentation.
Visit: www.cyberlabzone.com
It includes various types of programming errors: Syntax, Semantic, Logical, Runtime Error with the help of C++ programs. Also, discussed how to fix these errors.
For better understanding, subscribe following YouTube channel:
https://youtu.be/PIOCmaYdSCg
Complete C++ programming Language CourseVivek chan
This is the Complete course of C++ Programming Language for Beginners. All Topics of C++ programming Language are covered in this single power point presentation.
Visit: www.cyberlabzone.com
Project Report for Twitter Sentiment Analysis done using Apache Flume and data is analysed using Hive.
I intend to address the following questions:
How raw tweets can be used to find audience’s perception or sentiment about a person ?
How Hadoop can be used to solve this problem?
How Apache Hive can be used to organize the final data in a tabular format and query it?
How a data visualization tool can be used to display the findings?
SentiTweet is a sentiment analysis tool for identifying the sentiment of the tweets as positive, negative and neutral.SentiTweet comes to rescue to find the sentiment of a single tweet or a set of tweets. Not only that it also enables you to find out the sentiment of the entire tweet or specific phrases of the tweet.
Make a query regarding a topic of interest and come to know the sentiment for the day in pie-chart or for the week in form of line-chart for the tweets gathered from twitter.com
Python is a general-purpose, interpreted, interactive, object-oriented and high-level
programming language. Python was created by Guido van Rossum in the late eighties and
early nineties. Like Perl, Python source code is also now available under the GNU General
Public License (GPL).
The Tellurium Automated Testing Framework (Tellurium) is a UI module-based automated testing framework for web applications and it is robust, expressive, flexible, and reusable. This is Tellurium 0.6.0 User Guide.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Python for class 11 (CBSE Computer science sub code 083)
1. Python for class XI
Document Version: 0.2
Control: Internal
Document Release Date: June 2014
Reference book for Computer
Science CBSE (code- 083)
Nitin Kumar
2. Version: 0.2 2 of 49
Distribution
Document Distribution
Architecture Group
All rights reserved. This document is protected and cannot be reprinted, reproduced, copied or utilised in whole or in part by any means
including electronic, mechanical, or other means without the prior written consent of Nitin K.
Whilst reasonable care has been taken by Nitin K to ensure the information contained herein is reasonably accurate, Nitin K shall not, under
any circumstances be liable for any loss or damage (direct or consequential) suffered by any party as a result of the contents of this publication
or the reliance of any party thereon or any inaccuracy or omission therein. The information in this document is therefore provided on an “as is”
basis without warranty and is subject to change without further notice and cannot be construed as a commitment by Nitin K.
The products mentioned in this document are identified by the names, trademarks, service marks and logos of their respective companies or
organisations and may not be used in any advertising or publicity or in any other way whatsoever without the prior written consent of those
companies or organisations and Nitin K.
3. Version: 0.2 3 of 49
Table of Contents
1
Preface...................................................................................................................6
1.1
Purpose ..................................................................................................................................6
1.2
Syllabus..................................................................................................................................7
1.3
About Author ..........................................................................................................................9
1.4
Acknowledgment and Credit ..................................................................................................9
1.5
Organisation ...........................................................................................................................9
1.6
Typographic Conventions.....................................................................................................10
2
Introduction to Python.......................................................................................11
2.1
About Python........................................................................................................................11
2.2
History of Python ..................................................................................................................12
2.3
Companies using Python .....................................................................................................12
2.4
Basics of Computer programming........................................................................................13
2.4.1
Advantages of Interpreter Language ......................................................................13
2.4.2
Disadvantages of Interpreter Language..................................................................13
2.4.3
Open source Software ............................................................................................14
2.5
Python Enhancement Proposals (PEPs)..............................................................................14
2.5.1
PEP 8......................................................................................................................15
2.5.2
PEP 20....................................................................................................................15
2.6
First step toward of Python Program....................................................................................16
2.6.1
Download and install Python...................................................................................16
2.6.2
Python IDLE............................................................................................................16
2.6.3
Python Interactive Mode .........................................................................................17
2.6.4
Python Script Mode.................................................................................................19
2.6.5
Getting Help ............................................................................................................21
3
Data Types ..........................................................................................................22
3.1
Variables ..............................................................................................................................22
3.2
Assigning Values to Variables:.............................................................................................25
3.3
Standard Data Types: ..........................................................................................................27
3.3.1
Numbers .................................................................................................................27
3.3.2
Number Data Type Conversion: .............................................................................31
3.3.3
Boolean Operations: ...............................................................................................32
3.3.4
Important Numeric Exceptions................................................................................32
4
Collection Data Types........................................................................................33
4.1
List........................................................................................................................................34
4.1.1
Indexing ..................................................................................................................34
4.1.2
List Slicing...............................................................................................................35
4.1.3
Operators on list......................................................................................................36
4.1.4
Methods of list Objects............................................................................................38
4. Version: 0.2 4 of 49
4.1.5
Important List Exception .........................................................................................40
4.2
Tuple ....................................................................................................................................41
4.2.1
Operators on Tuple .................................................................................................42
4.2.2
Methods of Tuple Objects .......................................................................................44
4.2.3
Important Tuple Exception ......................................................................................45
4.3
String ....................................................................................................................................46
Glossary and Abbreviations ...................................................................................47
References................................................................................................................48
5. Version: 0.2 5 of 49
List of Tables
Table P-1: Typographic Conventions .................................................................................... 10
6. Version: 0.2 6 of 49
1 Preface
1.1 Purpose
As this year in 2013 CBSE (Central Board of Secondary Education) brought major changes in
the syllabus of Class 11 and class 12 students. The changes are made in the subject
'Computer Science' (code- 083).
C++ session is replaced with PYTHON. This major change was introduced keeping in mind
that teaching PYHTON for today's technical students will help them in the future, because this
technology is used all over the world. Currently this language is being used by much industry.
As the technology grows, there is a need to adopt them and help students to learn about
them as well.
This change is in line with global trends, as even premier institutions such as Massachusetts
Institute of Technology offer PYTHON instead of C++, as part of their syllabus.
Python is probably one of the few programming languages, which are both simple and
powerful. This is good for both and beginners as well as experts, and more importantly, are
fun to program with. This book aims to help you learn this wonderful language and show how
to get things done quickly and painlessly - in effect.
This book will make you comfortable with basics of Python programming language. This book
provides numerous examples and complete programs. The programs are meant to both
simple and educational. The entire programs have been tested with Python IDLE.
We have worked hard to make sure that the book works well as quick reference.
I am pretty sure despite my strenuous efforts error might remain in the text. I will be grateful if
they could communicate to me any errors they discover.
Nitin Kumar
nitin_k@outlook.com
7. Version: 0.2 7 of 49
1.2 Syllabus
This book is meant for students who chose computer science for their class 11.
Syllabus for class XI is as shown below:
Learning Objectives:
• To understand basics of Computer
• To develop problem solving skills and their implementation through Python (Version:
2.7) To understand and implement the concept of working with relational Database To
understand the basics of Computing Logic
• To understand the basic concepts of Communication and Networking technologies To
understand Open source Software
Competencies:
• The student will develop the following proficiency: Identify Computer components/
Subsystems/ Peripherals Problem Solving using Object Oriented Programming
Database Handling
• Appreciate the logic used in digital circuits
• Identify communication device/ medium and their application
• The Python syllabus for Class 11 is as following.
1. Introduction to Python: 20 Marks (44 Theory+32 Practical Periods)
• Getting Started: Introduction to Python- an interpreted high level language,
interactive mode and script mode
• Variables, Expressions and Statements: Values, Variables and Keywords,
Operators and Operands in Python; (Arithmetic, relational and logical operators),
operator precedence, Expressions and statements (Assignment statement); Taking
input (using raw_input() and input ()) and displaying output (print statement); Putting
comments.
• Functions: Importing Modules (entire module or selected objects), invoking built in
functions, functions from math module (for example, ceil, floor, fabs, exp, log, log10,
pow, sqrt, cos, tan, degrees, radians), using random() and randint() functions of
random module to generate random numbers, composition.
• Defining functions, invoke functions, passing parameters (default parameter values,
keyword arguments), scope of variables, void functions and functions returning
values, flow of execution.
• Conditional constructs and looping: if else statement and while, for (range
function), break, continue, else, pass
2. Programming with Python: 20 marks (50 Theory+44 Practical Periods)
8. Version: 0.2 8 of 49
• Strings: Creating, initializing and accessing the elements; string operators: +, *, in,
not in, range slice [n:m]; comparing strings using relational operators
• String functions and methods: len, capitalize, find, isalnum, isalpha, isdigit,
lower, islower, isupper, upper, lstrip, rstrip.
3. Practical’s:
• Programming in Python: One programming problem in python to be developed
and tested on Computer during the examination. Marks are allotted on the basis of the
following:
1. Logic: 6 Marks
2. Documentation: 2 Marks
3. Output Presentation: 4 Marks
4. Project Work: Problems related to string and List manipulation General Guidelines:
Initial requirement, developing requirement, developing an interface for a user (it is advised to
use text-based interface screen), developing logic for playing the game and developing logic
for scoring points.
1. Hollywood/Hangman: A word guessing game
2. Cows N Bulls: A word/ number guessing game
3. A game to check whether a word does not use any of the forbidden letters. OR
Similar projects may be undertaken in other domains (as mentioned in general guidelines for
project, given at the end of the curriculum in a group of 2-4 students)
5. The Practical File:
Record of the configuration of computer system used by the student in the computer lab (by
exploring inside computer system in the first 2 lab classes) Must have minimum 15 programs
from the topics covered in class 11 course. 5 Programs on Control structures
• 5 Programs on string manipulations
• 5 Programs in list manipulations
6. Viva Voce: Viva will be asked from the syllabus covered in class 11 and the project
developed by the students.
9. Version: 0.2 9 of 49
1.3 About Author
Nitin Kumar is a professional software developer (Currently working for Juniper Networks
and past for Intel security) who loves to use python whenever possible. His current projects
include developing open source for Junos operating system. With Intel security he was
involved in developing Automation framework in Python for an Antivirus application. In past
got to work for Automating Printing applications and to create interface for telecom product in
Python.
Apart from these worked on hooking windows APIs, different application like Facebook,
Google using Python only.
He was a Speaker in Python conference (PyCon) Bangalore in 2010 with topic “Automation
using Python”. He also presented different whitepaper for Patents and Ideas. He also visited
few colleges to give workshop on Python.
He did his bachelor of engineering in Electronics and communication from National Institute
of Technology, Patna in 2006.
He can be reached out at nitin.nitp@gmail.com or nitin_k@outlook.com
1.4 Acknowledgment and Credit
Although this book represents many hours of work on our part, there are many other without
whom we would have failed.
First and foremost is Guido van Rossum, Python’s creator. We are glad he created such a
cool language and that many others have joined him along the way. Then my family for giving
me spare time to write this book and encouraging for the same.
Many thanks to all the companies who let me work aggressively on Python for so long period.
I am grateful to my teammates Nitin and Shailendra for reviewing my Paper and helping with
valuable feedbacks.
1.5 Organisation
This document is organised in three sections. The first section focuses on covering CBSE
syllabus.
The second section focuses on the more number of exercises to give student more command
for each topic.
The third chapter gives hint and answer for each chapter exercise.
10. Version: 0.2 10 of 49
1.6 Typographic Conventions
In this document, the typographic conventions listed in Table P-1 are used.
Table P-1: Typographic Conventions
Typeface or Symbol Meaning/Used for Example
This is official Python programming language
symbol.
This logo is a trademark of the Python
Software Foundation
Will be used to represent
Python Language.
This too will represent
python language.
>>> Python interpreter console >>> 2+2
... Interactive/Interpreter console for continues
code. Say second line of code in function
>>> if x%2==0:
... print 'it is even number'
11. Version: 0.2 11 of 49
2 Introduction to Python
2.1 About Python
As stated by official python website www.python.org “Python is a programming
language that lets you work more quickly and integrate your systems more
effectively. You can learn to use Python and see almost immediate gains in
productivity and lower maintenance costs.”
Python is an easy to learn, powerful programming language. It has efficient high-level data
structures and a simple but effective approach to object-oriented programming. Python’s
elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal
language for scripting and rapid application development in many areas on most platforms.
The Python interpreter and the extensive standard library are freely available in source or
binary form for all major platforms from the Python Web site, http://www.python.org/, and can
be freely distributed. The same site also contains distributions of and pointers to many free
third party Python modules, programs and tools, and additional documentation.
Python is probably the easiest-to-learn and nicest-to-use programming language in
widespread use. Python code is clear to read and write, and it is concise without being
cryptic. Python is a very expressive language, which means that we can usually write far
fewer lines of Python code than would be required for an equivalent application written in,
say, C++ or Java.
Python is a cross-platform language: In general, the same Python program can be run on
Windows and Unix-like systems such as Linux, BSD, and Mac OS X, simply by copying the
file or files that make up the program to the target machine, with no “building” or compiling
necessary. This tutorial introduces the reader informally to the basic concepts and features of
the Python language and system.
It helps to have a Python interpreter handy for hands-on experience, but all examples are
self-contained, so the tutorial can be read off-line as well.
After reading it, you will be able to read and write Python modules and programs, and you will
be ready to learn more about the various Python library modules described in the Python
Library Reference.
Note
Guido van Rossum, the creator of the Python language, named the language after the BBC
show "Monty Python's Flying Circus" but not from Python Snake. He doesn't particularly
like snakes that kill animals for food by winding their long bodies around them and crushing
them.
12. Version: 0.2 12 of 49
2.2 History of Python
Python was developed by Guido van Rossum and it finally appeared in 1991. Python
released 1.0 in 1994 and currently we have 2.7 and 3.3. (In this book we will concentrate on
2.7 as that is most widely used and is in the CBSE syllabus.) 3.3 came up with some major
changes with respect to 2.x version. We are not discussing this here as this is off topic for this
book.
A brief about Guido, He worked with Google till 2012 end for Google App
Engine project. Currently he is associated with Dropbox.
Python maintenance/upgrade is taken care by Python software foundation.
Many of the large organizations that make use of Python include Google, Yahoo, NASA,
NetApp, Cisco, Intel, McAfee, Dropbox, VISA, Disney, Youtube, BitTorrent and many more.
2.3 Companies using Python
• makes extensive use of Python in its web search systems, and employs
Python’s creator.
• video sharing service is largely written in Python.
• The popular BitTorrent peer-to-peer file sharing system is a Python program.
• , a Massively Multiplayer Online Game (MMOG), makes extensive use of
Python.
• , Cisco, H P, Qualcomm, and IBM use Python for hardware testing.
• , use Python in the production of animated movies.
• JPMorgan, , Citadel apply Python for financial market forecasting.
• , Los Alamos use Python for scientific programming tasks.
• Surveymoney, , facebook APIs are also among many other companies using
Python
13. Version: 0.2 13 of 49
2.4 Basics of Computer programming
We will be concentrating on basics of computer programming with respect to Python only.
Python is known to be interpreter language.
Programming languages generally fall into one of two categories: Compiled or Interpreted.
Interpreted language is a programming language that avoids explicit program compilation.
The interpreter executes the program source code directly.
Python is Interpreted: This means that it is processed at runtime by the interpreter and you
do not need to compile your program before executing it.
Python is Interactive: This means that you can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
As any machine only understands machine language (Machine code or machine language is
a set of instructions executed directly by computer's central processing unit (CPU)), either of
Interpreter or compiled language finally gets converted to machine code to get executed.
Compiled language code once compiled gets converted into machine language code so is
fast but specific to that machine for which it got compiled. For compiled language, code we
enter is reduced directly to a set of machine-specific instructions before being saved as an
executable file (.exe files).
Interpreter language the code is saved in the same format that we entered or is converted
into intermediate form called byte code. It gets converted into machine code at runtime hence
is slow (as takes some time at runtime to get converted into machine code) but pros is same
piece of code is portable to different machine (as only at runtime it check for machine code to
need to be changed into)
2.4.1 Advantages of Interpreter Language
• Platform independence
• Easy to learn and use
• minimum programming knowledge or experience
• Allows complex tasks to be performed in relatively few steps
• Allows simple creation and editing in a variety of text
editors
• Allows the addition of dynamic and interactive activities to
web pages
• Edit and running of code is fast.
2.4.2 Disadvantages of Interpreter Language
• Usually run quite slowly
• Limited access to low level and speed optimization code.
• Limited commands to run detailed operations on graphics.
14. Version: 0.2 14 of 49
2.4.3 Open source Software
Open-source software (OSS) is computer software with its source code made
available and licensed with an open-source license in which the copyright holder
provides the rights to study, change and distribute the software for free to anyone and
for any purpose. Open-source software is very often developed in a
public, collaborative manner.
CPython, the reference implementation of Python, is free and open source
software and has a community-based development model, as do nearly all of its
alternative implementations. CPython is managed by the non-profit Python Software
Foundation.
2.5 Python Enhancement Proposals (PEPs)
If you are in hurry then can skip this section for now but make sure you come back and read
this. As this defines the grammar of python and also how Python grows.
The PEP process is the primary mechanism for proposing major new features, for collecting
community input on an issue, and for documenting the design decisions that have gone into
Python. Outstanding PEPs are reviewed and commented upon by the Python community and
by Van Rossum, the Python project's Benevolent Dictator for Life (leader / language
architect)
Python's development is conducted largely through the Python Enhancement Proposal (PEP)
process. So we can suggest any change in existing python backend (say for better
implementation or to fix a bug) code or give new code to be included in python library using
PEP.
Depending upon above scenarios PEP can be classified into different keys like:
S - Standards Track PEP
I - Informational PEP
P - Process PEP
Any PEP proposed for change get below level depending on their present state.
A - Accepted proposal
R - Rejected proposal
W - Withdrawn proposal
D - Deferred proposal
F - Final proposal
A - Active proposal
D - Draft proposal
S - Superseded proposal
For more detail can visit link: http://www.python.org/dev/peps/
15. Version: 0.2 15 of 49
Few of the PEPs which we must have a look at:
• PEP 8
• PEP 20
2.5.1 PEP 8
PEP 8 is Process PEP and said to be “Style Guide for Python Code“. This PEP gives coding
conventions for the Python code comprising the standard library in the main Python
distribution.
For more info refer link: http://www.python.org/dev/peps/pep-0008/
2.5.2 PEP 20
PEP 20 is an Informational PEP and is described as “The Zen of Python”. This PEP also
describes PROS of Python language over other languages.
Few of the point in this PEP are:
• Beautiful is better than ugly.
• Explicit is better than implicit.
• Simple is better than complex.
• Complex is better than complicated.
• Flat is better than nested.
• Sparse is better than dense.
• Readability counts.
• Special cases aren't special enough to break the rules.
• Errors should never pass silently.
• There should be one-- and preferably only one --obvious way to do
it.
• Now is better than never.
• If the implementation is hard to explain, it's a bad idea.
• If the implementation is easy to explain, it may be a good idea.
For more info refer to the link: http://www.python.org/dev/peps/pep-0020/
16. Version: 0.2 16 of 49
2.6 First step toward of Python Program
2.6.1 Download and install Python
I am considering we will be using windows.
Installing Python from Python.org (http://www.python.org/)
1. Download the latest Python Windows installer by going to
http://www.python.org/ftp/python/ and selecting the highest version number listed, then
downloading the .exe installer.
2. Double−click the installer, Python−2.xxx.yyy.exe. The name will depend on the version of
Python available when you read this.
3. If you do not have administrative rights on your machine, you can select Advanced
Options, and then choose Non−Admin Install. This just affects where Registry entries and
Start menu shortcuts are created.
4. After the installation is complete, close the installer and select Start−> Programs−>Python
2.7−>IDLE (Python GUI, will discuss little more in detail in next section). You'll see
something like the following:
This will be installed under folder c:python27 (Go through this folder to feel the structure of
installed Python)
(On unix/linux it gets installed at /usr/local/bin/python)
PATH under environment variable append c:python27 to its value so that we can use Python
from the windows command line or different IDE.
2.6.2 Python IDLE
An Integrated Development Environment (IDE) for Python IDLE is a basic editor and
interpreter environment that ships with the standard distribution of Python.
An integrated development environment (IDE) or interactive development environment for
any programming language is a software application that provides comprehensive facilities
to computer programmers for software development. An IDE normally consists of a source
code editor, build automation tools and a debugger. For Python it’s IDLE.
17. Version: 0.2 17 of 49
According to the included README, its main features are:
• Multi-window text editor with syntax highlighting, auto
completion, smart indent and other
• Python shell with syntax highlighting.
• Integrated debugger with stepping, persistent breakpoints, and
call stack visibility.
For beginners IDLE is good IDE, but as we grow some time we feel some feature are missing
in IDLE, but there are many other IDE freely available which gives us more desired features.
Few among them are PyScriptor, IDLEX, komodo, PyDev, PyCharm, PTVS and many more. I
would suggest you to stick to IDLE as it help learn python in better way. Once you have
confidence on writing basic python code, can try PyScriptor or IDLEX as they are one of
favourite one.
As mentioned above IDLE can be launched from Start−> Programs−>Python 2.7−>IDLE.
Now once we have Python ready on our machine, we are ready to write our first program.
Python code can be written using any plain text editor that can load and save text. Python
files normally have an extension of .py (.pyc when .py files are compiles and .pyo when
compiled using optimization). Python code can similarly be written on IDLE.
We will see in just a while how to run a traditional 'Hello World' program in Python. This will
teach you how to write, save and run Python programs.
We can write any code generally in two ways:
• Interactive mode
• Script Mode
2.6.3 Python Interactive Mode
Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory. As new lines are fed
into the interpreter, the fed program is evaluated both in part and in whole.
The >>> is Python's way of telling you that you are in interactive mode. In interactive mode
what you type is immediately run. Try typing 2+2 in. Python will respond with 4. Interactive
mode allows you to test out and see what Python will do. If you ever feel the need to play with
new Python statements, go into interactive mode and try them out.
Interactive mode helps us to run code one by one. (Single to multiple line at a time)
In this mode it prompts for the next command after completing current one with the primary
prompt, usually three greater-than signs ‘>>> ‘. (for continuation lines it prompts with
the secondary prompt, by default three dots ‘...’ which we will see in our next chapters)
18. Version: 0.2 18 of 49
Python Interactive mode looks like
Similarly on command prompt type python and hit enter we will get the below interactive
mode prompt for python.
So on Python IDLE’s Interactive mode “hello world” will look like:
Below we can see few examples of code from Interactive mode. (Note some time we are
using print but not on next statement, still outputs are same, print are necessary when we
want to print any output in script mode, will discuss this in next section).
19. Version: 0.2 19 of 49
Python Interactive mode
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.
>>> print "Hello world"
Hello world
>>> "hello world"
'hello world'
>>> print 2+2
4
>>> 2+2
4
>>> 'Nitin'*5
'NitinNitinNitinNitinNitin'
>>>
2.6.4 Python Script Mode
Now we will see “hello world” our classical first example in script mode. Create a file called
hello.py in a plain text editor (even Windows Notepad is fine), or by opening new page from
IDLE (File->New Window) and save it with name hello.py at your desired location with the
following contents:
The first line is a comment. In Python, comments begin with a # and continue to the end of
the line. (We will explain the rather cryptic comment in a moment.)
The second line is blank—outside quoted strings, Python ignores blank lines, but they are
often useful to humans to break up large blocks of code to make them easier to read. The
third line is Python code. Here, the print function is called with one argument of type str
(string; i.e., a sequence of characters).
To run above code we can call directly from this file using (RUN ->Run Module F5) or just
pressing F5 on this file. This will give below output on IDLE
>>> ================= RESTART ====================
>>>
Hello World
20. Version: 0.2 20 of 49
We can also run the program from command line.
Each statement encountered in a .py file is executed in turn, starting with the first one and
progressing line by line. This is different from some other languages, for example, C++ and
Java, which have a particular function or method with a special name where they start from.
Now say we have below lines in our hello.py file
Hello.py
print 'hello world'
print 2 + 3
'done with addition'
3*2
print 3*3
If we run this file (by any mean as discussed above) we will get below output:
>>>
hello world
5
9
Notice we got only those output that started with print. So in script mode we see output for
only those lines that starts with print but in interactive mode we would get output for all above
lines (give a try yourself). This is just one of the differences between running code in script
and interactive mode python.
21. Version: 0.2 21 of 49
2.6.5 Getting Help
If you need quick information about any function or statement in Python, then you can use the
built-in help functionality. This is very useful especially when using the interpreter prompt. For
example, run help(str) - this displays the help for the str class which is used to store all text
(strings) that you use in your program.
Similarly, you can obtain information about almost anything in Python using help ()
Type "help", "copyright", "credits" or "license" for more
information.
>>> help ('print')
---------
---------
You will notice that I have used quotes to specify 'print' so that Python can understand that I
want to fetch help about 'print' and I am not asking it to print something. Just try this out to
see the output.
22. Version: 0.2 22 of 49
3 Data Types
We will start learning using Python from Interactive mode. Few things which you need to
know while using Interpreter.
Presence of >>> means Interpreter is ready to take our initial input
Presence of … denotes that Interpreter is ready to take our further input. These symbols
keep on coming till our input is over. This symbol we will encounter once we go through
conditional check like if, else, while or functions.
Ex:
>>> for i in range(4):
... print i
...
0
1
2
3
Note: With green colour we are trying to represent output.
Many of the examples in this manual, even those entered at the interactive prompt, include
comments. Comments in Python start with the hash character, ‘#’, and extend to the end of
the physical line.
# Dimension of rectangle (this is the first comment)
Length = 2 # and this is the second comment
BREADTH = 5 # and now a third!
3.1 Variables
The way we assign any variable in Maths or Physics (excluding unit of that data), similarly we
assign any data variable in Python too.
Length = 5
Breadth = 4
g = 9.8
The sequence of characters used to form a variable name (and names for other Python
entities later) is called an identifier or variable. It identifies a Python variable.
• Variables in Python follow the standard nomenclature of an alphanumeric name
beginning in a letter or underscore.
The characters must all be letters, digits, or underscores _, and must start with a letter. In
particular, punctuation and blanks are not allowed.
The following are some examples of valid and invalid identifiers:
Area
volumeOfCube
third_quadrant
AudiA4
23. Version: 0.2 23 of 49
_surnname
_2 #Accepted but this kind of name is
discouraged.
Khert83508054rn #Accepted in Python but this kind of
name is discouraged, as they don’t convey
proper meaning. Also even though length of
identifier is limited to our eagerness but
that doesn’t mean we use very long names
which might look odd.
• There are some restrictions on the character sequence that make up an identifier:
There are some words that are reserved for special use in Python. You may (we will explain
down why May is mentioned here) not use these words as your own identifiers. They are
easy to recognize in Idle, because they are automatically colour orange or some different
colour. For the curious, you may read the full list:
False class finally is return
None continue file for xlambda
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
*There are more than 100 names in the list, so we have omitted most of them and shown
some of important keywords only.
We will get error if we try to assign value to some of these reserved keywords.
>>> for = 5
SyntaxError: invalid syntax
>>>
>>> try = 2
SyntaxError: invalid syntax
We won’t be getting any error if we define some other among above listed reserved keyword
but the functionality of the keyword will get changed and it will be difficult to figure out in our
code downward why the key is not behaving as expected.
>>> file=3
>>> file('log.txt')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
file('log.txt')
TypeError: 'int' object is not callable
See file which is supposed to open a file is behaving like integer as we assigned file
to 3 which is an integer.
So you could redefine some reserved keywords, but you probably should not unless you
really know what you are doing! When you start the editor, we will see how IDLE uses colour
to help you know what identifies are predefined.
• Variable names are case sensitive.
>>> LENGTH = 4
>>> length = 3
>>> Length = 5
24. Version: 0.2 24 of 49
>>> print LENGTH
4
>>> print length
3
>>> print Length
5
As you can notice same variable name with different case behaves differently.
• Variables do not need to be declared and their datatypes are inferred from the
assignment statement.
The way we define any simple variables like int, float in Maths or Physics it’s the same way in
Python also. We need not to give the data type as a prefix or suffix in Python variables.
x = 5
y = 10
z= 3+4j
pie= 3.14
But if we take other examples from Physics or Maths we append unit to define the variable
type, as example shown below.
area = 10 sq mts
vol = 20 cub mts
mass = 2 kg
force = 2 N
power = 5 W
Similarly if you are aware of C++/C we need to prefix the data type.
int width = 5
float pie =3.14
string name = “Guido”
So in Python the variable becomes same data type to which it is being assigned. Ex:
x = 5
As 5 is Integer so variable x data type is Integer (int). Now let
we reassign it to float.
x = 2.3
So this time variable gets converted to float type.
Hello.py
>>> x = 5
>>> type(x)
<type 'int'>
>>> x = 2.3
>>> type(x)
<type 'float'>
25. Version: 0.2 25 of 49
Hello.py
>>> name=”guido”
>>> type(name)
<type 'str'>
Please note that even in Math we define normal variables like integer, float without data type
say to find sum, subtraction, multiplication etc. but other data types like area volume need
data types (unit) suffixed.
X=4
Y=5
Sum=X+Y
Multiple = X*Y
But
Area = X cm * Y cm = Z cm sq
In Python any type of variable don’t need any declaration or suffix of that data type. When we
say any data type its mean integer, float, string or some python specific variable like list,
tuple, dictionary (all these we will read in coming chapter).
X = [2, 3, 4, 6] #list
Y = (4, 5, 75, 53) #tuple
Z = {1:’hello’, 2:’world’} #dictionary
Variable Scope: Most variables in Python are local in scope to their own function or class.
For instance if you define a = 1 within a function, then a will be available within that entire
function but will be undefined in the main program that calls the function. (we will explain this
in function topic)
3.2 Assigning Values to Variables:
Python variables do not have to be explicitly declared to reserve memory space as we do in
C/C++ or other language. The declaration happens automatically when you assign a value to
a variable.
When we say variables reserved memory it’s the memory space which we keep aside to
store the value in our memory space. For example if we define these two variable in C++ we
need to explicitly declare data type (in our examples its int and char) which is prefixed to the
variable.
int x =5
char y = ‘d’
26. Version: 0.2 26 of 49
Then for integer program keep aside 4 byte and for char it keeps aside 1 byte.
To know more about byte and why 4 byte for integer and 1 for character.
In computer language everything is 0 or 1. So a bit is a single numeric value, either '1' or '0',
that encodes a single unit of digital information kept in disk space, or data storage space,
and system memory.
A byte is a sequence of bits; usually eight bits equal one byte.
8 bits [] [] [] [] [] [] [] [] = 1 byte
As one block can be either of 0 or 1 (among 2 values) similarly for all 8 bit block.
2*2*2… 8times = 2^8 = 256. So 1 byte can contain 256 values. So to take care of all
character 1 byte is enough. Do remember we assign memory in Byte not in block. Say even
4 or 5 bit is sufficient to store some data, we will assign such variables with 1 byte of data,
remaining of 3-4 bit will remain empty.
Hence one integer (int) variable with 4 byte can store up to 2^(8 *4) value i.e. 4,294,967,296
As we need not to declare any data type for Python the equal sign (=) is used to assign
values to variables. The operand to the left of the = operator is the name of the variable, and
the operand to the right of the = operator is the value stored in the variable. For example:
x=5
y=2.4
z=”Python”
So when we assign value 5 to x, Python read it from right to left (<-). Now as it notices
that 5 is to be assigned to the variable x. As 5 is integer it will store 5 in memory and will
assign the reference to this int object memory to x. hence x is the pointing to the memory
location containing 5. Similarly it works for other variables too.
>>> x=5
>>> id(x)
19561000
>>> x=7
>>> id(x)
19560976
When we assign x to 5, 5 get saved to some memory location (19561000 in our case). So x
reference to this memory location (19561000) of int data 5, once we change x to 7, x start
referencing to the memory location (19560976) where 7 is saved.
The syntax is simply objectReference = value. The
= operator binds an object reference to an
object in memory. If the object reference already exists, it is simply re-bound to refer to the
object on the right of the = operator; if the object reference does not exist it is created by the
= operator. We will try to understand this by an example.
>>> x=5
>>> id(x)
X
5
7
The circles represent object
references.
The rectangles represent
objects in memory.
27. Version: 0.2 27 of 49
20216360
>>> y=5
>>> id(x)
20216360
In above example say if 5 object is not there in memory it gets created at memory location
20216360 and assigned to x. In next step when y is assigned to 5 and as 5 is already in
memory y get assigned to same int object data. Can be made out by same id value of x and
y.
id(object)
Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to
be unique and constant for this object during its lifetime
(Hint: it's the object's memory address.). So we can use If to get the memory location of any
data or variable reference.
3.3 Standard Data Types:
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has
various standard types that are used to define the operations possible on them and the
storage method for each of them.
Python has mainly five standard data types:
• Numbers
• String
• List
• Tuple
• Dictionary
3.3.1 Numbers
Python has fort built-in numeric data types: integers, long integers, float and complex
number.
In addition, Booleans are a subtype of plain integers.
3.3.1.1 Integers
We have already discussed in topic “assigning values to variables” how bit/byte is used to
assign values.
Python uses 4 byte (4*8=32 bits) to store an Integer. One bit can contain 0 or 1 (2 value).
Hence 32 bits can contain 2*2*2…….32 times or 2^32=4294967296.
So integer can have 4294967296 values. As integer can be +ve as well as –ve numbers so
integer are whole numbers in the range of -2147483648 to 0 to 2147483647 (2147483648 –
ve values + 1 zero + 2147483647 +ve value = 4294967296)
28. Version: 0.2 28 of 49
Plain integers (also just called integers) are implemented using long in C, which gives them
at least 32 bits of precision
In addition to writing integers in the default decimal (base 10) notation we can also write
integer in hexadecimal (base 16) and octal (base 8) notation by
>>> 100 #100 in decimal format
100
>>> 0144 #100 in octal format
100
>>> 0x64 #100 in hexadecimal format
100
From previous math’s classes you might be aware that for decimal number, valid digits are
0 through 9. For hexadecimal it’s 0 through 9 and A to F and for octal it’s 0 through 7. If you
are not familiar with hexadecimal and octal numbering system, or if you are but they don’t
excite you, then no need to panic and keep moving.
Table P-2 Standard data Operations
Operation Result Examples Notes
x + y sum of x and y 2+2=4
2+1.1=3.1
42L + 3=45L
(2+3j) + (4+2j)= (6+5j)
x - y difference of x and y 4-3=1
3.3-1.1=2.2
45L-10L=35L
(6+5j) - 3j=(6+2j)
x * y product of x and y 3*2=6
2.1*4=8.4
1.1*1.1=1.21
(2+3j)*(4+2j)= (2+16j)
x / y quotient of x and y 4/2=2, 5/2=2
6.4/1.6=4.0, 6.4/2=3.2
(6+5j)/(2+1j)= (3.4+0.8j)
(1)
x // y (floored) quotient of x and y 7//2=3, 6//4=1 (2)
x % y remainder of x / y 7%2=1
-x x negated
29. Version: 0.2 29 of 49
+x x unchanged
abs(x) absolute value or magnitude
of x
abs(-3)=3
int(x) x converted to integer int(2.3)=2, int('2')=2
long(x) x converted to long integer long(2.3)=2L,long(4)=4L
float(x) x converted to floating point
complex(re,im) a complex number with real
part re, imaginary
part im. im defaults to zero.
complex(2,3)= (2+3j)
c.conjugate() conjugate of the complex
number c
(2+3j).conjugate()=(2-3j)
divmod(x, y) the pair (x // y, x % y) divmod(7,3)= (2, 1)
pow(x, y) x to the power y pow(2,3)=8
hex(x) hexadecimal representation of x
as a string
hex(2)= '0x2'
*0x denotes hexadecimal
bin(x) binary representation of int x
as a string
bin(5)= '0b101'
*0b denotes binary
Notes:
(1) For (plain or long) integer division, the result is an integer. The result is always
rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note
that the result is a long integer if either operand is a long integer, regardless of the
numeric value.
(2) Also referred to as integer division. The resultant value is a whole integer, though
result type is not necessarily be integer.
Whenever there are arithmetic operations between different data types, then the output/result
of such mixed mode operations are summarized in below table.
Table P-3 Results of mixed mode Operations
LHO
RHO
Int Float Long
Int Int Float Long
Float Float Float Float
Long Long Float Long
30. Version: 0.2 30 of 49
RHO: Right hand operand
LHO: Left hand operand
So it’s clear from above chart the priority order goes down from Float->Long->int. Said that if
we have int or long being calculated with float output will be a float only.
3.3.1.2 Floats
Floats are real number (that is, a number that can contain a fractional part). The following are
floating-point numbers:
2.3, -23.4, 1/3, 3e-4 (0.0003)
Floating point number are implemented using double in C
>>> x=2.1
3.3.1.3 Long Integers
Long integers are similar to integers which are beyond integer limit. Minimum and maximum
value of long integers depends on machine architecture; say 64 bit machine’s long integer
limit will be more than 32 bit machine.
Above in integer topic we got to know that integer can have value from -2147483648 to
2147483647. So any integer value outside this limit will be a long integer.
Even if you try to save a value outside this limit as integer it will get converted into long.
>>> x=2147483650
>>> x
2147483650L
>>>
To differentiate between integer and Long Integers we append an upper “L” or lower “l” to end
of Long Integers.
Even though Python allows you to use a lowercase L with long, but it is recommended that
you use only an uppercase L to avoid confusion with the number 1.
Python always displays long integers with an uppercase L even if we had defined it using
lowercase “l”.
>>> x=214748365l
>>> x
214748365L
Note: In python 3.x, Int and Long has been merged to single data type Int.
3.3.1.4 Complex Numbers
Complex numbers are of the form p + qJ, where p and q are floats and J (or j) represents the
square root of -1 (which is an imaginary number). p is the real part of the number, and q is
the imaginary part. Complex numbers are not used much in Python programming.
31. Version: 0.2 31 of 49
The complex data types are those data that holds a pair of floats, one representing the real
part and the other the imaginary part of a complex number. Literal complex numbers are
written with the real and imaginary parts joined by a + or - sign, and with the imaginary part
followed by a j. Here are few examples: 3.7+4j, 0.1j, 5+0j, -3-1.2j.
The separate parts of a complex are available as attributes real and imag. Below example
shows the use of real and imag. Also do take care that even if we provide real or imaginary
value with integer data, python takes it as float only.
>>> x=2+3j
>>> x.real
2.0
>>> x.imag
3.0
>>>
Note: Python float has been designed on top of complex number only. Say if we have a
float variable with value 2.1 then you can consider it as complex number 2.1 + 0.0J. Or
we can say float is a complex number with imaginary part.
>>> x=2.1
>>> x.real
2.1
>>> x.imag
0.0
3.3.1.5 Booleans
In Python from version 2.3 onward, there is a bool type which is a part (subclass) of int, the
standard integer type. It has two possible values: True and False (Do take care of capital T
and F, we most often do mistake here), which are "special versions" of 1 and 0 respectively
and behave as such in arithmetic contexts.
>>> False==0
True
>>> True==1
True
>>> 2*2==4
True
3.3.2 Number Data Type Conversion:
Python provides internal function which can be used to convert one data type to other. See
below examples. It was also covered in table P2.
Use int(x) to convert x to a plain integer.
• int(3.4) = 3
Use long(x) to convert x to a long integer.
• long(34) = 34L, long(3.4)=3L
Use float(x) to convert x to a floating-point number.
• float(200)=200.0, float(45L)=45.0
Use complex(x) to convert x to a complex number with real part x and imaginary part
zero.
• complex(4)=(4+0j)
32. Version: 0.2 32 of 49
Use complex(x, y) to convert x and y to a complex number with real part x and
imaginary part y. x and y are numeric expressions
• complex(4,3)=(4+3j), complex(4.1,3.4)=(4.1+3.4j)
3.3.3 Boolean Operations:
Operation Results Examples Notes
x or y if x is false, then y, else x 2 or 3 = 2, 0 or 5 = 5 (1)
x and y
if x is false, then x, else y
0 and 5 = 0, 1 and 5
= 5
(1)
not x
if x is false, then True,
else False
not 1 = False, not 0 =
True, not 5 = False (2)
Notes:
(1) These only evaluate their second argument if needed for their outcome.
(2) "not" has a lower priority than non-Boolean operators, so not a == b is interpreted
as not (a == b), and a == not b is a syntax error.
3.3.4 Important Numeric Exceptions
TypeError
Raised on application of arithmetic operation to non-number
>>> 2 + 'python'
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
2 + 'python'
TypeError: unsupported operand type(s) for +: 'int' and
'str'
ZeroDivisionError
Raised when zero second argument of div or modulo op. Example:
>>> 3/0
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
3/0
ZeroDivisionError: integer division or modulo by zero
Different other data types like list, tuple, dictionary, string we will be doing in next chapter.
33. Version: 0.2 33 of 49
4 Collection Data Types
All those simple data which we came across in last chapter are common to many other
programming languages but still you won’t find it that easy to use the way we can in Python.
Data types that we will be covering in this chapter will differentiate Python from other languages
like C++/Java. Even though we will try to compare these data types with some in C/C++ but you
can easily make out how easy it is easy to use here in Python.
Lists, Tuple, String are python inbuilt sequence/collection data types. We will go through all of
them one by one and
also
introduce
new
collection
data
types
sets
and
dictionaries
Before we go into other important data types like List, tuple, string, Dictionary, I would like to
revise few import python keywords. These keywords we will be using more frequently and
these key word help in learning python in better way.
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among simultaneously
existing objects. (Hint: it's the object's memory address.)
help(…)
We can use help(object) for help about object. It gives the documentation about that object.
type(object)
This function gives the data type for data passed to the function. Ex:
>>> type(2)
<type 'int'>
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope. Else, return an
alphabetized list of names comprising (some of) the attributes of the given object, and of
attributes reachable from it.
it returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes of its bases.
for any other object: its attributes, its class's attributes, and recursively the attributes of
its class's base classes.
In basic terms dir([object]) will tell about what all functions we can use related to our
variable. You will understand it better once we have an example for the same.
34. Version: 0.2 34 of 49
4.1 List
Python knows a number of compound data types, used to group together other values. The
most versatile is the list, which can be written as a list of comma-separated values (items)
between square brackets. List items need not all have the same type.
We can take different data together inside square bracket separated by comma to create a
list.
>>> x = [ ] #an empty list
>>> x = [2,4,5,32,1] #list containing only integers
>>> x = [5, 4.3, 3+4j, 'python', 32] #list containing different data types
To compare with Math, it looks like matrix with one row but can contain different data
types.
You can verify whether the variable (in our above examples its x) is list or not using python
builtin type function.
>>> x = [5, 4.3, 3+4j, 'python', 32]
>>> type(x)
<type 'list'> #This tells us that x is a list.
4.1.1 Indexing
By this time we might have question in our mind how to use data inside list.
List elements can be accessed using their index location. List indices start at 0
Say if we have a list x.
>>> x = [5, 4.3, 3+4j, 'python', 32]
Then each element inside this list can be indexed like below
0 1 2 3 4
5 4.3 3+4j ‘python’ 32
-5 -4 -3 -2 -1
To access any element at specific index we need to use the list data variable (x in our case)
and index value inside a square bracket. Say to access first value (ie 5) we can do it this way
>>> x[0] #access 1
st
element using index 0
5
35. Version: 0.2 35 of 49
>>> x[1] #access 2
nd
element with index 1
4.3
>>> x[2]
3+4j
>>> x[3]
‘python’
>>> x[4] #access last (5
th
) element with index 4
32
Similarly we can also access data using negative indexing. Do remember we don’t have
anythin called -0 index. Negative index starts with -1.
>>> x[-1] #access last element using index -1, its same as x[4]
32
>>> x[-2] #access 2
nd
last element with index -2, same as x[3]
‘python’
>>> x[2]
3+4j
>>> x[3]
‘python’
>>> x[-5] #access 1
st
element with index -5, same value as x[0]
32
If we use index which is outside the range of given list we get an exception (IndexError) as
there is no value assigned with respect to that index.
>>> x[6]
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
x[6]
IndexError: list index out of range
>>> x[-7]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
x[-7]
IndexError: list index out of range
4.1.2 List Slicing
Till now we were able to access single element of list. But using slicing we can fetch more
data at a time. We can specify slice in the form x[start:end]. Start is including but end is
excluding. Said that if we do x[start:end] will give is list elements starting from given index
start till given index value end (end index value is excluded).
>>> x = [4, 3, 5, 2, 23, 9, 12, 0, 2] #list with length 9
>>> x[1:4]
[3, 5, 2] #from index 1 to 3. i.e. x[1],x[2], x[3] not x[4]
36. Version: 0.2 36 of 49
>>> x[0:4] #slicing from starting
[4, 3, 5, 2]
>>> x[2:9] #slicing till end
[5, 2, 23, 9, 12, 0, 2]
Start and end parameter are both optional. x[0:4] can also be written as x[:4] and x[2:9] as
x[2:]
>>> x[:4] #slicing from starting with optional parameter
[4, 3, 5, 2]
>>> x[2:] #slicing till end with optional parameter at end
[5, 2, 23, 9, 12, 0, 2]
Python silently take care of invalid entry if possible. Say if we provide index out of range then
it will consider index till end point.
>>> x[3:25] #slicing till end even though we provided index out of range
[2, 23, 9, 12, 0, 2]
>>> x[-34:4] #slicing from starting point as -34 is beyond index point -9 (i.e 0 starting point).
So python consider this as x[-9:4] without giving any error/exception.
[4, 3, 5, 2]
We can also pass third parameter to list slicing. Third parameter gives alternate items
depending on the value of third parameter.
Ex:
>>> x = [4, 3, 5, 2, 23, 9, 12, 0, 2] #list with length 9
>>> x[1:4]
>>> x[::2] #get every alternate item, starting with the first
[4, 5, 23, 12, 2]
>>> x[1::2] #get every alternate item, starting with 2
nd
elem
[3, 2, 9, 0]
>>> x[0:5:2]
[4, 5, 23]
>>> x[0:8:3] #get every 3
rd
alternate item, starting with 1
st
element.
[4, 2, 12]
We will put all above things in a table so that it’s easy to go through them easily in one view.
4.1.3 Operators on list
37. Version: 0.2 37 of 49
Operator Definition Example
len(x) Length of x x=[4, 3, 5, 2, 23, 9, 12]
len(x) >>> 7
min(x) Smallest item of x x=[4, 3, 5, 2, 23, 9, 12]
min(x) >>> 2
max(x) Largest item of x x=[4, 3, 5, 2, 23, 9, 12]
max(x) >>> 23
i in x True if an item i is there in list x
else False.
x=[4, 3, 5, 2, 23, 9, 12]
3 in x >>> True
i not in x True if an item i is not there in list
x else False.
x=[4, 3, 5, 2, 23, 9, 12]
3 not in x >>> False
x + y The concatenation of two list x
and y.
[12,56] + [34, 45] >>> [12,
56, 34, 45]
x*n, n*x n copies of x concatenated [1,2]*3 = [1, 2, 1, 2, 1, 2]
3*[2,1] >>> [2, 1, 2, 1, 2, 1]
x[i] i'th item of x, origin 0 x=[4, 3, 5, 2, 23, 9, 12]
x[0] >>> 4
x[i:j] slice of x from i to j, slice from
index i up to but not including
index j. i defaults to 0, j to len(s)
x=[4, 3, 5, 2, 23, 9, 12]
x[1:4] >>> [3, 5, 2]
x[4:] >>> [23, 9, 12]
x[:4] >>> [3,5,2]
Below operators are specific to Lists (mutable sequences). These operators
changes the original list (in our case x)
x[i]=data Item I of x is replaced by data x=[4, 3, 5, 2, 23, 9, 12]
x[0]=10
>>> x
[10, 3, 5, 2, 23, 9, 12]
x[i:j] = data slice of x from i to j is replaced by
data
x=[4, 3, 5, 2, 23, 9, 12]
x[1:4]=[56,43]
>>> x
[4, 56, 43, 23, 9, 12]
del x[i:j] delete slice (same as x[i:j] = []) x=[4, 56, 43, 23, 9, 12]
>>> del x[2:4]
38. Version: 0.2 38 of 49
>>> x
[4, 56, 9, 12]
4.1.4 Methods of list Objects
As discussed earlier python has internal function names dir that will list down all the function
or other attribute related to given object.
>>> x=[4, 3, 5, 2, 23, 9, 12]
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
This list consists of some functions with name having double underscore (_) at prefix and
suffix. These are the functions, which are used to define the internal property of the object.
We are not supposed to use them unless we want to change the behaviour of that data type.
For ex, when we do [2,5] +[23,32,12] we get [2,5,23,32,12] this we get when list internally
calls __add__ function. Similarly other functions serve their own purpose.
>>> x=[2,5]
>>> y=[23,32,12]
>>> x+y
[2, 5, 23, 32, 12]
>>> x.__add__(y) #equivalent of x + y
[2, 5, 23, 32, 12]
Other functions (which are highlighted in bold) are normal functions, which are meant for
general use. We will list down these function and respective examples in below table.
Function Definition Example
x.append(y) Append y to the end. >>> x=[2, 5, 23, 32, 12]
>>> x.append(45)
>>> x
[2, 5, 23, 32, 12, 45]
x.count(value)
-> integer
Return number of occurrences
of value
>>> x=[2, 5, 23, 32, 12, 5]
>>> x.count(5)
2
39. Version: 0.2 39 of 49
x.extend(iterable) Extend list by appending
elements from the iterable.
Iterable can be list, tuple, string
etc
>>> x.extend([54,24])
>>> x
[2, 5, 23, 32, 12, 5, 54, 24]
x.index(value,
[start, [stop]])
Return first index of value.
Raises ValueError if the value is
not present.
Start and stop are optional
parameter. If these parameters
are used, function will look from
the start position till the stop
position.
Even in this case output will be
the original index of element not
the count from start location.
Note: If parameter of a function
is shown in [ ] that means that
parameter is optional. If it is like
[a, [b]] one square bracket
inside other, that means either
we can pass just a or we have
to pass a, b. Square bracket
shown in definition does not
mean that you should type
square brackets at that position
while calling it.
>>> x.index(23) #looking for
23 in our list
2 #3
rd
position
>>> x.index(5)
1
#with start stop parameter
#Here it starts looking from
position 4(index 3)
>>> x.index(5,3)
4 #location of 2
nd
5 in list
>>> x.index(5,3,7)
4 #original index count of
2
nd
5. Its not the count from
index 3 (start parameter)
>>> x.index(57)
ValueError: 57 is not in list
x.insert(index,
object)
Insert object before index.
Function will insert object at
given index and move all
followed elements to next
location.
>>> x=[2, 5, 23, 32, 5]
#adding 10 at index 2(3
rd
position)
>>> x.insert(2,10)
>>> x
[2, 5, 10, 23, 32, 5]
x.pop([index]) Remove and return item at
index (default last).
*As index is in [ ], it’s an optional
parameter. By default pop will
return last element.
Raises IndexError if list is empty
or index is out of range.
x = [2, 5, 10, 23, 32, 5]
>>> x.pop()
5 #returns last
element when pop is not
given any parameter.
>>> x #5 is removed
from x
[2, 5, 10, 23, 32]
>>> x.pop(2) #calling with
optional index parameter.
10 #removed from 3
rd
position (index value 2)
40. Version: 0.2 40 of 49
>>> x #10 is removed from
list.
[2, 5, 23, 32]
x.remove(value) Remove first occurrence of
value.
Raises ValueError if the value is
not present.
>>> x=[2, 5, 23, 32, 12, 45]
>>> x.remove(23)
>>> x
[2, 5, 32, 12, 45]
>>> x.remove(100)
ValueError: list.remove(x): x
not in list
x.sort() Sort the items of the list, in
place.
>>> x = [6.5, 233, 433, 11,
65.5]
>>> x.sort()
>>> x
[6.5, 11, 65.5, 233, 433]
4.1.5 Important List Exception
IndexError
IndexError is raised on providing out-of-range index to given list.
>>> x=[2,5,3]
>>> x[6]
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
x[6]
IndexError: list index out of range
ValueError
ValueError is raised with some functions when the value being looked for is not present in
the list.
>>> x=[2,5,3]
>>> x.index(23)
Traceback (most recent call last):
File "<pyshell#**>", line 1, in <module>
x.index(23)
ValueError: 23 is not in list
>>> x.remove(12)
Traceback (most recent call last):
File "<pyshell#**>", line 1, in <module>
x.remove(12)
ValueError: list.remove(x): x not in list
AttributeError
41. Version: 0.2 41 of 49
AttributeError is raised when an attribute reference or assignment fails. In below
example we are trying to use “upper”
>>> x=[2,5,3]
>>> x.upper()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x.upper()
AttributeError: 'list' object has no attribute 'upper'
4.2 Tuple
A tuple like List is an ordered sequence of zero or more data elements (object references).
The difference is that tuple is immutable i.e. it cannot be modified. Tuples support the same
slicing and packing syntax as List.
Creating tuple is also similar to creating a List. The difference being in case of List we use
square bracket while in tuple you use parentheses.
x = (23, 43, 54, 56) #tuple containing only integer data
x = (34, ‘python’, 2.7) #tuple with int, string, float data types
x = (578, [23, 345, 657], (7, 3)) #tuple can also contain list, tuple as its element
x = () #empty tuple
x = (3,) #tuple with one element
We need to notice tuple with just one element. Such tuple should have a trailing comma.
Otherwise the variable (in our case x) is of the data type that is there inside the parenthesis.
>>> x = (3) #this is not tuple, x will be assigned with 3, hence x data type is int.
>>> type(x)
<type 'int'>
>>> x = (3,) #this is tuple with one data.
>>> type(x)
<type 'tuple'>
One more way to input tuple to a variable is as shown below.
>>> x = 2, 3.5, ‘abc’
Is equivalent to
>>> x = (2, 3.5, ‘abc’)
Python also provide keyword tuple(sequence) to convert other sequence type data to tuple
data. Sequence can be list, string.
42. Version: 0.2 42 of 49
>>> x=[2,3,4,6]
>>> type(x)
<type 'list'>
>>> y=tuple(x)
>>> y
(2, 3, 4, 6)
>>> type(y)
<type 'tuple'>
4.2.1 Operators on Tuple
Operators on tuple behave similar to list.
Operator Definition Example
len(x) Length of x x=(4, 3, 5, 2, 23, 9, 12)
len(x) >>> 7
min(x) Smallest item of x x=(4, 3, 5, 2, 23, 9, 12)
min(x) >>> 2
max(x) Largest item of x x=(4, 3, 5, 2, 23, 9, 12)
max(x) >>> 23
i in x True if an item i is there in tuple
x else False.
x=(4, 3, 5, 2, 23, 9, 12)
3 in x >>> True
i not in x True if an item i is not there in
tuple x else False.
x=(4, 3, 5, 2, 23, 9, 12)
3 not in x >>> False
x + y The concatenation of two tuple x
and y. Will create new tuple
(12,56) + (34, 45) >>> (12,
56, 34, 45)
x*n, n*x n copies of x concatenated (1,2)*3 = (1, 2, 1, 2, 1, 2)
3*(2,1) = (2, 1, 2, 1, 2, 1)
x[i] i'th item of x, origin 0 x=(4, 3, 5, 2, 23, 9, 12)
x[0] >>> 4
x[i:j] slice of x from i to j, slice from
index i up to but not including
index j. i defaults to 0, j to len(s)
x=(4, 3, 5, 2, 23, 9, 12)
x[1:4] >>> (3, 5, 2)
43. Version: 0.2 43 of 49
x[4:] >>> (23, 9, 12)
x[:4] >>> (3,5,2)
Tuple slicing behaviour is
similar to those of list. For
more detail follow list slicing.
As tuple is immutable data type hence we won’t have those operators, which can
change the tuple variable as we can in case of list. We will get exception if we try
such operations we get Exception.
**Below operators are works with Lists (mutable sequences). These operators
changes the original list (in our case x)
x[i]=data Trying to replace ith value of x
tuple.
x=(4, 3, 5, 2, 23, 9, 12)
x[0]=10
Traceback (most
recent call last):
File
"<pyshell#17>", line
1, in <module>
x[0]=10
TypeError: 'tuple'
object does not
support item
assignment
x[i:j] = data Trying slicing of x from i to j to
replace by given data.
x=(4, 3, 5, 2, 23, 9, 12)
x[1:4]=(56,43)
Traceback (most
recent call last):
File "<pyshell#22>",
line 1, in <module>
x[1:4]=(56,43)
TypeError: 'tuple'
object does not
support item
assignment
del x[i:j] Trying to Delete slice (same as
x[i:j] = [])
x=(4, 56, 43, 23, 9, 12)
>>> del x[2:4]
Traceback (most
recent call last):
File
"<pyshell#23>", line
1, in <module>
del x[2:4]
TypeError: 'tuple'
object does not
support item deletion
44. Version: 0.2 44 of 49
4.2.2 Methods of Tuple Objects
As discussed in details under section Methods of list Objects inbuilt python function dir gives
all the functions related to an object. We can notice here too we have some internal functions
(with pre and post double underscores). Apart from those we have just 2 functions for our
use. count and index.
If we have a look to functions for list object we had:
append, extend, insert, pop, remove, reverse, sort
and
count, index
As tuple is immutable data types, which cannot be changed, hence we don’t have 1
st
set of
functions, which are meant for changing the variable. For ex pop used to remove one
element from the list and lead to change the list.
>>> x=[4, ‘abc’, 5, 2.1, 23, 9, 12] #x is list here
>>> x.pop()
12
>>> print x
[4, 'abc', 5, 2.1, 23, 9]
12 is removed from x. Such kind of operation can’t be used on immutable data types, hence
we don’t see those function on doing dir of tuple variable. The functionality if count and index
is such that they won’t change the variable hence we have them with tuple too.
>>> x=(4, ‘abc’, 5, 2.1, 23, 9, 12)
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__',
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'count', 'index']
Function Definition Example
x.count(value)
-> integer
Return number of
occurrences of value
**wont change the x
>>> x=(2, 5, 23, 32, 12, 5)
>>> x.count(5)
2
x.index(value, [start,
[stop]])
Return first index of value.
Raises ValueError if the value
is not present.
Start and stop are optional
parameter. If these
parameters are used,
>>> x.index(23) #looking
for 23 in our list
2 #3
rd
position
>>> x.index(5)
1
45. Version: 0.2 45 of 49
function will look from the
start position till the stop
position.
Even in this case output will
be the original index of
element not the count from
start location.
Note: If parameter of a
function is shown in [ ] inside
function defination that
means that parameter is
optional. If it is like [a, [b]] one
square bracket inside other,
that means either we can
pass just a or we have to
pass a, b. Square bracket
shown in definition does not
mean that you should type
square brackets at that
position while calling it.
#with start stop parameter
#Here it starts looking from
position 4(index 3)
>>> x.index(5,3)
4 #location of 2
nd
5 in list
>>> x.index(5,3,7)
4 #original index count of
2
nd
5. Its not the count from
index 3 (start parameter)
>>> x.index(57)
ValueError: 57 is not in list
4.2.3 Important Tuple Exception
Similar to list we too have:
IndexError
IndexError is raised on providing out-of-range index to given tuple.
>>> x=(‘abc’,5, 3.9, 3)
>>> x[6]
Traceback (most recent call last):
File "<pyshell#**>", line 1, in <module>
x[6]
IndexError: tuple index out of range
ValueError
ValueError is raised with some functions when the value being looked for is not present in
the tuple.
>>> x=(2,5,3)
>>> x.index(23)
Traceback (most recent call last):
File "<pyshell#**>", line 1, in <module>
x.index(23)
ValueError: tuple.index(x): x not in tuple
46. Version: 0.2 46 of 49
AttributeError
AttributeError is raised when an attribute reference or assignment fails. In below
example we are trying to use “upper”
>>> x=(2,5,3)
>>> x.upper()
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x.upper()
AttributeError: 'tuple' object has no attribute 'upper'
We do need to take care that we might sometime try out the functions meant for list
such as remove, append on tuple. These functions too will give AttributeError.
>>> x=(2,5,3)
>>> x.append(8)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
x.append(8)
AttributeError: 'tuple' object has no attribute 'append'
4.3 String
Coming sortly…………………….
47. Version: 0.2 47 of 49
Glossary and Abbreviations
Term Description
API Application Programming Interface
IDLE Integrated development environment
49. Version: 0.2 49 of 49
Version History
Version Status Date Details of Changes Author(s)
0.1 DRAFT 24/12/2013 Initial Draft Nitin Kumar
0.2 DRAFT 14/06/2014 Initial Draft Nitin Kumar