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
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,
- How to print screen output with different options and addingΒ colors.
- Variables andΒ Arrays.
- String manipulations and Concatenation.
- Processing Arrays.
- Generate and use a sequence ofΒ numbers.
- Operators
- Loops (forβ¦)
- Conditional Statements (ifβ¦else)
- Use of built-in functions (print, randomΒ number)
- Creating custom functions to automate repetitive tasks.
- Adding colors to the screen outputΒ text
- 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.
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.
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).
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
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
- Python 3 Documentation. Retrieved January 1,Β 2021.
- Python Colorama library for producing colored terminal text and cursor positioning. Retrieved January 1,Β 2021.
- Numpy. Retrieved January 1,Β 2021.
- Julia 1.5 Documentation. Retrieved January 1,Β 2021.
- Julia Crayons.jl for Colored and styled strings for terminals. Retrieved January 1,Β 2021.
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