Python 101 - For Beginners

As Python is the engine behind the app, we need to attach to it’s functionality, below We will list important points to keep in mind while developing using Easy for Jira.

A note from the writer:

While reading the guide, to fixate your knowledge, go to the app (if you already have it installed) and code along with the guide, test stuff yourself. The only way to learn how to code well is by writing code, unfortunately there’s no shortcut in this part.

Indentation

Python is a language that can’t be written unstructured such as Javascript, Python reserves scope with text Indentation, which is done by Tabs, this also helps keeping the code more readable. Identation in python is made by 4 spaces or a “Tab”.

Indentation is only used when entering some sort of scope such as class declaration, function declaration, loop iterations, etc. NEVER on variable declaration, as the variable should be declared in the same scope, check the reference below.

variable1 = 10 variable2 = 20 <--------------- Wrong def sum_function(a, b): return a + b <------ Right

variable1 is declared correctly
variable2 is declared incorrectly as it should have no spaces in the left
function sum_function is declared correctly as the return statement has 4 spaces in the left.

Not respecting indentation will result in this error → Built-in Exceptions

Global Methods

From the segment Built-in Functions — Python 3.10.15 documentation in the official documentation, We will skip this part, these functions are almost never used in general cases with a few exceptions. In case you need them, they are available, the functions that are useful from that list are:

type() all([]) any([])

And general datatype declarations such as

dict(obj) str(obj) list(obj), etc

Data Types

Let’s start with the foundations, first you need to understand the basic Python data types and their methods (functions). Everything in Python is an Object, and all the objects have functions or in the official nomenclature - Methods.

Some (almost all) information that will be outlined here is from the original python documentation, no place better to get the information from.

Now let’s cut to the chase, the list of data types you can work with in python is the following

Text Type

str

Numeric Types

int, float, complex

Sequence Types

list, tuple, range

Mapping Type

dict

Set Types

set, frozenset

Boolean Type

bool

Binary Types

bytes, bytearray, memoryview

None Type

NoneType

Outlining all the functions for all the data types is sort of unnecessary as we have a lot of guides out there, so We will link some resources, with the original docs always available at Built-in Types — Python 3.10.15 documentation .

Data Types are auto-declarative in Python
Therefore, you don’t need to specify what is the type of object you want to hold in a variable, and also, if you want to replace the variable data with something different you can, there’s no boundaries.

Auto Declarative in this context means this:

myvar = "This will be considered as a String" myvar = 10 # This was changed to a Number (int) automatically.

Strings

Strings are basically text. You are reading a string right now, and everything can be a string in python if you declare it as so. The most basic example so you have “the AHA! moment“ on your head is the following:

You declare strings as follows:

mystring = "This is a string"

But you can also declare a pre-existing number as a string:

mynumber = 10 mystring = str(mynumber) print(mystring) # 10

You see a number, but the computer now sees a string.

Useful links

Floats

Floats, short for floating-point numbers, are a fundamental data type in Python used to represent real numbers. Real numbers include both integers and fractions, providing precision beyond whole numbers. Understanding floats is crucial for working with numerical data and performing mathematical operations accurately in Python.

You declare floats as follows:

myfloat = 3.14

Similar to strings, you can also convert other data types, such as integers, to floats:

myinteger = 10 myfloat = float(myinteger) print(myfloat) # 10.0

In the above example, although myinteger was initially an integer, after conversion to a float, it becomes 10.0, a floating-point number.

Floats in Python are represented in decimal notation and can contain a decimal point, as well as an optional exponent part indicated by the letter 'e' or 'E'. For example:

myfloat = 2.5e2 # equivalent to 250.0

It's important to note that while floats provide a high level of precision, they can encounter issues with accuracy due to the limitations of representing real numbers in binary format. Links:

 

Integers

Integers are one of the fundamental data types in Python used to represent whole numbers without fractional components. They can be positive, negative, or zero. Understanding integers is crucial for performing arithmetic operations, counting, and representing quantities in Python.

You declare integers simply by assigning a whole number to a variable:

my_integer = 42

Integers can also be the result of mathematical operations:

result = 10 + 5

Integers support various arithmetic operations, including addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (**):

addition_result = 10 + 5 subtraction_result = 10 - 5 multiplication_result = 10 * 5 division_result = 10 / 5 exponentiation_result = 10 ** 2

