PYTHON EXAMPLES

folder

Various scripting examples. Lists, Loops, functions, statements and more!

SHEBANG

folder

Used to Specify which interpreter will run the script. This will be the very 1st line. This line will start with a #! and be followed by the path to the Python interpreter. Doing this will ensure the correct interpreter is used to execute the script. Without this line, the script will be teated as just a text file. However, the Python interpreter is not always installed in the same location. In this case the shebang can also point to the Python environment variable, which will then point to the interpreter. Examples shown below.

01

Shebang (local)

If the script is being run locally on the machine that created it, the following command can be use to find the path to the Python interpreter. After finding the path, add it to the shebang/hashbang at the top of the script.

fossman@linux-server:~$ which python3

Screenshot
Find path to interpreter

Command Purpose
#! shebang / hashbang
/usr/bin/python3 path to interpreter

02

Shebang (portable)

Use the following example to specify the intended interpreter by the environment variable. This can be useful if the path to the interpreter is unknown.

fossman@linux-server:~$ which python3

Screenshot
Using environment variable

Command Purpose
#! shebang / hashbang
/usr/bin/env python3 use environment variable

USER INPUT

folder

Collect and store input from the user.

01

Basic User Input

The following example uses a user input to get information from the user. Ater this information has been collected, it will be stored in a variable called any_value and shown to the user.

#!/usr/bin/python3

import sys

# user input
any_value = input('Enter any value: ')

# print out entered value
print ('value entered: ' + any_value)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
any_value = input() user input
store value in 'any_value'
print (any_value) print value of any_value to the screen
sys.exit() exit script

Screenshot
User input example

CONDITIONALS

01

if / else

The following is an example scipt using a if/else statement. The user will first be asked to select a mode. If read is selected the message "mode was set to read" will be shown. If any other value is entered, the message "mode was not set to read" will be shown.

#!/usr/bin/python3

import sys

# user input
mode = input('choose mode [read/write]: ')

# if / else
if mode == 'read':
    print('mode was set to read')
else:
    print('mode was not set to read')

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
mode = input() user input
store value in mode
== is equal to...
sys.exit() exit script

Screenshot
if/else statement example

02

else / if

The following is an example scipt using a else/if statement. The user will first be asked to select a mode. If read is selected the message "mode was set to read" will be shown. If write is selected the message "mode was set to write" will be shown. If any other value is entered, the message "invalid value" will be shown.

#!/usr/bin/python3

import sys

# user input
mode = input('choose mode [read/write]: ')

# else / if
if mode == 'read':
    print('mode was set to read')
elif mode == 'write':
    print('mode was set to write')
else:
    print('invalid value: ' + mode)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
mode = input() user input
store value in mode
== is equal to...
sys.exit() exit script

Screenshot
else/if statement example

03

if / and

The following is an example scipt using a if/and statement. The user will first be asked to provide a username and password. If the username is root and the password is password, they will be presented with a welcome message. If the username entered is root and the password is not password, they will get a message saying the password is invalid. Finally... if the user is not root, they will be denied access and threatened.

#!/usr/bin/python3

import sys

# user input
print('')
username = input('Username: ')
password = input('Password: ')

# if / and
if username == 'root' and password == 'password':
    print('\nWelcome ' + username)
elif username == 'root' and password != 'password':
    print('\npassword entered is not valid')
else:
    print('\nonly root has access')

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
username = input() get username from user
password = input() get password from user
== equal to...
!= not equal to...
sys.exit() exit script

Screenshot
if/and statement example

04

if / or

The following is an example scipt using a if/or statement. The user will first be asked to provide a username and password. If the username is root or tux and the password is password, they will be presented with a welcome message. If the username entered is root or tux and the password is not password, they will get a message saying the password is invalid. Finally... if the user is not root or tux, they will be denied access and threatened.

#!/usr/bin/python3

import sys

# user input
print('')
username = input('Username: ')
password = input('Password: ')

# if / or
if (username == 'root' or username == 'tux') and password == 'password':
    print('\nWelcome ' + username)
elif (username == 'root' or username == 'tux') and password != 'password':
    print('\npassword entered is not valid')
else:
    print('\nonly root and tux have access')

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
username = input() get username from user
password = input() get password from user
or / and or / and
== is equal to...
!= is not equal to...
sys.exit() exit script

Screenshot
if/or statement example

LOOPS

01

For Loops

The following code snippets are examples of for loops

Specified Range
Complete a task for a predetermined amount of iterations. In the example below... the sentence "just some text" will be printed out to the screen 10 times.

#!/usr/bin/python3

