Master LLMs with our FREE course in collaboration with Activeloop & Intel Disruptor Initiative. Join now!

Publication

Learn Programming While Creating a New Year Greeting On Console Output
Programming

Learn Programming While Creating a New Year Greeting On Console Output

Last Updated on January 7, 2023 by Editorial Team

Author(s): Sumudu Tennakoon

Programming

A programming exercise using Python and Julia with a practical comparison between the two languages.

The Output

(Image by Author)

A similar exercise can be found in the article “Learn Programming While Assembling an On-Screen Christmas Tree” previously published by the author.

Learn Programming While Assembling an On-Screen Christmas Tree

Both of these articles can be helpful to an experienced Python user who wants to pick up Julia’s syntax quickly through examples and with a direct comparison between the usage of two languages.

For those who are in the early stage of exploring any programming language, these fun exercises with learning points can deliver a better learning experience as well as it can motivate you to explore the features and capability of the programming language(s).

Goal of the Excercise

To create a New Year Greeting Card to display in the console/terminal

  • Displaying the message “HAPPY NEW YEAR 2021”.
  • Decorating borders as top and bottom are Diamonds, left and right are Stars.
  • Using hearts to fill the gaps of consecutive Spaces
  • Colors: top and bottom borders are in red, message lines including side borders are blue, green, and yellow.

Concept and Logic

  • Use screen print function to output a display grid consist of larger characters and decorative symbols/illustrations assembled using ASCII characters.
  • The display characters are to be constructed by arranging ASCII characters on a grid.
  • Constructed display characters to be formed into lines that can assemble the display grid containing the Greeting message.

What you need to know/What you will learn

By working through this exercise, you will learn or practice your skills on,

  1. How to print screen output with different options and adding colors.
  2. Variables and Arrays.
  3. String manipulations and Concatenation.
  4. Processing Arrays.
  5. Generate and use a sequence of numbers.
  6. Operators
  7. Loops (for…)
  8. Conditional Statements (if…else)
  9. Use of built-in functions (print, random number)
  10. Creating custom functions to automate repetitive tasks.
  11. Adding colors to the screen output text
  12. Designing a grid layout.

In the next section, we will construct a code step by step to generate the desired output using two different programming languages, Python and Julia. As a Programming enthusiast/learner you are encouraged to focus more on the concept, logic, and algorithm than the programming language-specific syntax or style.

Let’s Start Building the Greeting Message

Let’s learn how to build the Greeting Message using both Python and Julia side by side. Please go to the end of the article to see the full code.

Task 1: Setup Display Characters

Let’s first see how many uniquely display characters we must design to create the intended message “Happy New Year 2021”.

