SCT Unit-5
SCT Unit-5
Unit – V
Secure coding in Python: Interactive Python Scripting, Python Variables, Conditionals, Loops,
Functions, External Modules, File operations, Web requests.
Interactive Mode
Interactive mode, also known as the REPL provides us with a quick way of running blocks or a
single line of Python code. The code executes via the Python shell, which comes with Python
installation. Interactive mode is handy when you just want to execute basic Python commands or
you are new to Python programming and just want to get your hands dirty with this beautiful
language.
To access the Python shell, open the terminal of your operating system and then type "python".
Press the enter key and the Python shell will appear. This is the same Python executable you use to
execute scripts, which comes installed by default on Mac and Unix-based operating systems.
C:\Windows\system32>python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
The >>> indicates that the Python shell is ready to execute and send your commands to the Python
interpreter. The result is immediately displayed on the Python shell as soon as the Python
interpreter interprets the command.
To run your Python statements, just type them and hit the enter key. You will get the results
immediately, unlike in script mode. For example, to print the text "Hello World", we can type the
following:
1.Helpful when your script is extremely short and you want immediate results.
2.Faster as you only have to type a command and then press the enter key to get the results.
3.Good for beginners who need to understand Python basics.
The following are the disadvantages of running your code in the interactive mode:
1.Editing the code in interactive mode is hard as you have to move back to the previous commands
or else you have to rewrite the whole command again.
1
SCT Unit 5
Script Mode
If you need to write a long piece of Python code or your Python script spans multiple files,
interactive mode is not recommended. Script mode is the way to go in such cases. In script mode,
You write your code in a text file then save it with a .py extension which stands for "Python". Note
that you can use any text editor for this, including Sublime, Atom, notepad++, etc.
If you are in the standard Python shell, you can click "File" then choose "New" or simply hit "Ctrl
+ N" on your keyboard to open a blank script in which you can write your code. You can then press
"Ctrl + S" to save it.
After writing your code, you can run it by clicking "Run" then "Run Module" or simply press F5.
Let us create a new file from the Python shell and give it the name "hello.py". We need to run the
"Hello World" program. Add the following code to the file:
Click "Run" then choose "Run Module". This will run the program:
Output:
1.Can be tedious when you need to run only a single or a few lines of cod.
2.You must create and save a file before executing your code.
There are two modes through which we can create and run Python scripts: interactive mode and
script mode. The interactive mode involves running your codes directly on the Python shell which
can be accessed from the terminal of the operating system. In the script mode, you have to create a
file, give it a name with a .py the extension then runs your code. The interactive mode is suitable
when running a few lines of code. The script mode is recommended when you need to create large
applications.
Python Variables
Variables
Python variables are the reserved memory locations used to store values with in a Python Program.
This means that when you create a variable you reserve some space in the memory.
Creating Variables
1. Python has no command for declaring a variable.
2. A variable is created the moment you first assign a value to it.
Syntax:
Example:
Program:
3
SCT Unit 5
Output:
Local variables in Python are the ones that are defined and declared inside a function. We can
not call this variable outside the function.
Example:
Global variables in Python are the ones that are defined and declared outside a function, and we
need to use them inside a function.
Example:
4
SCT Unit 5
Conditionals
1) if
Syntax:
if condition : statement
Or
if condition :
statement-1
statement-2
statement-3
Example:
Output:
2) if - else
Syntax:
if condition :
Action-1
else :
Action-2
5
SCT Unit 5
Example:
Output:
3) if – elif - else
Syntax:
if condition1 :
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
…
else :
Default Action
6
SCT Unit 5
Output:
Note:
1. else part is always optional
Hence the following are various possible syntaxes.
1. if
2. if - else
3. if-elif-else
4. if-elif
2. There is no switch statement in Python
Program1:
#Write a Python program that calculates a student's grade based on their score.
Output:
Program2:
Write a program to find biggest of given 3 numbers from the command prompt?
7
SCT Unit 5
Output:
Loops
Iterative Statements
1. for loop
2. while loop
for loop:
If we want to execute some action for every element present in some sequence
(it may be string or collection)then we should go for for loop.
Syntax:
for x in sequence :
body
8
SCT Unit 5
for x in range(1,11):
print(x)
for x in range(21):
if(x%2!=0):
print(x)
for i in range(10,0,-1):
print(i)
Output:
Output:
9
SCT Unit 5
while loop:
If we want to execute a group of statements iteratively until some condition
false, then we should go for while loop.
Syntax:
while condition:
body
Functions
• If a group of statements is repeatedly required then it is not recommended to write
these statements every time separately. We have to define these statements as a single
unit and we can call that unit any number of times based on our requirement without
rewriting. This unit is nothing but function.
1. Built in Functions
2. User Defined Functions
1. Built in Functions:
The functions which are coming along with Python software automatically, are called built in
functions or pre defined functions
Ex:
id()
type()
input()
eval()
10
SCT Unit 5
etc..
def function_name(parameters):
Note:
1. def (mandatory)
2. return (optional)
Example1:
def display():
print(“Hello Good Morning”)
display()
display()
display()
Example2:
def display():
print(“Hello Good Morning”)
def wish():
display()
wish()
display()
wish()
Parameters:
Parameters are inputs to the function. If a function contains parameters, then at the
time of calling, compulsory we should provide values otherwise, otherwise we will get
error.
Example3:
#Write a function to take name of the student as input and print wish message by name.
11
SCT Unit 5
Output:
Example4:
#Write a function to take number as input and print its square value.
Output:
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
Example5: Write a function to accept 2 numbers as input and return sum.
Output:
Example6:
If we are not writing return statement then default return value is None
12
SCT Unit 5
Output:
Output:
Types of arguments:
def f1(a,b):
------
------
------
f1(10,20)
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments
1. positional arguments:
• These are the arguments passed to function in correct positional order.
def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)
13
SCT Unit 5
2. keyword arguments:
We can pass argument values by keyword i.e by parameter name.
Example:
Output:
Note: We can use both positional and keyword arguments simultaneously. But first we
have to take positional arguments and then keyword arguments, otherwise we will get
Syntax error.
3. Default Arguments:
Sometimes we can provide default values for our positional arguments.
Example:
Output:
14
SCT Unit 5
def f1(*n):
• We can call this function by passing any number of arguments including zero number.
• Internally all these values represented in the form of tuple.
Example:
Output:
External Modules
External Modules There are many other libraries that have been built by developers outside of the
core Python team, to add additional functionality to the language. These modules don't come as part
of the Python language, but can be added in. We call these external modules.
In order to use an external module, you must first install it on your machine. This means you'll need
to download the files from the internet to your computer, then integrate them with the main python
library, so that the language knows where the module is located.
pip
It is usually possible to install modules manually, but this process can be a major pain. Luckily,
python also gives us a streamlined approach for installing modules- the pip module! This feature
can locate modules that are indexed in the Python Package Index (a list of commonly-used
modules), download them, and attempt to install them.
Traditionally, we don't run pip from our normal editor- instead, you'll need to run it from the
terminal. This is a command interface that lets you make changes directly to your computer. On
Mac and Linux machines, you can find the terminal by searching your applications for the built-in
app Terminal. On Windows, search for the built-in application Powershell.
Syntax:
15
SCT Unit 5
File operations
Files
• As the part of programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.
• Files are very common permanent storage areas to store our data.
Types of Files:
There are 2 types of files
1. Text Files:
Usually we can use binary files to store binary data like images,video files, audio
files etc…
16
SCT Unit 5
1.Opening a File
Before performing any operation (like read or write) on the file, first we have to
open that file. For this we should use Python's inbuilt function open()
• But at the time of open, we have to specify mode, which represents the purpose of
opening file.
f = open(filename, mode)
Note: All the above modes are applicable for text files. If the above modes suffixed
with 'b' then these represents for binary files.
f = open("abc.txt","w")
We are opening abc.txt file for writing data.
2.Closing a File:
After completing our operations on the file, it is highly recommended to close the file.
For this we have to use close() function.
f.close()
17
SCT Unit 5
Example
Output:
We can write character data to the text files by using the following 2 methods.
1)write(str)
2)writelines(list of lines)
1) write(str)
Output:
Note: In the above program, data present in the file will be overridden every time if
we run the program. Instead of overriding if we want append operation then we
should open the file as follows.
f = open("abcd.txt","a")
2)writelines(list)
18
SCT Unit 5
Output:
Note: while writing data by using write() methods, compulsory we have to provide line
seperator (\n), otherwise total data should be written to a single line.
Output:
19
SCT Unit 5
Web Requests
Web Requests in Python using requests Library
These fundamental concepts cover making web requests, handling responses, sending parameters, making
POST requests, and dealing with JSON data. The requests library is versatile and widely used for interacting
with web APIs and fetching data from the internet in Python.
Example:
1. Making a GET Request
Output:
(JSON - like format)
20
SCT Unit 5
Output:
(JSON - like format)
Output:
(JSON - like format)
21
SCT Unit 5
Output:
(css -like format)
1. Input Validation
User input is often a significant source of security risks. Input validation is the process of verifying
that the user input meets the expected criteria and is safe to use in the application.
For example, when a user enters a credit card number, the input should only contain digits and no
special characters. To validate the input, developers can use built-in functions such as isdigit() or
regular expressions to ensure that the input meets the expected criteria.
For example, instead of using eval() function to convert a string to an integer, developers should
use the int() function.
22
SCT Unit 5
Cryptography libraries such as cryptography and pycryptodome provide a secure way to perform
encryption and decryption operations. Use these libraries instead of creating custom encryption
methods, which may be prone to vulnerabilities.
For example, if an application requires read-only access to a database, it should use a database
account with read-only permissions instead of an account with full permissions. This reduces the
risk of an attacker exploiting the application to modify or delete data.
For example, if the application uses a third-party library, such as Requests , which has a security
vulnerability, the developer should update to the latest version of the library that addresses the
vulnerability.
For example, bandit is a popular static code analyzer that examines Python code for potential
security vulnerabilities. It can detect issues such as hard-coded passwords, SQL injection, and use
of unsafe functions.
23
SCT Unit 5
Web applications are vulnerable to several security risks such as cross-site scripting, SQL injection,
and command injection. Developers should follow secure coding practices such as input validation,
output encoding, and parameterized queries to ensure that web applications are secure.
For example, when writing SQL queries, use parameterized queries instead of concatenating user
input with the query. Parameterized queries prevent SQL injection attacks by treating user input as
data rather than executable code.
S H A I K _ _ 4 4 3
24