Script Language Syntax
TODO: need syntax examples for Bash and Windows Batch scripting (issue #22)
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
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.
Key Features of Variables
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.
Common Uses
Storing user input
Performing calculations
Managing lists and structured data
Controlling flow with conditional logic
Basic Variable Operations
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 variables are dynamic, meaning their type can change based on assignment. You can find more details on Python variables here and here.
Python variable scope
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()
You can find more details on Python variable scopes here and here.
Strings
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 '
Advanced String Manipulation in Python
Python provides powerful tools for string manipulation, including regular expressions, string slicing, and other advanced techniques for text processing.
Regular Expressions (re
module)
re
module)Regular expressions (regex) allow pattern-based searching and manipulation of strings.
Example: Extracting Email Addresses
import re
text = "Contact us at support@example.com or sales@example.com"
emails = re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
print(emails) # Output: ['support@example.com', 'sales@example.com']
Uses regex to find all email addresses in a string.
Flexible for extracting structured data from text.
String Slicing
String slicing allows extracting specific parts of a string using index ranges.
Example: Extracting Substrings
text = "Python Programming"
print(text[0:6]) # Output: 'Python'
print(text[-11:]) # Output: 'Programming'
print(text[::-1]) # Output: 'gnimmargorP nohtyP' (Reversed)
Supports positive and negative indexing.
Allows reversing strings easily.
Advanced String Manipulation Techniques
Python offers additional methods for efficient text processing.
Example: Removing Unwanted Characters
text = " Hello, World! "
cleaned_text = text.strip() # Removes leading/trailing spaces
print(cleaned_text) # Output: 'Hello, World!'
Example: Replacing Words Using re.sub()
import re
text = "The price is $100."
updated_text = re.sub(r"\$\d+", "affordable", text)
print(updated_text) # Output: 'The price is affordable.'
Uses regex for complex replacements.
Great for cleaning up messy text.
Combining Multiple String Operations
Example: Extracting and Formatting Data
import re
text = "User: John Doe, Age: 30, Email: john@example.com"
match = re.search(r"User: (\w+ \w+), Age: (\d+), Email: (\S+)", text)
if match:
name, age, email = match.groups()
print(f"Name: {name}, Age: {age}, Email: {email}")
Extracts structured data using regex.
Formats extracted values using
f-strings
.
Want More?
You can explore more advanced string manipulation techniques here and here.
Type Casting
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.
Types of Type Casting
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.
Common Use Cases
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.
Potential Risks
⚠️ 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.
Type Casting in Python
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}
Converting Between Types
x = "42"
y = int(x) # Converts string to integer
z = float(y) # Converts integer to float
print(y, z) # Output: 42 42.0
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:
num = int(3.9) print(num) # Output: 3 (decimal truncated)
Type Errors
Some conversions are not allowed, leading to
TypeError
.Example:
num = int([1, 2, 3]) # Raises TypeError
Value Errors
Converting incompatible strings to numbers results in
ValueError
.Example:
num = int("hello") # Raises ValueError
Unexpected Boolean Behavior
Python treats non-empty values as
True
and empty values asFalse
, which can cause logic errors.Example:
print(bool("False")) # Output: True (because it's a non-empty string)
Implicit Conversions Can Lead to Bugs
Mixing integers and floats in operations can cause unintended type changes.
Example:
result = 5 + 2.5 # Implicitly converts 5 to float print(type(result)) # Output: <class 'float'>
Handling Type Casting Errors
try:
num = int("hello") # Invalid conversion
except ValueError:
print("Cannot convert 'hello' to an integer.")
Using eval()
for Dynamic Type Casting
eval()
for Dynamic Type Castingvalue = "3.14"
converted = eval(value) # Converts string `"3.14"` to float `3.14`
print(type(converted)) # Output: <class 'float'>
⚠️ Caution: eval()
can execute arbitrary code, so use it carefully.
Arrays
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.
Working with Lists in Python
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
arr = ['apple', 'banana', 'cherry']
for item in arr:
print(item) # Outputs each fruit
Filtering Elements in a List
arr = [1, 2, 3, 4, 5]
filtered = [x for x in arr if x > 2]
print(filtered) # Output: [3, 4, 5]
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]
Tuples
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
# List (Can be modified)
my_list = ["apple", "banana", "cherry"]
my_list.append("date") # Adding a new element
print(my_list) # Output: ['apple', 'banana', 'cherry', 'date']
# Tuple (Cannot be modified)
my_tuple = ("apple", "banana", "cherry")
# my_tuple.append("date") # ❌ This will raise an error!
print(my_tuple) # Output: ('apple', 'banana', 'cherry')
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).
Conditionals
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
Loops
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
Functions
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
Classes
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()
Comments
Single line
# Hello, world!
Multiline
"""
Hello, world!
"""
Data Types
Get Object's Type
var = 1
type(var)
Dictionaries
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"
Lambdas
Lambda
x = lambda a : a + 10
print(x(5))
Math Operators
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
Error Handling
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")
Shell Command Execution
Output Redirection
HERE docs
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.
text = """This is a multi-line string.
It works like a heredoc."""
print(text)
Package Management
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)
You can also check out this guide for more details!
References
If you like this content and would like to see more, please consider buying me a coffee!
Last updated
Was this helpful?