0% found this document useful (0 votes)
21 views9 pages

Scripting vs Programming Languages Explained

This are my material

Uploaded by

vijayarani11680
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)
21 views9 pages

Scripting vs Programming Languages Explained

This are my material

Uploaded by

vijayarani11680
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

Nice — here’s a medium-length, exam-friendly explanation for each item (definitions,

syntax when relevant, examples, and key points). I kept each answer detailed enough for a 5–
8M answer but not overly long.

1. Differentiate between Scripting language and


Programming language
Definition & purpose

 Scripting language: Usually interpreted and designed to automate


tasks, glue components, or write short programs quickly. Common
for web scripting, automation, and prototypes. Example: Python,
JavaScript, Bash.
 Programming language: Often compiled (though not always) and
used for building larger, standalone applications with performance
or low-level control concerns. Example: C, C++.

Key differences

 Execution: Scripting — interpreted (line-by-line). Programming —


usually compiled to machine code or bytecode first.
 Use case: Scripting — automation, small utilities, embedding.
Programming — system/software development.
 Performance: Scripting languages are typically slower but faster to
write; compiled languages are faster at runtime.
 Development cycle: Scripting allows rapid edit-run-debug;
compiled languages require a separate compile step.

Example

 Python script:

print("Quick task automation")

 C program:

#include<stdio.h>
int main(){ printf("Compiled program\n"); return 0; }

2. Operators in Python (8M)


Definition
Operators are symbols or keywords that perform operations on operands (values or
variables).
Types, brief description & examples

1. Arithmetic operators — math operations: + - * / % // **


2. 5 + 2 # 7
3. 5 ** 2 # 25 (power)
4. 7 // 2 # 3 (floor division)
5. Assignment operators — assign or modify values: =, +=, -=,
*=, /=, //=, **=
6. x = 5
7. x += 2 # x = 7
8. Comparison (Relational) operators — compare values: ==, !=,
>, <, >=, <=
9. 3 < 5 # True
10. Logical operators — combine boolean expressions: and, or,
not
11. True and False # False
12. not True # False
13. Bitwise operators — operate on binary bits: & | ^ ~ << >>
14. 5 & 3 # 1 (0101 & 0011 = 0001)
15. Membership operators — test membership in sequences:
in, not in
16. 'a' in 'apple' # True
17. Identity operators — compare object identity: is, is not
18. a = [1,2]; b = a; a is b # True
19. a is not [1,2] # True (different object)
20. Unary operators — single-operand operators (e.g., unary -,
unary +, not, ~).

Operator precedence & associativity