Python also supports floor division (//), which returns the quotient without the remainder:

floor_division_result = 10 // 3 # Output: 3

And modulo (%), which returns the remainder of the division:

modulo_result = 10 % 3 # Output: 1

Integers in Python have unlimited precision, meaning they can represent arbitrarily large or small numbers without overflowing or losing precision:

large_integer = 1234567890123456789012345678901234567890

You can convert other data types to integers using the int() constructor:

float_to_int = int(3.14) string_to_int = int("42")

If the string contains non-numeric characters, converting it to an integer will raise a ValueError:

invalid_string_to_int = int("hello") # Output: ValueError: invalid literal for int() with base 10: 'hello'

Understanding integers is essential for performing arithmetic calculations, representing quantities, and manipulating numerical data in Python. Integers are used extensively in a wide range of applications, from simple arithmetic operations to complex mathematical algorithms and data processing tasks. Links:

 

Dictionaries

Dictionaries in Python are a versatile and powerful data structure used to store key-value pairs. Unlike sequences such as lists and tuples, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be of any immutable data type. Dictionaries are widely used for data organization, mapping, and rapid retrieval of information based on keys.

You declare dictionaries as follows:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

Each key-value pair in a dictionary is separated by a colon (:), and pairs are separated by commas. Keys must be unique within a dictionary, but values can be duplicated.

You can also create dictionaries using the dict() constructor and passing in a sequence of key-value pairs as tuples:

my_dict = dict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

Accessing values in a dictionary is done by specifying the key inside square brackets:

print(my_dict["key2"]) # Output: value2

If a key does not exist in the dictionary, trying to access it will result in a KeyError. You can avoid this by using the get() method, which returns None if the key does not exist, or a default value that you specify:

print(my_dict.get("key4")) # Output: None print(my_dict.get("key4", "Key not found")) # Output: Key not found

Dictionaries are mutable, meaning you can modify, add, or remove key-value pairs after creation. You can modify the value associated with a key:

my_dict["key1"] = "new value"

Add new key-value pairs:

my_dict["key4"] = "value4"

And remove key-value pairs:

del my_dict["key3"]

Understanding dictionaries is essential for efficient data manipulation and retrieval in Python, especially when dealing with complex data structures and large datasets. They offer fast lookup times and provide a flexible way to organize and access data based on custom criteria. Links:

 

Lists

Lists are a fundamental data structure in Python used to store collections of items. They are versatile and widely used due to their flexibility, allowing for the storage and manipulation of heterogeneous data types and providing various methods for accessing, modifying, and iterating over elements.

You declare lists as follows:

my_list = ["apple", "banana", "cherry", "date"]

Lists can contain any number of elements, including zero, and can mix data types:

mixed_list = [1, "two", 3.0, True]

Elements in a list are indexed starting from zero, meaning the first element is accessed with index 0, the second with index 1, and so on.

print(my_list[0]) # Output: apple

Negative indexing is also supported, allowing you to access elements from the end of the list:

print(my_list[-1]) # Output: date

Lists in Python are mutable, meaning you can modify their contents after creation. You can change the value of a specific element:

my_list[1] = "orange"

You can also add elements to the end of a list using the append() method:

my_list.append("elderberry")

Or insert elements at a specific index using the insert() method:

my_list.insert(2, "fig")

To remove elements from a list, you can use the remove() method to delete a specific value:

my_list.remove("banana")

Or use the del statement to delete an element by index:

del my_list[0]

Lists also support various other operations, such as slicing to create sublists:

sublist = my_list[1:3] # Output: ['cherry', 'date']

And concatenation to combine lists:

new_list = my_list + ["grape", "honeydew"]

Understanding lists is essential for many Python programming tasks, as they provide a flexible and efficient way to store and manipulate collections of data. Lists are used extensively in a wide range of applications, from simple data storage to complex algorithms and data processing tasks. Some useful links about lists:

 

Booleans

Booleans in Python represent truth values, and they are primarily used in conditions and logical operations to determine whether an expression is true or false. Booleans have only two possible values: True and False. Understanding booleans is essential for writing conditional statements and controlling the flow of program execution in Python.

You can assign boolean values directly to variables:

is_true = True is_false = False

Booleans are often the result of comparison or logical operations:

result = 5 > 3 print(result) # Output: True

You can also use comparison operators like == (equal), != (not equal), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) to compare values and obtain boolean results.

Logical operators such as and, or, and not can be used to combine boolean values or expressions:

