[Go to site: main page, start]

0% found this document useful (0 votes)
2 views15 pages

Chapter1 Python Notes

Chapter 1 introduces Python, a powerful and easy-to-learn programming language developed by Guido Van Rossum in 1991. It discusses the advantages of Python, such as its simplicity, expressiveness, and cross-platform capabilities, as well as its limitations, including slower execution speed and fewer libraries compared to other languages. The chapter also covers how to work in Python using different modes and environments, including interactive and script modes, and provides a simple example of a 'Hello World' program.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Chapter1 Python Notes

Chapter 1 introduces Python, a powerful and easy-to-learn programming language developed by Guido Van Rossum in 1991. It discusses the advantages of Python, such as its simplicity, expressiveness, and cross-platform capabilities, as well as its limitations, including slower execution speed and fewer libraries compared to other languages. The chapter also covers how to work in Python using different modes and environments, including interactive and script modes, and provides a simple example of a 'Hello World' program.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CHAPTER 1

Getting Started with Python


Computer Science with Python – Class XI | Sumita Arora
Full Notes with Solved Exercises & CBSE-Style Answers

📚 Topics Covered in This Chapter


• 1.1 Introduction to Python
• 1.2 Python – Pluses (Advantages)
• 1.3 Python – Some Minuses (Limitations)
• 1.4 Working in Python (Interactive & Script Mode)
• 1.5 Understanding First Program / Script

1.1 INTRODUCTION
The word Python was chosen for this language NOT because of the reptile but after the famous BBC
comedy show Monty Python's Flying Circus.
Python programming language was developed by Guido Van Rossum in February 1991.
Python is based on / influenced by two programming languages:
• ABC language – a teaching language created as a replacement of BASIC, and
• Modula-3

Python is an
easy-to-learn yet powerful object-oriented programming language. It is a very high-level
language yet as powerful as many other middle-level languages like C, C++, Java etc.
📝 NOTE: Python was 4th most popular programming language as per February 2013 popularity
index, after Java, PHP and C#.
1.2 PYTHON – PLUSES (ADVANTAGES)
Though Python came into being in early 1990's, it competes with ever-popular languages. It has many
strengths that make it a good choice for many situations.

1. Easy to Use
Python is compact and very easy to use object oriented language with very simple syntax rules. It is a
very high-level language and thus very programmer-friendly.

2. Expressive Language
Python's expressiveness means it is more capable to expressing the code's purpose than many other
languages. Reason: fewer lines of code, simpler syntax.
Example – Swapping values in C++ vs Python:
// In C++ : Swap Values
int a = 2, b = 3, tmp;
tmp = a;
a = b;
b = tmp;

# In Python : Swap values


a, b = 2, 3
a, b = b, a
Python achieves the same with just 2 lines instead of 5 lines in C++!

3. Interpreted Language
Python is an interpreted language, not a compiled language. This means the Python installation
interprets and executes the code line by line at a time. It makes Python an easy-to-debug
language and thus suitable for beginners to advanced users.

4. Its Completeness
When you install Python, you get everything you need to do real work. You do not need to download
additional libraries; all types of required functionality is available through various modules of the
Python Standard Library. Thus, Python follows "Batteries Included" philosophy.
5. Cross-platform Language
Python can run equally well on variety of platforms – Windows, Linux/UNIX, Macintosh,
supercomputers, smart phones etc. That makes Python a true cross-platform language (also
called a portable language).

6. Free and Open Source


Python language is freely available (from [Link]) without any cost. And not only that, its
source-code (complete program instructions) is also available – i.e., it is open-source. You can
modify/improve/extend an open-source software!

7. Variety of Usage / Applications


Python is used in many diverse fields/applications:
• Scripting
• Web Applications
• Game Development
• System Administrations
• Rapid Prototyping
• GUI Programs
• Database Applications

1.3 PYTHON – SOME MINUSES (LIMITATIONS)


Although Python is very powerful and simple, it is not the Perfect Programming Language. The
following are its limitations:

1. Not the Fastest Language


Python is an interpreted language, not a fully compiled one. Python is first semi-compiled into an
internal byte-code which is then executed by a Python interpreter. Fully compiled languages are faster
than their interpreted counterparts. So, here Python is little weaker though it offers faster
development times but execution-times are not that fast compared to some compiled
languages.

