Programming in Python
In Python, programs can be written in two ways
namely Interactive mode and Script mode. The Interactive mode allows us to write codes in Python
command prompt (>>>) whereas
in script mode programs can be written and stored as separate file with the
extension.py and executed. Script
mode is used to create and edit python source file.
In interactive mode Python code can be directly
typed and the interpreter displays the result(s) immediately. The interactive
mode can also be used as a simple
calculator.
The following command can be used to invoke
Python IDLE from Window OS.
Start → All Programs → Python 3.x → IDLE (Python 3.x)
(Or)
Click python Icon on the Desktop if
available.
Now Python
IDLE window appears as shown in the Figure
5.1
The prompt (>>>) indicates that
Interpreter is ready to accept instructions. Therefore, the prompt on screen
means IDLE is working in interactive
mode. Now let us try as a simple calculator by using a simple mathematical
expressions.
Example 1:
>>> 5 + 10
15
>>> 5 + 50 *10
505
>>> 5 ** 2
25
Example 2:
>>>print (“Python Programming Language”)
Python Programming Language
>>>x=10
>>>y=20
>>>z=x + y
>>>print (“The Sum”, z)
The Sum = 30
Basically, a script is a text file containing
the Python statements. Python Scripts are reusable code. Once the script is
created, it can be executed again and again without retyping. The Scripts are
editable.
1. Choose File
→ New File or press Ctrl + N in Python shell window.
2. An untitled
blank script text editor will be displayed on screen as shown in Figure 5.3(a)
3. Type the following code in Script editor
a =100
b = 350
c = a+b
print ("The Sum=", c)
(1) Choose File
→ Save or Press Ctrl + S
(2) Now, Save
As dialog box appears on the screen as shown in the Figure 5.6
(3) In the Save
As dialog box, select the location where you want to save your Python code,
and type the file name in File Name
box. Python files are by default saved with extension.py. Thus, while creating Python scripts using Python Script
editor, no need to specify the file
extension.
(4) Finally, click Save button to save your Python script.
(1) Choose Run
→ Run Module or Press F5
(2) If your code has any error, it will be
shown in red color in the IDLE window, and Python describes the type of error
occurred. To correct the errors, go back to Script editor, make corrections,
save the file using Ctrl + S or File → Save and execute it again.
(3) For all error free code, the output will
appear in the IDLE window of Python as shown in Figure 5.8
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.