result = (5 > 3) and (10 < 20) print(result) # Output: True
result = (5 > 3) or (10 < 5) print(result) # Output: True
result = not (5 > 3) print(result) # Output: False

Booleans are often used in conditional statements, such as if, elif, and else, to control the flow of program execution based on certain conditions:

x = 10 if x > 5: print("x is greater than 5") else: print("x is not greater than 5")

Understanding how to work with booleans is fundamental for writing robust and expressive Python code. Booleans play a crucial role in decision-making processes and are widely used in various programming contexts, from simple comparisons to complex logical operations. Links:

 

Those are the main methods you need to master to become a hero on Easy for Jira. About the other methods, if you need to use them, you are probably already falling into a specific audience which already has previous python knowledge and use it professionally. For day to day, Jira Admin use, you won’t need almost any of that.

Flow Control (Loops and Conditions)

Loops are fundamental constructs in programming that allow you to execute a block of code repeatedly. They are essential for automating repetitive tasks and processing large amounts of data efficiently.

 

Importance of Loops in Coding Logic

In summary, loops play a critical role in programming logic by enabling efficient iteration, automation of repetitive tasks, scalability, flexibility, and the implementation of iterative algorithms. Mastering loop constructs is essential for any programmer looking to write efficient and maintainable code across a wide range of applications and problem domains but you can read in more detail below.

  1. Repetitive Tasks: Loops allow you to repeat a certain set of instructions multiple times without having to write the same code over and over again. This saves time and reduces the chances of errors that can occur when manually repeating code.

  2. Efficiency: Instead of writing separate lines of code to handle each iteration, loops enable you to accomplish repetitive tasks with minimal code, making programs more concise and easier to maintain. This efficiency is particularly crucial when dealing with large datasets or performing complex computations.

  3. Scalability: Loops make programs scalable by enabling them to handle varying amounts of data or perform tasks a variable number of times. As the size of the input increases, the loop can adapt to process it without requiring changes to the underlying code structure.

  4. Flexibility: Loops provide flexibility in controlling the flow of execution within a program. You can use loop control statements like break and continue to alter the loop's behavior based on certain conditions, allowing for more dynamic and responsive programming logic.

  5. Iterative Algorithms: Many algorithms, such as searching, sorting, and traversing data structures, rely heavily on loops to iterate through elements and perform operations. Loops are integral to the implementation of these algorithms, making them indispensable in various areas of computer science and software development.

  6. Automation: Loops are essential for automating tasks that involve repetitive actions, such as processing batches of files, generating reports, or updating database records. By encapsulating the repetitive logic within a loop, programmers can create efficient, automated solutions to common problems.

  7. Code Readability: Well-structured loops can enhance the readability of code by encapsulating repetitive logic in a clear and concise manner. Using descriptive loop constructs, such as for and while, helps communicate the intention of the code to other developers, making it easier to understand and maintain.

 

Loop Types

  1. For loop: A for loop iterates over a sequence (such as a list, tuple, string, or range) and executes a block of code for each item in the sequence.

# Example of a for loop iterating over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # apple # banana # cherry
  1. While loop: A while loop repeats a block of code as long as a specified condition is true.

# Example of a while loop num = 0 while num < 5: print(num) num += 1 # 0 # 1 # 2 # 3 # 4
  1. Nested loops: Both for and while loops can be nested inside each other to perform more complex iterations.

# Example of a nested loop for We in range(3): for j in range(2): print(i, j)

These examples demonstrate the basic usage of each type of loop in Python. Additionally, Python provides loop control statements such as break, continue, and else that can be used within loops to alter their behavior or handle specific conditions.

  1. Specific Easy for Jira Example: Let’s suppose you want to make a bulk edit with code logic for issues in a specific project, you can do that fairly easy with the following methodology

    for issue in api.search_issues("project = EFJ"): amount = issue.fields.customfield_10090 # Product Amount price = issue.fields.customfield_10089 # Product Price issue.set("customfield_10091", amount * price) # customfield_10091 as "Total Price"

In this example, for every issue in the JQL results of the query project = EFJ it will get the value from the amount * price and populate the customfield_10091 which is “Total Price“ as the result. As the only operation in there that requires some execution time to be awaited is api.search_jql, this change will happen quite fast, the set function is designed to be very fast, but this scope of search is still very open. That JQL is definitely not recommended for changes that big as if the project has 1k+ issues, that will take a lot of time and the script will time out.

Conditions

