Published at 11/13/2024

Python on z/OS - Functions and Variables

In this tutorial will cover how functions and variables work in Python along with best practices one should follow.

Working with Python variables

declaring variables in Python is really easy:

my_variable = "Amazing string!"

Python variables can have a variety of different values:

my_variable = False  #Boolean
my_other_variable = 2 #Integers
my_last_variable = 2.123123 #Float

Just like the variable in the first code block you should always write your variable names lowercase and make them descriptive, this is standard practice in Python. Below are examples of bad variable names that work but are not recommended:

MyVariable = "Incorrect casing and no underscore"
a = "Not descriptive"
thisiswaytoolongandstupid="Poor readability"

See the PEP8 style guide for more information

Working with Python functions and if statements

Python is an indentation based language, which means the contents of functions, loops and so on has to be indented, this is not just a best practice but your code won't work without following this rule. You can declare a function with def (): as seen below. Note the indentation.

def my_function():
    print("Hello there!")

Unlike the first function example this would not work due to the missing indentation:

def my_function():
print("Hello there!")

This indentation can be a bit confusing for people coming from languages that use curly brackets or other termination methods. The print("Greetings!") in the example below is not considered part of my_function() because it is not indented.

def my_function():
    print("Hello there!")
print("Greetings!")

Below you can see a simple if statement that checks if a variable is greater than 1 and prints a message if it is:

my_variable = 2

if my_variable > 1:
    print(f"{my_variable} is greater than the number 1!")

Passing data to functions

You can pass information to Python functions when invoking them by putting variables in the parenthesis like shown below:

def my_function(message):
    print(message)

It is best practice to use type annotations when doing this, below I have specified that message should be a string:

def my_function(message: str):
    print(message)

You can still pass information of the wrong type with type declarations, but it will make your code more readable and editors will pick up on your type declarations.

Share on social media

Facebook share buttonReddit share buttonThreads share button

Recommendations