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

Variables

Type

Code Examples

Standard Variable

var = "Hello"

Global Variable

global var

var = "Hello"

Environment Variables

Retrieving Variable Contents

Strings

Method

Code Examples

Normal String

"Hello World"

'Hello World'

Empty String

""

''

Multiline String

"""Hello

World"""

Select Character from String

str = 'Hello'

str[1]

# 'e'

Get Length

str = 'Hello'

len(str)

# 5

Remove whitespace at front and back

str = ' Hello World '

str.strip()

# 'Hello World'

To Lowercase

str = 'HELLO WORLD'

str.lower()

# 'hello world'

To Uppercase

str = 'hello world'

str.upper()

# 'HELLO WORLD'

Replace

str = 'Hello'

str.replace('H', 'Y')

# 'Yello'

Split

str = 'Hello, World'

str.split(',')

# ['Hello', ' World']

Join

list = ["Hello", "World"]

", ".join(list)

# 'Hello World'

Formatting

price = 42

txt = "The price is {} dollars"

print(txt.format(price))

# The price is 42 dollars

Formatting by Index

price = 42

txt = "The price is {0} dollars"

print(txt.format(price))

# The price is 42 dollars

Formatting Strings

price = 42

f"The price is {price} dollars"

# The price is 42 dollars

Type Casting

Type

Code Examples

As Integer

i = int("10")

As Float

i = float("10.5")

As String

i = str(10)

As Char

Arrays

Activity

Code examples

Define

['Hello', 'World']

Access Elements

arr = ['Hello', 'World']

arr[0]

# 'Hello'

Get Length

arr = ['Hello', 'World']

len(arr)

Adding Elements

arr = ['Hello', 'the']

arr.append('World')

Removing Elements

arr = ['Hello', 'World']

arr.pop(1)

Remove Element by Value

arr = ['Hello', 'World']

arr.remove('Hello')

Conditionals

Switch

Code Examples

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

Loop Type

Code Examples

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

Functions

Code Examples

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

Activity

Code Examples

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

Comment Type

Code Examples

Single line

# Hello, world!

Multiline

"""

Hello, world!

"""

Data Types

Action

Code Examples

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

Code Examples

Lambda

x = lambda a : a + 10

print(x(5))

Math Operators

TODO: Add other operator types

Operator

Code Examples

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

Error Handling

Code Examples

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

Package Management

Activity

Code Examples

Install

pip install requests

Import

import requests

List

pip list

References

If you like this content and would like to see more, please consider buying me a coffee!

Last updated