SCT Unit-V
SCT Unit-V
SCT Unit-V
Secure coding in Python: Interactive Python scripting, Python variables, Conditionals, Loops, Functions,
External Modules, File operations, Web requests.
Interactive python scripting: Python is a programming language that lets you work quickly and integrate
systems more efficiently. It is a widely used general-purpose, high-level programming language. It was
designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in
fewer lines of code. In the Python programming language, there are two ways in which we can run our code:
1. Interactive mode
2. Script mode
Interactive mode:
• It is a way of executing a Python program in which statements are written in command prompt and
result is obtained on the same.
• The interactive mode is more suitable for writing very short programs.
• Editing of code can be done but it is a tedious task.
• We get output for every single line of code in interactive mode i.e. result is obtained after execution of
each line of code.
• Code cannot be saved and used in the future.
• It is more preferred by beginners.
Example :
Let us take an example in which we need to perform addition on two numbers and we want to get its
output. We will declare two variables a and b and store the result in a third variable c. We further print
c. All this is done in the command prompt.
# Python program to add two numbers
a=2
b=3
# Adding a and b and storing result in c
c=a+b
# Printing value of c
print(c)
Script mode:
• In the script mode, the Python program is written in a file. Python interpreter reads the file and then
executes it and provides the desired result. The program is compiled in the command prompt.
• Script mode is more suitable for writing long programs.
• Editing of code can be easily done in script mode.
• In script mode entire program is first compiled and then executed.
• Code can be saved and can be used in the future.
• It is more preferred by experts than the beginners to use script mode.
Example :
Our example is the same addition of two numbers as we saw in the interactive mode. But in this case,
we first make a file and write the entire code in that file. We then save it and execute it using the
command prompt.
Python variable: In Python, a variable is a named storage location used to store data or values in memory.
Variables are essential for working with data because they allow you to manipulate and access values as your
program runs. Here are some key points about Python variables:
I. **Variable Naming Rules:**
- Variable names can consist of letters, numbers, and underscores (_).
- They must start with a letter (a-z, A-Z) or an underscore (_).
- Python is case-sensitive, so `myVar` and `myvar` are considered different variables.
- Avoid using Python reserved keywords (e.g., `if`, `while`, `for`, `print`) as variable names.
2. **Floating-Point Numbers (`float`):** Floating-point numbers are used to represent real numbers with a
decimal point.
For example: pi = 3.14159
3. **Strings (`str`):** Strings are sequences of characters enclosed in single, double, or triple quotes. They are
used to represent text.
For example: name = "Alice"
4. **Booleans (`bool`):** Booleans represent binary values, either `True` or `False`. They are often used in
conditional statements and comparisons.
For example: is_student = True
5. **Lists (`list`):** Lists are ordered collections of items. They can contain elements of different data types
and are mutable, meaning you can change their contents.
For example: my_list = [1, 2, 3, "apple"]
6. **Tuples (`tuple`):** Tuples are similar to lists, but they are immutable, meaning their elements cannot be
changed after creation. They are often used to represent fixed collections of items.
For example: coordinates = (3, 4)
7. **Dictionaries (`dict`):** Dictionaries are collections of key-value pairs, where each key is unique. They
are used to store and retrieve data using a key.
For example: person = {"name": "Alice", "age": 30, "is_student": False}
8. **Sets (`set`):** Sets are unordered collections of unique elements. They are often used for mathematical
operations like union, intersection, and difference.
For example: my_set = {1, 2, 3}
9. **None (`NoneType`):** `None` represents the absence of a value or a null value. It is often used as a
placeholder or to indicate that a variable has no value assigned.
For example: empty_variable = None
10. **Complex Numbers (`complex`):** Complex numbers have a real part and an imaginary part and are
represented as `a + bj`, where `a` is the real part and `b` is the imaginary part.
For example: z = 3 + 2j
IV. **Variable Reassignment:** You can change the value of a variable by assigning a new value to it. The
data type can also change if you assign a different type of value.
EX: x = 5 # x is an integer
x = "Hello" # x is now a string
V. **Variable Scope:** Variables have a scope, which defines where they can be accessed. Variables can be
local (limited to a specific function or block of code) or global (accessible throughout the entire program).
6. **Printing Variables:** You can print the value of a variable using the `print()` function.
EX: my_variable = 42
print(my_variable) # Output: 42
Conditions in python:
We have different types of conditional statements like if, if-else, elif, nested if, and nested if-else statements which control
the execution of our program.
1) if statements
Python if statement is one of the most commonly used conditional statements in programming languages. It
decides whether certain statements need to be executed or not. It checks for a given condition, if the condition
is true, then the set of code present inside the ” if ” block will be executed otherwise not.
The if condition evaluates a Boolean expression and executes the block of code only when the Boolean
expression becomes TRUE.
Syntax:
If ( EXPRESSION == TRUE ):
Block of code
Example: 1
num = 5
if (num < 10):
print(“Num is smaller than 10”)
2) if-else statements
The statement itself says if a given condition is true then execute the statements present inside the “if block”
and if the condition is false then execute the “else” block.
The “else” block will execute only when the condition becomes false. It is the block where you will perform
some actions when the condition is not true.
if-else statement evaluates the Boolean expression. If the condition is TRUE then, the code present in the “ if “
block will be executed otherwise the code of the “else“ block will be executed
Syntax:
If (EXPRESSION == TRUE):
Statement (Body of the block)
else:
Statement (Body of the block)
Example: 1
num = 5
if(num > 10):
print(“number is greater than 10”)
else:
print(“number is less than 10”)
3) elif statements
In Python, we have one more conditional statement called “elif” statements. “elif” statement is used to check
multiple conditions only if the given condition is false. It’s similar to an “if-else” statement and the only
difference is that in “else” we will not check the condition but in “elif” we will check the condition.
“elif” statements are similar to “if-else” statements but “elif” statements evaluate multiple conditions.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
num = 10
if (num == 0):
print(“Number is Zero”)
else:
print(“Number is smaller than 5”)
Output:
Number is greater than 5
An “if” statement is present inside another “if” statement which is present inside another “if” statements and so
on.
Nested if Syntax:
if(condition):
#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
#end of nested if
#end of if
The above syntax clearly says that the if block will contain another if block in it and so on. If block can contain
‘n’ number of if block inside it.
Example: 1
num = 5
if(num >0):
print(“number is positive”)
if(num<10):
print(“number is less than 10”)
Output:
number is positive
5) elif Ladder
We have seen about the “elif” statements but what is this elif ladder? As the name itself suggests a program that
contains a ladder of “elif” statements or “elif” statements are structured in the form of a ladder.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
#Set of statements to be executed when both if and first elif condition is false and second elif condition is true
elif (condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and third elif statement is true
else:
#Set of statement to be executed when all if and elif conditions are false
Example: 1
my_marks = 90
if (my_marks < 35):
print(“Sorry!, You failed the exam”)
elif(my_marks > 60 and my_marks < 90):
print(“Passed in First class”)
else:
print(“Passed in First class with distinction”)
Output:
Passed in First class with distinction
Loops in Python:
Python programming language provides the following types of loops to handle looping requirements.
Python provides three ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition-checking time.
While Loop in Python:
In python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the program
is executed.
Syntax:
while expression:
statement(s)
Example:
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
Syntax:
for iterator_var in sequence:
statements(s)
Example:
# Python program to illustrate
# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)
Output:
0
1
2
3
Nested Loops:
Python programming language allows to use one loop inside another loop. Following section shows
few examples to illustrate the concept.
Syntax:(for loop)
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Example:
# Python program to illustrate
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
22
333
4444
Syntax:(while loop)
while expression:
while expression:
statement(s)
statement(s)
Example:
I=0
While i<=5:
J=1
While j<=i:
Print(I,end=“ ”)
j=j+1
print(“”)
i=i+1
Output:
1
12
123
1234
12345
In Python, functions are reusable blocks of code that perform a specific task. Functions help you organize your
code, make it more readable, and allow you to avoid duplicating code. Here's how you define and use functions
in PythonYou can pass data, known as parameters, into a function.A function can return data as a result.
Example
def my_function():
print("Hello from a function")
my_function()
Defining a Function:You can define a function using the def keyword followed by the function name and parentheses
containing optional parameters. The function body is indented and contains the code to be executed when the function is
called. You can also include a return statement to specify what value the function should return.
Calling a Function:
To call a function, you simply use its name followed by parentheses, passing any required arguments or
parameters.
Function Parameters:Functions can have zero or more parameters. Parameters allow you to pass information
into a function. You can also use default values for parameters to make them optional.
def greet(name="Guest"):
print(f"Hello, {name}!")
Return Values:Functions can return values using the return statement. You can return one or more values from
a function.
Docstring:It's good practice to provide a docstring (documentation string) for your functions to describe what
they do. This helps other developers (and yourself) understand the purpose of the function.
Scope:Variables defined within a function have local scope, meaning they are only accessible within that
function. Variables defined outside of any function have global scope and can be accessed from anywhere in
the code.
global_var = 10
def my_function():
local_var = 5
print(global_var) # Accessing a global variable is possible
print(local_var) # Accessing a local variable is possible within the function
my_function()
print(global_var) # Accessing a global variable outside the function is possible
# print(local_var) # This would result in an error because local_var is not defined globally
External Modules:
In Python, external modules are pre-written libraries or packages of code that you can use to extend the
functionality of your programs. These modules contain functions, classes, and variables that can be imported
and used in your Python scripts. External modules help you save time and effort by providing ready-made
solutions for common tasks. Here's how you can work with external modules in Python:
Importing Modules:
You can import an external module using the import statement. For example, to import the math module, which
provides mathematical functions and constants, you would use:
import math
import math
# Using module functions
result = math.sqrt(25) # Calculates the square root of 25
print(result)
# Using module variables
print(math.pi) # Accesses the value of pi from the math module
Module Aliasing:
You can give a module a shorter alias for easier reference using the ‘ as’ keyword.
Third-Party Modules:
In addition to the built-in modules, Python has a vast ecosystem of third-party modules that you can install and
use in your projects. You can use package managers like pip or conda to install these modules. For example, to
install the popular requests module for HTTP requests:
import requests
response = requests.get("https://www.example.com")
Here are a few examples of external modules and their use cases:
When working on Python projects, it's common to leverage external modules to streamline development and
take advantage of the extensive Python ecosystem. You can find and install third-party modules from the
Python Package Index (PyPI) or other sources, depending on your needs.
File operations:
File operations in Python are used to perform various operations on files, such as reading from and writing to
files, creating and deleting files, and more. Python provides built-in functions and methods to handle these file
operations. Here are some common file operations in Python:
1. Opening a File: You can open a file using the built-in open() function. It requires the filename and an
optional mode parameter (default is 'r' for reading). Common modes include:
• 'r': Read (default mode)
• 'w': Write (creates a new file or overwrites an existing one)
• 'a': Append (appends data to an existing file)
• 'b': Binary mode (e.g., 'rb', 'wb', 'ab' for reading, writing, and appending in binary mode)
Example:
file = open('example.txt', 'r')
2. Reading from a File: You can read data from a file using methods like read(), readline() or
readlines().
Example:
content = file.read() # Reads the entire file content
line = file.readline() # Reads one line at a time
lines = file.readlines() # Reads all lines into a list
3. Writing to a File: To write data to a file, open the file in write or append mode and use the
write()method.
Example:
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
4. Closing a File: It's essential to close a file after you're done with it using the close() method to free up
system resources.
Example:
file.close()
5. Using 'with' Statement (Context Managers): The with statement is a convenient way to open and
automatically close files. It ensures that the file is properly closed even if an exception occurs.
Example:
with open('example.txt', 'r') as file:
content = file.read()
# File is automatically closed outside the 'with' block
6. Checking File Existence: You can check if a file exists using the os.path.exists( ) function from the os
module.
Example:
import os
if os. path.exists('example.txt'):
print('File exists')
7. Deleting a File: To delete a file, you can use the os.remove() function.
Example:
import os
os.remove('example.txt')
8. Renaming a File: To rename a file, you can use the os. rename()function.
Example:
import os
os.rename('old_file.txt', 'new_file.txt')
These are the fundamental file operations in Python. Always remember to handle exceptions, especially
when working with files, to ensure your code is robust and handles potential errors gracefully.
Web requests:
In Python, you can make web requests to retrieve data from web servers or interact with web APIs using
various libraries. Two commonly used libraries for making web requests in Python are requests and urllib.
Here's how you can make GET and POST requests using the requests library:
import requests
if response.status_code == 200:
print('POST request successful')
else:
print('POST request failed')
Python's standard library includes the urllib module, which can also be used to make HTTP requests, although
it's less user-friendly compared to requests. Here's an example of how to make a GET request using urllib:
import urllib.request
import urllib.error
try:
response = urllib.request.urlopen('https://api.example.com/data')
data = response.read()
print(data)
except urllib.error.URLError as e:
print('Failed to retrieve data:', e)
While urllib can be used for basic HTTP requests, requests is often preferred because it offers a more
straightforward and feature-rich API, including support for handling various types of requests, authentication,
session management, and handling response data (e.g., JSON).
Before making web requests, make sure to review the documentation of the API or website you are accessing to
understand its usage, authentication requirements, and any rate limits or guidelines that need to be followed.
Choose the library that best suits your needs, and handle exceptions appropriately to ensure robust error
handling in your web request code.