2. Lesser Libraries than C, Java, Perl


Python offers library support for almost all computing programs, but its library is still not as large as
languages like C, Java, Perl which have larger collections available. Sometimes in some cases, these
languages offer better and multiple solutions than Python.

3. Not Strong on Type-binding


Python interpreter is not very strong on catching 'Type-mismatch' issues. For example, if you declare a
variable as integer but later store a string value in it, Python won't complain or pin-point it.

4. Not Easily Convertible


Python has easy syntax, but this becomes a disadvantage when it comes to translating a program into
another programming language. This is because most other languages have structured defined syntax.
So, translating from Python to another language would require careful examination of the Python code.

📦 KEY CONCEPT: Interpretation vs Compilation


Interpreter:
This language processor converts a HLL (High Level Language) program into machine language by
converting and executing it line by line. If there is any error in any line, it reports it at the same
time and program execution cannot resume until the error is rectified. Interpreter must always be
present in the memory.

Compiler:
It also converts the HLL program into machine language but the conversion manner is different. It
converts the entire HLL program in one go, and reports all the errors of the program along with
the line numbers. After all errors are removed, the program is recompiled, and after that the compiler
is not needed in the memory as the object program is available.

Compiler Interpreter
Translates entire program at once Translates line by line
Reports all errors after full translation Reports error as soon as it is encountered
Faster execution (not needed after Slower execution (always needed in memory)
compilation)
Object code stored; re-compilation needed No object code stored; re-interpreted every
only if changed time
Used by: C, C++, Java Used by: Python, BASIC

📝 NOTE: Python is an interpreted language – all commands you write are interpreted and
executed one by one.

1.4 WORKING IN PYTHON


Before you start working in Python, you need to install Python on your computer. There are multiple
Python distributions available today:
• CPython (Default Installation) – available from [Link]. Comes with Python
interpreter, Python IDLE (GUI) and Pip (package installer).
• Anaconda Python Distribution – one such highly recommended distribution that comes
preloaded with many packages and libraries (e.g., NumPy, SciPy, Panda libraries etc.).
• Many popular IDEs are also available, e.g., Spyder IDE, PyCharm IDE etc. Spyder IDE is
already available as a part of Anaconda Python distribution.

Once Python is installed, you can work in Python in two different ways:
• (i) Interactive mode (also called Immediate Mode)
• (ii) Script mode

1.4.1 Working in Default CPython Distribution


The default distribution, CPython, comes with Python interpreter, Python IDLE (GUI based) and
pip (package installer). To work in interactive as well as script mode, you need to open Python IDLE.
1.4.1A Working in Interactive Mode (Python IDLE)
Interactive mode of working means you type the command – one command at a time, and the
Python executes the given command there and then and gives you output. In interactive mode, you
type the command in front of Python command prompt >>>. For example, if you type 2 + 5 in front of
Python prompt, it will give you result as 7.

To work in Interactive Mode:


1. Click Start button → All Programs → Python 3.6.x → IDLE (Python GUI)
2. It will open Python Shell where you'll see the Python prompt (>>>)
3. Type commands in front of this Python prompt and Python will immediately give you the result.

Example:
>>> 2 + 5
7
>>> print('Hello')
Hello

📝 NOTE: Interactive mode proves very useful for testing code; you type the commands one by
one and get the result or error one by one.

1.4.1B Working in Script Mode (Python IDLE)


What if you want to save all the commands in the form of a program file? With interactive mode, you
cannot do so, because:
• Interactive mode does not save the commands entered by you in the form of a program.
• The output is sandwiched between the command lines.

The solution is Script mode. To work in a script mode:

Step 1: Create Module / Script / Program File


4. Click Start button → All Programs → Python 3.6.x → IDLE
5. Click File → New in IDLE Python Shell
6. In the New window that opens, type the commands you want to save in the form of a program
(or script).
7. Click File → Save and then save the file with .py extension. For instance, we gave the name
to our program as [Link].

📝 NOTE: If you forget to give .py extension, Python won't be able to run your script.

Step 2: Run Module / Script / Program File