import sys
import time

for i in range(10):
    print('just some text')
    time.sleep(1)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
i representitive value (convention)
each item in loop
range(10) repeat 10 times
sys.exit() exit script

Specified Range (iterations shown)
Similar to the example above, the following code snippet will complete a task for a predetermined amount of iterations. The sentence "just some text" will be printed out to the screen 10 times. Showing each iteration can be done by adding the variable created in the for loop "i" to the end of the print function. In this context, the "i" can be considered as an item or iteration. Any other character or name can also be used, as the "i" is only representative. str(i) is used to convert this value into a string so it can be printed out to the screen.

#!/usr/bin/python3

import sys
import time

for i in range(10):
    print('just some text: ' + str(i))
    time.sleep(1)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
i representitive value (convention)
each item in loop
range(10) repeat 10 times
str(i) convert item to a string
required to print to screen
sys.exit() exit script

Specified Iterations (iterations shown)
In this example, we can define where the iteration will start and where it will end. Each iteration will be shown, starting at 1 and ends at but not including 10.

#!/usr/bin/python3

import sys
import time

for i in range(1, 10):
    print('just some text: ' + str(i))
    time.sleep(1)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
i representitive value (convention)
each item in loop
range(1, 10) start at 1 and end at 10
str(i) convert item to a string
required to print to screen
sys.exit() exit script

Specified Iterations (iterations shown 5-10)
Similar to the example above, we can specify where the iterations will start and when they will end. In this example the 1st iteration starts at 5 and ends at but not including 10. Resulting in 5 iterations.

#!/usr/bin/python3

import sys
import time

for i in range(5, 10):
    print('just some text: ' + str(i))
    time.sleep(1)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
i representitive value (convention)
each item in loop
range(5, 10) start at 5 and end at 10
str(i) convert item to a string
required to print to screen
sys.exit() exit script

Specified Iterations (iterations shown 1, 4, 7 and 10)
In addition to specifying where the iterations will start and end, we can also specify the size of each step. In the example below, the iterations will start at 1, ends at but does not include 10 and will have a step count of 3. Resulting in 3 iterations (1,4,7)

#!/usr/bin/python3

import sys
import time

for i in range(1, 10, 3):
    print('just some text: ' + str(i))
    time.sleep(1)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
i representitive value (convention)
each item in loop
range(1, 10, 3) start at 1 ,end at 10 and use steps of 3
str(i) convert item to a string
required to print to screen
sys.exit() exit script

Lists (show contents)
For loops can also be used to iterated through a list. The items in said list can be anything from strings to functions and even other lists. In the example below, a list of employees will be printed out to the screen from an list of employees.

#!/usr/bin/python3

import sys
import time

Employees = ['John', 'Alice', 'Tux', 'May', 'Jessie', 'Jade', 'Louis', 'Sara', 'Donald']

print('')
print('Employees' + '\n---------')

for i in Employees:
    print(i)
    time.sleep(1)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
Employees = [] list of employees
i representitive value (convention)
each item in loop
print(i) print name of employee
sys.exit() exit script

02

While Loops

The following is an example script using a while loop. These are used to execute a block of code repeatedly while a specified condition remains true. It evaluates the condition before each iteration based on changing conditions within the program.

While Loop (Basic Example)
In the example below, the while loop will execute its commands while a condition remains True or when the iteration count reaches 5. After which, the script will then exit. Each iteration will be shown excluding the last iteration(5).

#!/usr/bin/python3

import sys
import time

count = 1

while True:
    print('current count: ' + str(count))
    count = int(count)
    count += 1
    time.sleep(1)
    if count == 5:
        break

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
while True while a condition remains True
str(count) convert to a string
required to print to screen
int(count) convert to an integer
required for calculation
sys.exit() exit script

Screenshot
basic while loop

While Loop (with user input)
In the example below, the while loop will execute its commands while the value of "guess" is not equal to 5 (the magic number) At each iteration, the user will be prompted to enter a number. When the magic number has been guessed correctly the number will be shown along with some positive feedback. After which, the program will exit.

#!/usr/bin/python3

import sys

magic_number = '5'
guess = '0'

while guess != magic_number:
    guess = input('Guess the magic number [1-10]: ')

print('\nYou guessed correctly!')
print('The magic number is ' + magic_number)

# exit this script
sys.exit()
Command Purpose
import sys import the 'sys' module
used to exit script
import time import time module
used for sleep
magic_number = '5'
guess = '0'
set original values
== is equal to...
!= is not equal to...
sys.exit() exit script

Screenshot
while loop with user input