Operators have a defined precedence (e.g., ** higher than *//, which are higher than +/-).
Use parentheses () to ensure desired evaluation order.

3. Concept of Data types and its examples (5M)


Definition
A data type specifies the kind of value a variable can hold and the operations permitted on it.

Built-in Python data types (common ones)

 Numeric: int (e.g., 10), float (e.g., 3.14), complex (e.g., 2+3j)
 Text: str (e.g., "hello")
 Boolean: bool (True or False)
 Sequence types: list (mutable, e.g., [1,2]), tuple (immutable,
e.g., (1,2)), range
 Mapping type: dict (key → value, e.g., {'a':1})
 Set types: set, frozenset (unordered collections of unique items)
 Binary: bytes, bytearray, memoryview

Example
age = 21 # int
price = 19.99 # float
name = "Priya" # str
flags = [True, False] # list of bool
record = {'id':1, 'name':'Asha'} # dict

4. Define function and give an example


Definition
A function is a named block of reusable code that performs a specific task and can accept
parameters and optionally return a value.

Syntax

def function_name(parameters):
"""optional docstring"""
statements
return value # optional

Example

def add(a, b):


"""Return sum of a and b"""
return a + b

result = add(4, 5) # 9

Additional notes

 Functions allow modularity, code reuse, and clarity.


 Types: built-in functions (e.g., len()), user-defined functions,
anonymous (lambda) functions.
 Support for default parameters, keyword arguments, variable-length
arguments (*args, **kwargs), recursion.

5. Variables, Identifiers
Variable (definition)
A variable is a name that refers to a value stored in memory.

Identifier (definition)
An identifier is the name used to identify variables, functions, classes, etc.

Rules for identifiers

 Must start with a letter (A–Z, a–z) or underscore _.


 Remaining characters can be letters, digits, or underscores.
 Case-sensitive (age ≠ Age).
 Cannot be a Python keyword (e.g., for, if, class).
Example

student_name = "Ravi"
_age = 18
PI = 3.14159

Best practices

 Use meaningful names (total_score rather than ts), follow snake_case


for variables and functions.

6. Type conversions and what are its types


Definition
Type conversion is the process of converting a value from one data type to another.

Types

1. Implicit conversion (automatic) — Python automatically converts


one type to another during an operation when safe:
2. x = 5 # int
3. y = 2.0 # float
4. z = x + y # 7.0 (int implicitly converted to float)
5. Explicit conversion (type casting) — programmer converts types
using built-in functions:
o int(), float(), str(), bool(), list(), tuple(), dict(), etc.
6. a = int(3.9) # 3
7. b = str(123) # "123"
8. c = float("2.5") # 2.5

Caveats

 Converting incompatible types (e.g., int("abc")) raises ValueError.


 Converting floats to ints truncates toward zero, not rounding.

7. String handling
Definition
Operations and methods to manipulate text (str objects).

Common operations & methods

 Concatenation & repetition: +, *


 "Hi " + "there" # "Hi there"
 "la" * 3 # "lalala"
 Indexing & slicing: s[0], s[1:4]
 Length: len(s)
 Useful methods: .upper(), .lower(), .strip(), .split(), .join(),
.replace(), .find(), .format() / f-strings
 s = " Hello World "
 [Link]() # "Hello World"
 [Link]() # ["Hello", "World"]
 " ".join(["a","b"]) # "a b"
 Immutability: Strings are immutable — operations return new
strings; you cannot change characters in place.

Examples

name = "Anita"
print(name[1:4]) # 'nit'
print([Link]("A", "E")) # 'Enita'
print(f"Hello, {name}!") # f-string formatting

8. Array handling
Note: Python’s flexible sequence for general-purpose arrays is the list. For true typed arrays,
use array module or numpy (external).

Using lists

 Create: lst = [1,2,3]


 Add/modify: append(), insert(), slicing assignment
 Remove: pop(), remove()
 Iterate, sort: sorted(), [Link]()

Example

arr = [10, 20, 30]


[Link](40)
arr[1] = 25
for x in arr:
print(x)

Using array module (stores typed data)

import array
a = [Link]('i', [1,2,3]) # typecode 'i' = signed int
[Link](4)

Using NumPy (recommended for large numeric arrays / performance)

import numpy as np
a = [Link]([1,2,3])
a = a + 5 # vectorized operation
9. File handling
Definition
Reading from and writing to files using built-in file objects.

Modes

 'r' — read (default)


 'w' — write (truncate/create)
 'a' — append
 'rb', 'wb' — binary modes
 'r+', 'w+' — read/write

Basic syntax

f = open("[Link]", "r")
data = [Link]()
[Link]()

Better (recommended) — with with (context manager)

with open("[Link]", "w") as f:


[Link]("Hello\n")
# file auto-closed here

Examples

 Read whole file: content = [Link]()


 Read line-by-line: for line in f: or [Link]()
 Write text: [Link]("text") or [Link]([...])

Error handling

 Use try/except for I/O errors (e.g., FileNotFoundError, IOError).

10. Scopes of Variable


Definition
Scope refers to the region of a program where a variable name is visible/accessible.

Types of scope in Python (LEGB rule)

 L — Local: names defined inside a function.


 E — Enclosing: names in the local scope of enclosing functions (for
nested functions).
 G — Global: module-level names.
 B — Built-in: names preassigned in Python (len, int, etc.)
Special keywords

 — declare that a variable inside a function refers to the


global
module-level variable.
 x = 5
 def f():
 global x
 x = 10
 nonlocal — in nested functions, refer to variable in enclosing (non-
global) scope.
 def outer():
 a = 1
 def inner():
 nonlocal a
 a = 2

Example

x = "global"
def func():
x = "local" # different from global x
print(x)

11. List, String, Dictionaries, Tuple


List

 Ordered, mutable, allows duplicates.


 Syntax: lst = [1, 2, 'a']
 Methods: append, insert, pop, remove, sort, reverse.

String

 Immutable sequence of characters.


 Syntax: s = "hello"
 Methods: .upper(), .split(), .join(), .replace().

Tuple

 Ordered, immutable, allows duplicates.


 Syntax: t = (1, 2, 3) or single element (1,).
 Useful for fixed collections or as dictionary keys (if elements are
hashable).

Dictionary

 Unordered mapping of keys → values (in modern Python insertion-


ordered).
 Syntax: d = {'name':'Maya', 'age':20}
 Operations: access d['name'], add d['city']='Delhi', iterate for k,v
in [Link]():.

Examples

lst = [1,2,3]
tup = (1,2)
s = "abc"
d = {'a':1, 'b':2}

12. Features of Python


 Simple & Readable: Clear syntax and indentation.
 Interpreted: No separate compile step (bytecode compiled and run
by PVM).
 Dynamically typed: Type checked at runtime.
 High-level: Manages memory, provides rich built-ins.
 Extensive standard library: Batteries included (os, sys, math, json,
etc.).
 Portable: Runs on many platforms.
 Object-oriented: Supports classes & objects.
 Extensible: Can integrate C/C++ for performance-critical parts.
 Large ecosystem: Third-party packages (NumPy, Pandas, Django).

13. Jump Statements


Definition
Statements that alter the normal flow of control in loops or functions.

Types & examples

 break — exit the nearest loop immediately.


 for i in range(5):
 if i == 3:
 break
 continue — skip the rest of current iteration and continue loop.
 for i in range(5):
 if i % 2 == 0:
 continue
 print(i) # prints odd numbers
 pass — do-nothing placeholder (useful when syntax requires a
statement).
 def todo(): pass
 return — exit a function and optionally return a value.
14. Different types of modules and its examples
Definition
A module is a file containing Python code (definitions, functions, classes) which can be
imported.

Types

1. Built-in modules — part of Python standard library (no install


needed). Examples: math, sys, os, datetime.
2. import math
3. print([Link](16))
4. User-defined modules — files you create, e.g., [Link] and
import mymodule.
5. Third-party (external) modules/packages — installed via pip.
Examples: numpy, pandas, requests.
6. import requests
7. r = [Link]("[Link]

How to create & use

 Create [Link] with functions, then import mymodule or `

Common questions

Powered by AI

Variable scope in Python dictates the visibility and lifetime of a variable within different parts of a program. The LEGB rule outlines variable precedence in Local, Enclosing, Global, and Built-in scopes. Local variables are restricted to their function, Enclosing to outer functions in nested contexts, Global to the module, and Built-in to Python's reserved keywords. Understanding these scopes is crucial for avoiding unintentional variable shadowing and ensuring correct referencing. Keywords like 'global' and 'nonlocal' manage variable access across these scopes, influencing program execution and data handling .

Python operators, including arithmetic, assignment, comparison, logical, bitwise, membership, identity, and unary operators, provide versatile ways to manipulate data and control the flow of execution within a program. Arithmetic operators (+, -, *, /, etc.) perform mathematical operations, assignment operators modify variable values, comparison operators compare entities, logical operators manage boolean logic, and bitwise operators work on the binary level. Membership operators check element presence in sequences, identity operators compare object identities, and unary operators operate on a single operand. Each of these operators enhances control over program flow and data manipulation in specific contexts .

File handling is critical in Python applications for data persistence, enabling reading and writing operations on external files. Typical errors include FileNotFoundError when attempting to open non-existing files and IOError on failed read/write operations. Using context managers (with) is recommended for handling files as it ensures proper closure, preventing resource leaks. Understanding file modes ('r', 'w', 'a', etc.) is essential for correct file access and data integrity, making effective file handling vital for robust and error-free applications .

As an interpreted language, Python promotes ease of development and debugging by eliminating explicit compilation steps; however, this may impact runtime performance compared to compiled languages. Its high-level nature provides robust abstractions and memory management, simplifying complex operations at the cost of lower-level control and performance tuning. Dynamic typing eases coding and enhances flexibility, accommodating diverse data types seamlessly but can result in runtime errors if type expectations are not managed. These attributes enable rapid development and iterative prototyping, especially for applications prioritizing flexibility over compute efficiency .

Functions in Python encapsulate reusable code, enhancing modularity by allowing the separation of concerns within complex systems. A function's structure, defined with the 'def' keyword followed by a name and parameters, supports code reuse and clarity. Functions can return values, accept default and variable-length parameters, and facilitate recursion. They permit creating abstractions, separating logic into manageable units, enhancing readability, and easing debugging. By organizing code into discrete, well-defined functions, Python supports maintainable and scalable software development .

Scripting languages are typically interpreted line-by-line, designed for automating tasks or writing short programs quickly, and are used for web scripting and rapid prototyping. Examples include Python and JavaScript. Programming languages are often compiled into machine code or bytecode, ideal for building larger, standalone applications requiring performance or system-level control, such as C and C++. Scripting languages allow faster development cycles with rapid edit-run-debug processes, whereas programming languages, usually compiled, have a separate compile step for performance optimization .

Implicit type conversion, or coercion, occurs automatically during operations where Python interprets the need, ensuring consistent data types, such as converting an 'int' to a 'float' in a mixed-type arithmetic operation. Explicit type conversion, or casting, requires manual intervention using functions like int(), float(), str(), allowing precise control over data types. Implicit conversion enhances convenience in operations, whereas explicit conversion is necessary for preparing data for operations that require specific types. Each approach serves different scenarios, like arithmetic operations for implicit and input validation for explicit conversions .

Understanding data types is crucial because they define the nature of data that can be stored in variables and determine what operations can be performed. Python, being dynamically typed, allows different types of data to interact seamlessly. Common built-in data types include numeric types (int, float, complex), text type (str), boolean type (bool), sequence types (list, tuple, range), mapping type (dict), and set types (set, frozenset). Correctly using these types ensures proper data handling and efficient execution of operations, guaranteeing the robustness of applications .

Python's string manipulation methods, such as .upper(), .split(), and .join(), provide powerful tools for text processing, supporting operations like formatting, parsing, and reformatting effortlessly. The immutability of strings, while promoting stability and thread safety, necessitates deliberate handling when transformations are needed, as each modification returns a new string object. This can impact memory usage and performance during intensive operations, requiring developers to strategize transformations efficiently. These attributes make Python suitable for text-heavy applications but demand careful management in performance-critical scenarios .

Modules in Python facilitate code organization and reuse by separating functionality into distinct files. Built-in modules are part of the standard library, requiring no installations (e.g., math, sys), offering commonly used utilities. User-defined modules are custom files created by developers, allowing specific functionalities to be encapsulated and imported as needed. Third-party modules, installed via package managers like pip (e.g., numpy, requests), provide extended capabilities beyond the standard library. While built-in modules offer utility and reliability, third-party modules enhance capabilities, and user-defined modules allow tailored solutions, each supporting different aspects of development .

You might also like