8. Open the desired program/script file using IDLE's File → Open command.
9. Click Run → Run Module command (or press F5 key).
10. It will execute all the commands stored in the module/program/script and show you the
complete output in a separate Python Shell window.

Advantage of Script Mode: You can store all commands together in the form of a
module/program/script and can get all output lines together (no more command-output sandwiching).

1.4.2 Working in Anaconda Distribution


Anaconda distribution comes with many preloaded packages and libraries. You can work in it in both
interactive and script modes. Anaconda distribution provides the following tools:
• Jupyter notebook – a web-based, interactive computing environment.
• Spyder – a powerful Python IDE with many useful editing, interactive testing and debugging
features.

1.4.2A Working in Jupyter Notebook


11. Launch Anaconda Navigator.
12. From the Navigator window, click on Launch below jupyter notebook tile.
13. Since jupyter notebook is a web-based computing environment, it will be launched in a web
browser. Your web browser will now show you notebook dashboard.
14. On the notebook dashboard, click at down-arrow next to New button and select Python 3 to
create a notebook for executing Python 3.x code.
15. In a new tab, it will open a new notebook where you can write and run your code.

Interactive Mode in Jupyter:


16. To run Python code in interactive mode, type code in code cell and click Run. It will show the
output below the code and start a new code cell below it.

Script Mode in Jupyter:


17. (a) Write the code of a Python script – a group of Python commands – in a code cell.
(b) Click on its name to give it a new name.
(c) Click on save icon first to save it.
(d) Click Run to run your script.

1.4.2B Working in Spyder IDE


Spyder is a powerful interactive development environment for the Python language with advanced
editing, interactive testing, debugging and introspection features.

To launch Spyder IDE:


18. Launch Anaconda Navigator
19. Click on Spyder tile in Anaconda navigator
OR click Start button → Programs → Anaconda (folder name) → Spyder

Spyder Interface has two main panes:


• Editor pane – To create scripts, work here.
• IPython Console – To work in interactive mode, type command(s) here and it will give the
output below the command. The IPython console takes commands in front of In[ ] prompt and
often shows output with Out[ ] lines.

Interactive Mode in Spyder:


Type your command(s) in the IPython console pane of Spyder window. It will give you the output of
the command there itself.

Script Mode in Spyder:


Type your script's commands in the editor pane.
• To start a new script file, click File → New File...
• To save current script, use command File → Save or File → SaveAs.
• Python scripts have file extension as .py
• After typing and saving, run your script by clicking Run icon [▶] or by clicking Run → Run
command or by pressing F5.

📝 NOTE: Please make sure to click in IPython console before you run your script. So as to have
cursor in IPython console.

Reasons to Favour Anaconda Python Distribution:


• (i) it is free and open source
• (ii) it comes preloaded with many packages and libraries
• (iii) it offers jupyter notebook and spyder IDE like toolkits to write and run Python scripts and
code interactively

1.4.3 Writing and Compiling Python Program with Command Line in Linux
To create and run a Python program on Linux platform:
20. Write your program code in a text editor.
21. Save your program with .py extension.
22. Compile and run on the command prompt by giving appropriate command.

Typing Python Program in a Text Editor:


There are command line editors like nano, vim, emacs etc. Or GUI editors like Sublime Text, atom,
brackets etc. We work with Sublime Text 3.

Steps in Sublime Text (Linux):


23. Open Sublime Text. Press the super key (windows key) and search for Sublime Text.
24. Create a New File: File → New or press Ctrl + N.
25. A new untitled file will open. Write the hello world code: print('Hello World')
26. Save the file with .py extension: File → Save or press Ctrl + S. Give an extension .py (e.g.,
[Link]).

Compiling and Running the Code using the Terminal:


27. Open the terminal. Press Ctrl + Alt + T from the keyboard. A command prompt will appear.
28. Go to the folder where you saved the file.
29. Type the following command in front of the prompt and press enter: python <filename>.py
That is, we should type: python [Link]
30. It will compile and run your program. You will see the output of the program in the terminal
window.

PyScripter IDE – another Popular IDE