We can design each character in a 5×5 grid. You may choose a different size and change the character drawing pattern as you like. The hash (#) character is used as the filling character in the code below.

Character pixel grid (Image by Author)

Now make some decorative characters we can use for border and fillings. Hears and Diamonds are easy to create. A random arrangement of star (*) within the grid can also be used to create a decorative side border.

Decoration pixel grid (Image by Author)

String Literals

In Python, there are three ways of defining a string: single quotes ('Hello'), and double quotes ("Hello")can be used to define single-line string while triple quotes ('''Hello''' or """Hello""") can be used to define multi-line strings which we will use to define the characters here.

Julia has a separate char data type which use the single quote literal ('A'). Therefore we only can use double quotes to define strings ("Hello"or """Hello"""for multi-line strings).

Defining Character pixel grid. Both Python and Julia share the same syntax. (Image by Author)

The message is composed of multiple characters (to be exact 8×5 =40). To make the code organized and to automate the repetitive task of converting the character string to the display grid, we can create a function.

To increase the readability of the characters, we need to add some space between each. Therefore, the 5×5 pixel grid is placed within a 7×7 grid to add one-pixel space from the top, bottom, left, and right. This function can be generalized to fit any input character size within the placeholder size (canvas).

Functions

The definition of Python function starts with the def keyword and has the general signature of def function_name(parameters,):. Note the:at the end. Since Python uses the indent to determine the scope, there is no explicit end literal to the function.

The Julia functions starts with the function keyword and has the general signature of function function_name(parameters). There must be end keyword specified to close the function body.

Return Value of a Function

Both Python and Julia functions use return keyword if the function should return a value after evaluating/executing. Consider the function add(a,b) that returns the result of a+b upon calling. If we use it c = add(2,3), value 5 will be assigned to the variable c.

The return value is not mandatory for a function. E.g. the built-in function print() is a function without a return value. You can also skip return in custom functions as well. However, in Julia, if you don’t mention the return keyword at the end, the result of the last evaluated expression will be returned. Therefore, in Julia, it is good practice to have return without any variable or value if your function is not intended to return a value.

The helping function whole_half is used to determine how many padded lines need to add from both sides of vertical (top, bottom)and horizontal (left, right) directions.

Type Conversion

In Python, a floating-point value can be converted to Integer with loss of (decimal points) using the builtin function int(value), whereas, in Julia, we can do the same in Julia using the function Int(value). Similarly, you have float(value) in Python and Float64(value) in Julia to convert integers to floating points. The discussion of type conversion should be done in detail to better understand the concept and usage.

Task 2: Assemble Lines of the Greeting Message

Array operations

Numpy is a Python package for scientific computing that supports arrays and matrices, along with a set of high-level mathematical functions. In Python [item1, item2,] literal creates a list which need to convert into np.array inorder to use the array functions which perform better than regular functions. Python also has vector operations if you would like to learn more about array operations.

Python list comprehension is a way of creating a list eliminating the need for a loop. If you are interested in learning more about Python, list comprehension will be a powerful technique to add to your knowledge base.

Julia supports vector operations to all its functions and operators by adding dot(.) in front of the function or operator.

The result returns to the variable characters in both Python and Julia will be an array of arrays where the element arrays store the characters of the word.

Array indexes

Keep that in mind Python indexes starts at 0 whereas the Julia indexes start at 1. Python array index runs from 0 to length-1 whereas Julia array index runs from 1 to length . In Python index of the last element of an array can be given as -1 and in Julia you can use end to represnt that. Julia also use begin to represnt the fist element.

Use of in Keyword

Both Python and Julia support in keyword to iterate through an array in a for loop. It can also be used to determine to check if a given element is present in an array. E.g. The expression 'A' in ['A', 'B', 'C'] should return true.

The characters in the same display line are concatenated by pixel line which makes each display line stored as arrays of 7 elements, each element contains a pixel line. The Python function np.char.add(line, character) is used for this line concatenation and in Julia, this is done using string concatenation operator in vector form (.*)

Task 3: Print Message Line

Task 4: Add Colors to Printed Message Line

Adding Colors to Console Output

Python coloram a library can be used to set the color of the string being printed on the console. In Julia, Crayons a package is available to generate colored and styled strings.

Symbols in Julia

The : the character is used to creates a Symbolthat represents the colors (E.g. :blue, :green, :red). You can learn more from the Julia documentation.

Task 5: Create a Function to Print a Given Line of Characters (Combine codes from Task 2–4)

Creating custom functions to automate repetitive tasks benefits many ways in programming. It can increase the readability of your code by making it concise as well as increase the reusability of the parts within the code and externally. If you are writing code lines for a task that is repetitively applied in the code creating a function for that task is a good practice.

We previously created a function display_character() to convert the character design input string to the display grid pattern. We can create another function that can assemble the display line combining multiple characters.

Task 6: Assemble The Greeting Message

The output in Jupyter Notebook (Image by Author)

What’s Next?

If you completed all 6 tasks above, Congratulations! You have completed building a programmatically Generated New Year Greeting using both Python and Julia.

You can also add your own creativity to the output e.g. Changing the colors, Border Decorations, Starts and Shapes, Assigning different colors for text lines within the character line, adding some animation, etc.

The complete code

Python

Julia

The notebooks can also be downloaded from GitHub using the links below.

Even this exercise is completed using Python and Julia, you can try it using your favorite programming language utilizing the same concept and logic.

Disclaimer

The views and opinions expressed in this paper are those of the author and do not represent those of the employer or other institutions related to the author. This article is part of a broader publication aimed at addressing data literacy in the community. The author has put a good amount of effort into researching the topics discussed, simplifying the technical jargon to increase the understanding of the content, finding relevant references to ensure the validity of the facts presented. Discussion, criticism, alternative thoughts, and suggestions are welcome.

References


Learn Programming While Creating a New Year Greeting On Console Output was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.

Published via Towards AI

Feedback ↓