Conditional programming in Python involves making decisions in your code based on certain conditions. This is achieved using conditional statements, primarily the if, elif (else if), and else statements. Here's an explanation of each:

if condition: # run this code

The if condition is used when you want to run a code snipped in a certain place IF the condition is met. Is really as straight forward as it looks like.

But now let’s suppose you want to foresee two scenarios, what you do then? You use the else statement, as follows:

if condition: # run this code else: # run this instead

The else block will consider everything that is not the first condition as True, so it’s very open, in that case, if you want to foresee various scenarios, you use the elif statement between the if and else statements, as follows:

if condition: # run this code elif second_condition: # run if second condition mets criteria elif third_condition: # if third condition mets criteria, run this elif fourth_condition: # if this fourth condition mets, then run this part elif n_condition: # create as many as you need, but usually not good to have more then 3 elifs. else: # if nothing above met, run this part (last pickle in the jar)

 

Switch Case

Switch Case was added in Python3.10, EFJ is currently running on Python3.9 so you can’t use that yet, once we access and upgrade Python to 3.10, we will add this part of the guide.

Functions

What is a Function?

A function in Python is a block of reusable code that performs a specific task. Functions provide modularity and reusability to your code by allowing you to define a block of code that can be executed multiple times with different inputs.

Function Declaration

To declare (or define) a function in Python, you use the def keyword followed by the function name and parentheses containing any parameters the function takes. Here's the basic syntax:

def function_name(parameters): # code block # optionally, return a value

Example, let's create a simple function that takes two numbers as input and returns their sum.

def add_numbers(num1, num2): sum = num1 + num2 return sum

Calling a Function

Once a function is defined, you can call it by using its name followed by parentheses containing the required arguments (if any). Here's how you call the add_numbers function:

result = add_numbers(3, 5) print(result) # Output will be 8

Parameters and Arguments

In the function definition, the variables inside the parentheses are called parameters. When you call the function, you provide values for these parameters, which are called arguments.

Returning Values

Functions can return values using the return statement. This allows the function to send data back to the caller. In the example above, the add_numbers function returns the sum of two numbers.

Default Parameters

You can assign default values to parameters in a function. If a value is provided for a parameter during the function call, it overrides the default value; otherwise, the default value is used. Here's an example:

def greet(name="there"): print("Hello, " + name + "!") greet() # Output: Hello, there! greet("Alice") # Output: Hello, Alice!

Conclusion

Functions are a fundamental concept in Python programming. They allow you to break down your code into smaller, reusable pieces, making your code more organized, easier to understand, and easier to maintain. Practice creating and calling functions to become comfortable with using them in your Python scripts.

 

Classes

What is a Class?

In Python, a class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that all objects of that class will have.

Class Declaration

To declare a class in Python, you use the class keyword followed by the class name. Here's the basic syntax:

class ClassName: # class attributes and methods

Example, let's create a simple class called Car with attributes make, model, and a method display_info to print the details of the car.

class Car: def __init__(self, make, model): self.make = make self.model = model def display_info(self): print(f"Car make: {self.make}, Model: {self.model}")

Creating Objects (Instances)

Once a class is defined, you can create objects (also known as instances) of that class by calling the class name followed by parentheses. Optionally, you can provide arguments to the class's __init__ method to initialize its attributes.

car1 = Car("Toyota", "Corolla") car2 = Car("Honda", "Civic")

Accessing Attributes and Calling Methods

You can access the attributes of an object using dot notation (object.attribute). Similarly, you can call methods using dot notation (object.method()).

print(car1.make) # Output: Toyota print(car2.model) # Output: Civic car1.display_info() # Output: Car make: Toyota, Model: Corolla car2.display_info() # Output: Car make: Honda, Model: Civic

Constructor (__init__ method)

The __init__ method is a special method that is called automatically when a new object of the class is created. It is used to initialize the object's attributes.

Instance Variables

Instance variables are unique to each object (instance) of a class. They are defined inside the __init__ method using self.

Conclusion

Classes are a powerful feature of Python that allow you to create custom data types with their own attributes and methods. They promote code reusability and maintainability by organizing related code into logical units. Practice creating and using classes to become proficient in object-oriented programming with Python.

 

This is the end of the Python Segment, next is Easy for Jira 101

 

Chapter Summary

In this chapter we understood what python can do, from foundations, the important aspects we need to understand to gain mastery with Easy for Jira.

Easy for Jira - Python Automations, 2023