There is another free and open source IDE by the name PyScripter IDE available. For interactive
mode, you can type commands directly in console window and for script mode, you can write script in
the editor pane and then run it by pressing Run icon or through Run menu.

1.5 UNDERSTANDING FIRST PROGRAM / SCRIPT


Let us create our first program – a simple "Hello World" program.

Steps (using Spyder IDE):


31. Start Spyder IDE or any other editor of your choice.
32. Start new file (File → New File) and type the following text in the editor window:

#My First Program


print("Hello World!")

33. Now save your script with a desired name.


• Make sure to select Save as type as Python Files.
• Give .py extension to your python program file.

34. Now run your script by clicking Run icon [▶] or by clicking Run → Run command or by
pressing F5. (Firstly, click in IPython console window)
35. It will show you the output in the console window pane.
Analysing Script and Output
You typed two lines:
#My First Program
print("Hello World!")

But Python gave you just one line's output as:


Hello World!

Reason: Any line that begins with a # symbol is a comment in Python. That is, it is for the
programmer's information only; Python will completely ignore all the lines starting with a #.

Understanding print( )
To print or display output, Python 3.x provides print( ) function. You can use print( ) as:
print(<objects to be printed>...)

For example:
print("Hello World!") → Hello World!
print('My name is Misha') → My name is Misha

Important about Strings:


• The first string is enclosed in double quotes and the second string is enclosed in single
quotes.
• Both are valid in Python. You can enclose strings in either double quotes or single quotes, but
ensure that opening and closing quotation marks should be of same type.
• INVALID: 'Hey there" – Error! Opening and closing Quotation marks do not match.

Valid print( ) statements:


print('The Golden Ratio')
print("has same letters as")
print('The God Relation')

📝 NOTE: In Python 2.x, print is a statement, not a function.

📋 LET US REVISE – Quick Summary


Python was developed by Guido Van Rossum in February 1991.
Python offers following advantages: easy to use, expressive, interpreted, complete, cross-
platform, free and open source, variety of applications.
Python also has these limitations: not the fastest language, lesser libraries than C/Java/Perl,
not strong on type-binding.
In Python, one can work in two different ways: (i) Interactive mode, (ii) Script mode.
Interactive mode does not save commands in form of a program and also, output is sandwiched
between commands. Interactive mode is suitable for testing code.
Script mode is useful for creating programs and then run the programs later and get complete
output.
Python is an interpreted language. Python's interactive interpreter is also called
Python Shell.

📖 GLOSSARY
Term Definition
Cross-platform Something that is compatible across various
platforms.
Open-Source Computer software for which source-code is
freely available.
Python Shell Interactive interpreter of Python.
Source Code Complete program instructions.
Interpreter A language processor that converts HLL to
machine code line by line.
Compiler A language processor that converts entire
HLL program to machine code in one go.
Script Mode A mode where Python instructions are stored
in a .py file and executed as a unit.
Interactive Mode A mode where Python instructions are given
at >>> prompt and executed immediately.

✅ SOLVED PROBLEMS (with CBSE-Style Answers)


(From the textbook – solved with full marks format)

Q1. Who developed Python Programming Language?


✅ Ans: Guido Van Rossum developed Python programming language in 1990s (February 1991).

Q2. Is Python an Object Oriented language?


✅ Ans: Yes, Python is an Object Oriented language.

Q3. 'Python is an interpreted high level language'. What does it mean to you?
✅ Ans: 'Python is a high level language' means it is programmer-friendly i.e., easy to program and
comprehend. 'Python is an interpreted language' means it requires an interpreter (not compiler) to
execute its code line by line – one statement at a time.

Q4. Python programming language got its name from which show.
✅ Ans: Python programming language was named after a British TV show namely 'Monty Python's
Flying Circus'.

Q5. What does a cross platform language mean?


✅ Ans: A cross platform language means it can run well on variety of platforms like Windows,
Linux/Unix, Macintosh etc. etc.

Q6. Python is a Free and Open Source language. What do you understand by this feature?
✅ Ans: It means – to download Python, one needs not pay anything, because it is Free. And its
source-code is also available, which can be modified/improved etc., because it is open-source.

