Script Language Syntax
Last updated
Was this helpful?
Last updated
Was this helpful?
TODO: need syntax examples for Bash and Windows Batch scripting (issue )
Add syntax examples for Bash and Windows Batch scripting
Add example output for all
Basic syntax examples for Python, PowerShell, Bash, and Windows cmd.exe batch scripting languages.
Variables in scripting languages are used to store and manipulate data dynamically. They act as placeholders for values such as numbers, text, arrays, or objects. They simplify data handling and improve code readability, making scripting more efficient for automation and processing tasks.
Assignment: Variables are assigned values that can be updated or referenced.
Data Storage: They hold different types of data, including strings, numbers, and lists.
Scope: Variables can have a global (accessible throughout the script) or local (restricted to a specific function or block) scope.
Type Handling: Some scripting languages require explicit type declaration, while others dynamically assign types based on the assigned value.
Storing user input
Performing calculations
Managing lists and structured data
Controlling flow with conditional logic
Declare Variable
x = 10
(Integer)
name = "Alice"
(String)
Assign Multiple Variables
a, b, c = 1, 2, 3
Check Variable Type
type(x)
String Formatting
f"Hello, {name}!"
List Variables
my_list = [1, 2, 3]
Dictionary Variables
my_dict = {"key": "value"}
Boolean Variables
is_active = True
Constants (Convention)
PI = 3.14159
(Uppercase naming for constants)
Python follows the LEGB rule (Local, Enclosing, Global, Built-in) to determine variable scope.
Local Scope
Variables declared inside a function, accessible only within that function.
python def my_function(): x = 10 # Local variable print(x) my_function() print(x) # Error: x is not defined outside the function
Global Scope
Variables declared outside any function, accessible throughout the script.
python x = 10 # Global variable def my_function(): print(x) # Accessible inside function my_function() print(x) # Accessible outside function too
Enclosing Scope
Variables in an outer function, accessible by inner functions (nested functions).
python def outer_function(): x = 10 # Enclosing variable def inner_function(): print(x) # Accessible from outer function inner_function() outer_function()
Built-in Scope
Variables and functions built into Python, available everywhere.
python print(len([1, 2, 3])) # 'len' is a built-in function
Using global
Keyword
Allows modification of a global variable inside a function.
python x = 10 def my_function(): global x x = 20 # Modifies global variable my_function() print(x) # Output: 20
Using nonlocal
Keyword
Allows modification of an enclosing variable inside a nested function.
python def outer_function(): x = 10 def inner_function(): nonlocal x x = 20 # Modifies enclosing variable inner_function() print(x) # Output: 20 outer_function()
Normal String
"Hello World"
or 'Hello World'
Empty String
""
or ''
Multiline String
"""Hello\nWorld"""
or '''Hello\nWorld'''
Select Character from String
str = "Hello"
print(str[1])
Output: 'e'
Get Length
str = "Hello"
print(len(str))
Output: 5
Remove Whitespace
str = " Hello World "
print(str.strip())
Output: 'Hello World'
To Lowercase
str = "HELLO WORLD"
print(str.lower())
Output: 'hello world'
To Uppercase
str = "hello world"
print(str.upper())
Output: 'HELLO WORLD'
Replace Characters
str = "Hello"
print(str.replace("H", "Y"))
Output: 'Yello'
Split String
str = "Hello, World"
print(str.split(","))
Output: ['Hello', ' World']
Join List into String
words = ["Hello", "World"]
print(" ".join(words))
Output: 'Hello World'
String Formatting (.format()
)
price = 42
txt = "The price is {} dollars".format(price)
print(txt)
Output: 'The price is 42 dollars'
String Formatting with Index
price = 42
txt = "The price is {0} dollars".format(price)
print(txt)
Output: 'The price is 42 dollars'
f-Strings (Modern Formatting)
price = 42
txt = f"The price is {price} dollars"
print(txt)
Output: 'The price is 42 dollars'
Check If Substring Exists
str = "Hello World"
print("Hello" in str)
Output: True
Reverse String
str = "Hello"
print(str[::-1])
Output: 'olleH'
Repeat String
print("Hello " * 3)
Output: 'Hello Hello Hello '
Python provides powerful tools for string manipulation, including regular expressions, string slicing, and other advanced techniques for text processing.
re
module)Regular expressions (regex) allow pattern-based searching and manipulation of strings.
Example: Extracting Email Addresses
Uses regex to find all email addresses in a string.
Flexible for extracting structured data from text.
String slicing allows extracting specific parts of a string using index ranges.
Example: Extracting Substrings
Supports positive and negative indexing.
Allows reversing strings easily.
Python offers additional methods for efficient text processing.
Example: Removing Unwanted Characters
Example: Replacing Words Using re.sub()
Uses regex for complex replacements.
Great for cleaning up messy text.
Example: Extracting and Formatting Data
Extracts structured data using regex.
Formats extracted values using f-strings
.
Type casting is the process of converting a variable from one data type to another. This ensures compatibility between different types in operations and functions.
Implicit Casting (Automatic Conversion)
Happens when a smaller or less precise type is converted into a larger or more precise type.
No risk of data loss.
Example: Converting an integer to a floating-point number.
Explicit Casting (Manual Conversion)
Requires direct conversion using specific functions or operators.
May lead to loss of data or precision.
Example: Converting a floating-point number to an integer.
Mathematical Operations: Ensuring consistency between integers and floats.
User Input Handling: Converting input into appropriate data types.
Data Processing: Handling different formats across APIs or databases.
⚠️ Data Loss: Converting complex types to simpler ones can remove details. ⚠️ Unexpected Behavior: Incompatible conversions may lead to errors.
Type casting is essential for efficient data management in programming, ensuring smooth interactions between different types.
Python's type casting allows flexible data manipulation, ensuring compatibility between different types.
As Integer
i = int("10")
→ Converts string "10"
to integer 10
As Float
f = float("10.5")
→ Converts string "10.5"
to float 10.5
As String
s = str(10)
→ Converts integer 10
to string "10"
As Character
c = chr(65)
→ Converts ASCII value 65
to character 'A'
As Boolean
b = bool(0)
→ Converts 0
to False
, bool(1)
→ True
As List
lst = list("hello")
→ Converts string "hello"
to list ['h', 'e', 'l', 'l', 'o']
As Tuple
tpl = tuple([1, 2, 3])
→ Converts list [1, 2, 3]
to tuple (1, 2, 3)
As Dictionary
d = dict([(1, "one"), (2, "two")])
→ Converts list of tuples to dictionary {1: "one", 2: "two"}
As Set
s = set([1, 2, 2, 3])
→ Converts list [1, 2, 2, 3]
to set {1, 2, 3}
Limitations and Pitfalls of Type Conversion in Python
Type conversion in Python is useful for handling different data types, but it comes with potential pitfalls that can lead to unexpected behavior or errors.
Loss of Precision
Converting floats to integers removes the decimal portion, potentially altering values.
Example:
Type Errors
Some conversions are not allowed, leading to TypeError
.
Example:
Value Errors
Converting incompatible strings to numbers results in ValueError
.
Example:
Unexpected Boolean Behavior
Python treats non-empty values as True
and empty values as False
, which can cause logic errors.
Example:
Implicit Conversions Can Lead to Bugs
Mixing integers and floats in operations can cause unintended type changes.
Example:
eval()
for Dynamic Type Casting⚠️ Caution: eval()
can execute arbitrary code, so use it carefully.
Python does not have built-in support for Arrays as so termed, but Python Lists and Tuples can be used instead, and work much in the same way.
Define
arr = ['Hello', 'World']
Access Elements
arr[0]
→ 'Hello'
Get Length
len(arr)
→ 2
Add Elements
arr.append('New')
→ ['Hello', 'World', 'New']
Insert at Specific Position
arr.insert(1, 'there')
→ ['Hello', 'there', 'World']
Remove Last Element
arr.pop()
→ ['Hello']
Remove Specific Index
arr.pop(1)
→ ['Hello']
Remove Element by Value
arr.remove('Hello')
→ ['World']
Sort Elements
arr.sort()
(Alphabetical order)
Reverse Elements
arr.reverse()
→ ['World', 'Hello']
Check if Element Exists
'Hello' in arr
→ True
Loop Through Elements
for item in arr: print(item)
Copy List
copy_arr = arr.copy()
Concatenate Lists
new_arr = arr + ['Python', 'Rocks']
Convert List to String
', '.join(arr)
→ 'Hello, World'
Convert String to List
arr = 'Hello World'.split()
→ ['Hello', 'World']
Looping Through Lists
Filtering Elements in a List
Nested Lists
Define a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Access an element
nested_list[1][2]
→ 6
Loop through nested lists
for sublist in nested_list: print(sublist)
Flatten a nested list
[item for sublist in nested_list for item in sublist]
→ [1, 2, 3, 4, 5, 6, 7, 8, 9]
A tuple is an ordered collection of items, similar to a list, but with one key difference—tuples are immutable. This means once a tuple is created, its contents cannot be changed, added to, or removed.
Key Differences Between Lists and Tuples
Feature
List (list
)
Tuple (tuple
)
Mutability
✅ Mutable (can modify, add, remove elements)
❌ Immutable (cannot change after creation)
Syntax
Defined using []
(square brackets)
Defined using ()
(parentheses)
Performance
Slower due to dynamic resizing
Faster due to fixed structure
Memory Usage
Uses more memory
Uses less memory
Intended Use
Dynamic, frequently modified data
Static, unchangeable data
Defining a List and a Tuple
Nested Tuples
Define a nested tuple
nested_tuple = ((1, 2), (3, 4), (5, 6))
Access an element
nested_tuple[2][1]
→ 6
Iterate through nested tuples
for subtuple in nested_tuple: print(subtuple)
When to Use Tuples vs. Lists
Use a List when you need a dynamic data structure that will change during program execution.
Use a Tuple when you need a fixed, unchangeable collection (e.g., coordinates, config settings, database records).
If / ElseIf / Else
a = 42
b = 420
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Case
For
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
While
i = 1
while i < 6:
print(i)
i += 1
Break
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Continue
i = 1
while i < 6:
print(i)
if i == 3:
continue
i += 1
Definition
def hello_function():
print("Hello from my function!")
<code></code>
hello_function()
Arguments
def my_name(fname, lname):
print("My name is " + fname + " " + lname)
<code></code>
my_function("Wolf", "Zweiler")
Variable Arguments
def second_arg(*children):
print("The youngest child is " + children[1])
<code></code>
my_function("Sarah", "Emily", "Tom")
Named Arguments
def young_child(child3, child2, child1):
print("The youngest child is " + child3)
<code></code>
my_function(child1 = "Sarah", child2 = "Emily", child3 = "Tom")
Default Values
def my_country(country = "Wakanda"):
print("I am from " + country)
<code></code>
my_country()
Return Values
def five_times(x):
return 5 * x
Class Definition
class MyClass:
x = 5
Object Creation
MyClass()
Using Class Constructors
class Person:
def
init
(self, name, age):
self.name = name
self.age = age
<code></code>
p1 = Person("Bob", 42)
Defining and using Methods
class Person:
def
init
(self, name, age):
self.name = name
self.age = age
<code></code>
def myfunc(self):
print("Hello my name is " + self.name)
<code></code>
p1 = Person("Bob", 42)
p1.myfunc()
Single line
# Hello, world!
Multiline
"""
Hello, world!
"""
Get Object's Type
var = 1
type(var)
Activity
Code Examples
Defining
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Elements
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict['brand']
Updating Elements
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict['brand'] = 'Chevy'
Enumerating Keys
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Enumerating Values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
Check if key exists
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Adding items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
Lambda
x = lambda a : a + 10
print(x(5))
TODO: Add other operator types
Addition
var = 1 + 1
Subtraction
var = 1 - 1
Multiplication
var = 1 * 1
Division
var = 1 / 1
Modulus
var = 1 % 1
Floor
var = 10 // 3
Exponent
var = 10 ** 3
Try/Except
try:
print(x)
except:
print("An exception occurred")
Else
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
try:
f = open("file.txt") f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
Raise
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
In scripting, a heredoc (here document) is a way to feed a block of text into a command or script. It's often used to generate multi-line output or pass structured text to commands like cat, echo, or tee. Some benefits of using HERE docs:
Simplifies Multi-Line Input – Instead of writing multiple commands, you can provide large text blocks neatly to a single input.
Improves Readability – Using heredocs makes scripts easier to read and maintain, especially when handling structured data.
Supports Variable Expansion – In most languages, heredocs allow variables to be expanded dynamically.
Python doesn't have a direct heredoc equivalent, but triple-quoted strings ("""
or '''
) serve a similar purpose.
Install
pip install <package-name>
Import
import <package-name>
List
pip list
Update
pip install --upgrade <package-name>
Uninstall
pip uninstall <package-name>
Search
pip search <package-name>
(Deprecated, use pip install <package-name>
to check availability)
Show Details
pip show <package-name>
Freeze
pip freeze
(Lists installed packages in a format suitable for requirements.txt)
References
Python variables are dynamic, meaning their type can change based on assignment. You can find more details on Python variables and .
You can find more details on Python variable scopes and .
You can find more details on PowerShell variable scopes and .
You can find a full list of automatic variables .
You can find more details on preference variables .
You can find more details on Bash variables and .
You can find more details on environment variables in Bash and .
For more details, check out on SET
vs SETX
.
You can explore more advanced string manipulation techniques and .
You can find more details on PowerShell string operations and .
You can explore more advanced PowerShell string manipulation techniques and .
You can explore more advanced printf
formatting techniques and .
You can explore more details on PowerShell type conversion and .
You can explore more details on Bash type conversion and .
You can explore more details on Batch type conversion and .
You can also check out for more details!
You can find more details on Winget commands .
You can find more details on Chocolatey commands .
You can find more details on managing Windows features .
If you like this content and would like to see more, please consider !