Q7. What is the difference between interactive mode and script mode in Python?
✅ Ans: In interactive mode, instructions are given in front of Python prompt (e.g., >>> or In[ ]:),
Python carries out the given instruction and shows the result there itself. In script mode, Python
instructions are stored in a file generally with .py extension and are executed. The saved
instructions are known as Python script or Python program. In script mode, all instructions are run
together as a unit, producing all output at once.

Q8. What will be the output of following code:


#This is a sample program
#to output simple statements
#print ("Such as")
print("Take every chance.")
print("Drop every fear.")
Pick the correct output from the following choices and give reason.
(a) This is a sample program to output simple statements such as Take every chance. Drop every
fear.
(b) Such as Take every chance. Drop every fear.
(c) Take every chance. Drop every fear.
✅ Ans: The correct output is (c): Take every chance. Drop every fear.
Reason: The code lines beginning with a # sign are comments. They are just for information and
ignored by the Python interpreter. Hence, the third line #print ("Such as") will also be ignored
by Python interpreter. Thus, the Python interpreter will give output of only print() statements.

Q9. Which of the following are not valid strings in Python?


(a) "Hello" (b) 'Hello' (c) "Hello' (d) 'Hello" (e) {Hello}
✅ Ans: Strings (c) "Hello', (d) 'Hello" and (e) {Hello} are not valid strings in Python. Because (c) and
(d) have mismatched opening and closing quotation marks, and (e) uses curly braces which are not
used for strings.

📝 ASSIGNMENTS – Questions & CBSE-Style Answers

Type A: Short Answer Questions / Conceptual Questions

Q1. When was Python released?


✅ Ans: Python was released in February 1991.

Q2. Who was Python's developer and which two languages contributed to Python as a
programming language?
✅ Ans: Python was developed by Guido Van Rossum. Two languages that contributed to Python
are: (i) ABC language – a teaching language created as a replacement of BASIC, and (ii) Modula-3.

Q3. What is a cross-platform software?


✅ Ans: A cross-platform software is one that is compatible across various platforms i.e., it can run
equally well on variety of platforms – Windows, Linux/UNIX, Macintosh, supercomputers, smart
phones etc. Python is an example of a cross-platform language.

Q4. What are the advantages of Python programming language?


✅ Ans: The advantages (pluses) of Python programming language are:
36. Easy to Use: Python is compact and very easy to use object oriented language with very
simple syntax rules. It is programmer-friendly.
37. Expressive Language: Python's expressiveness means it is more capable of expressing the
code's purpose than many other languages. Reason – fewer lines of code, simpler syntax.
38. Interpreted Language: Python is an interpreted language, meaning the Python installation
interprets and executes the code line by line at a time. It makes Python easy-to-debug.
39. Its Completeness: Python follows 'Batteries Included' philosophy – all types of required
functionality is available through various modules of Python Standard Library.
40. Cross-platform Language: Python can run equally well on variety of platforms – Windows,
Linux/UNIX, Macintosh, supercomputers, smart phones etc.
41. Free and Open Source: Python is freely available and its source-code is also available for
modification/improvement.
42. Variety of Usage/Applications: Python is used in Scripting, Web Applications, Game
Development, System Administrations, Rapid Prototyping, GUI Programs, Database
Applications.
Q5. What are some limitations of Python programming language?
✅ Ans: The limitations (minuses) of Python programming language are:
43. Not the Fastest Language: Python is first semi-compiled into an internal byte-code which is
then executed by a Python interpreter. Fully compiled languages are faster. So, Python's
execution times are not as fast compared to some compiled languages.
44. Lesser Libraries than C, Java, Perl: Python's library is still not competent with languages
like C, Java, Perl as they have larger collections available.
45. Not Strong on Type-binding: Python interpreter is not very strong on catching 'Type-
mismatch' issues. For example, if you declare a variable as integer but later store a string value
in it, Python won't complain.
46. Not Easily Convertible: It becomes a disadvantage when it comes to translating a program
into another programming language because most other languages have structured defined
syntax.

Q6. In how many different ways, can you work in Python?


✅ Ans: In Python, one can work in two different ways: (i) Interactive Mode (Immediate
Mode): In interactive mode, instructions are given in front of Python prompt (>>>). Python carries
out the given instruction and shows the result there itself. It is suitable for testing code. (ii) Script
Mode: In script mode, Python instructions are stored in a file with .py extension. These are known
as Python script or Python program. In script mode, all instructions run together as a unit and
complete output is shown at once.

Q7. What are advantages/disadvantages of working in Interactive mode in Python?


✅ Ans: Advantages of Interactive Mode: 1. Very useful for testing code – you type the
commands one by one and get the result or error one by one. 2. Immediate feedback – Python
immediately shows the result. Disadvantages of Interactive Mode: 1. Does not save the
commands entered by you in the form of a program. 2. The output is sandwiched between the
command lines. 3. Not suitable for writing long programs.

Q8. What are the advantages/disadvantages of working in script mode in Python?


✅ Ans: Advantages of Script Mode: 1. You can store all commands together in the form of a
module/program/script. 2. Can get all output lines together (no more command-output
sandwiching). 3. Useful for creating programs and then running them later. Disadvantages of
Script Mode: 1. Not very convenient for testing individual commands. 2. If there is an error, you
need to go back to the editor and fix it and then run again. 3. Requires saving the file each time
before running.

Type B: Application Based Question

Q1. Write instructions to get the following result (Do it in both interactive mode and script
mode):
Math is Fun so don't be resistant
Just learn the rules, the rules are consistent
And most important, you must be persistent !

Adding fractions, get common denominators.


Multiply by missing factors to get the denominators.
Add numerators only, NOT denominators.

✅ Ans: Solution:

Interactive Mode: (Type each line separately at >>> prompt)


>>> print("Math is Fun so don't be resistant")
Math is Fun so don't be resistant
>>> print("Just learn the rules, the rules are consistent")
Just learn the rules, the rules are consistent
>>> print("And most important, you must be persistent !")
And most important, you must be persistent !
>>> print("Adding fractions, get common denominators.")
Adding fractions, get common denominators.
>>> print("Multiply by missing factors to get the denominators.")
Multiply by missing factors to get the denominators.
>>> print("Add numerators only, NOT denominators.")
Add numerators only, NOT denominators.

Script Mode: (Save as [Link] and run)


# Math Poem
print("Math is Fun so don't be resistant")
print("Just learn the rules, the rules are consistent")
print("And most important, you must be persistent !")
print("Adding fractions, get common denominators.")
print("Multiply by missing factors to get the denominators.")
print("Add numerators only, NOT denominators.")

Output:
Math is Fun so don't be resistant
Just learn the rules, the rules are consistent
And most important, you must be persistent !
Adding fractions, get common denominators.
Multiply by missing factors to get the denominators.
Add numerators only, NOT denominators.
🎯 IMPORTANT EXAM QUESTIONS FOR CBSE
(Likely questions for 1-mark, 2-mark and 3-mark)

1-Mark Questions:
• Q: Who developed Python? Ans: Guido Van Rossum (February 1991)
• Q: Python is named after which show? Ans: Monty Python's Flying Circus (BBC comedy show)
• Q: What is Python Shell? Ans: Interactive interpreter of Python
• Q: What file extension does Python programs have? Ans: .py
• Q: What symbol is used for comments in Python? Ans: # (hash symbol)
• Q: What philosophy does Python follow due to its completeness? Ans: "Batteries Included"
philosophy

2-Mark Questions:
• Q: Differentiate between interactive mode and script mode. Ans: See Q7 in Solved Problems.
• Q: What is a cross-platform language? Give example. Ans: See Assignment Type A Q3.
• Q: What is the use of # in Python? Ans: # is used for comments in Python. Any line starting
with # is ignored by the Python interpreter; it is for the programmer's information only.
• Q: Differentiate between Compiler and Interpreter. Ans: See Interpretation vs Compilation
section.

3-Mark Questions:
• Q: List and explain any three advantages of Python. Ans: See Section 1.2.
• Q: List any three limitations of Python. Ans: See Section 1.3.
• Q: Explain the steps to run a Python program in script mode using Python IDLE. Ans: See
Section 1.4.1B.

─── End of Chapter 1 Notes ───


Computer Science with Python (Class XI) | Sumita Arora | Dhanpat Rai & Co.

You might also like