Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts


This is work completed for an assignment for Ashford University's CPT200: Fundamentals of Programming Languages

Problem:

The colors red, blue, and yellow are known as the primary colors because they cannot be made by mixing other colors. When you mix two primary colors, you get a secondary color, as shown here:
  • Red and blue = purple
  • Red and yellow = orange
  • Blue and yellow = green
#Note: The assignment called for lists to be used but I opted for a tuple because I don't think the primary colors are changing any time soon. 

Script:
primary_colors = ('red', 'yellow', 'blue')
user_input = ''

print('*******************************************')
print('*                                                         *')
print('*      Welcome to the Color Mixer!      *')
print('*                                                         *')
print('*******************************************\n')

def get_color(ordinal):
    color = input(f'{ordinal} primary color: \t').lower()
    if color in primary_colors:
        return color
    else:
        print('Invalid entry, please enter red, yellow, or blue')
        return get_color(ordinal)

def mix_colors(color1, color2):
    print('\nMixing colors...')
    if color1 == color2:
        return color1.capitalize()
    elif (color1 == 'red' and color2 == 'blue') or (color1 == 'blue' and color2 == 'red'):
        return 'Purple'
    elif (color1 == 'yellow' and color2 == 'blue') or (color1 == 'blue' and color2 == 'yellow'):
        return 'Green'
    else:
        return 'Orange'

def display_results(color1, color2, mixed_color):
    print(f'{color1.capitalize()} and {color2.capitalize()} = \t{mixed_color}\n')

def keep_going():
    global user_input
    try: 
        user_input = input("Enter 'q' to quit or press any other key to continue mixing colors: \t")[0:1].lower()
    except:
        print('Invalid entry!')
        keep_going()

while user_input != 'q':
    print('\nPlease enter two primary colors (red, yellow, blue).')
    color1 = get_color('First')
    color2 = get_color('Second')
    result = mix_colors(color1, color2)
    display_results(color1, color2, result)
    keep_going()
else:
    print('Goodbye!')

Results:


Ideas for Rework and expansion:
  • I like the idea of importing colorama and formatting the output so that there is some actual color involved. 
  • I've seen this done using dictionaries and lists for comparison, could refactor it to accomodate that. 

Hope this helps, leave me feedback if you'd like to see something specific!


Python has many different containers available, here we'll cover a couple of them
Containers are objects “which contain references to other objects instead of data” and are used to group related variables together (3.2)
There are many types of containers to include:
  • lists
  • dictionaries
  • tuples
  • and more…
Lists
Lists are Python’s version of arrays and are declared using square brackets []. Lists are ordered sequences that can hold a variety of object types (not limited to a single type). For instance,
my_list = [‘one’, 2, 3.0]]
holds a string, an int, and a float.
Lists support indexing, where elements are accessed by their sequential order, starting from 0. In the above example:
  • my_list[0] holds a value of ‘one’
  • my_list[1] holds a value of 2
  • my_list[2] holds a value of 3.0
Objects in a list can also be referenced from right to left:
  • my_list[0] holds a value of ‘one’
  • my_list[-1] holds a value of 3.0
  • my_list[-2] holds a value of 2
Slicing
Lists also support slicing, which is sort of like an expanded capability of indexing. The syntax for slicing is:
object_to_be_sliced[start:stop:step]
Like slicing with strings, slicing of list enables you to grab a subsection of the sequential objects using indexes.
Example:
my_nums = [0,1,2,3,4,5,6,7,8,9,10]
print(my_nums[0:6])
>> [0,1,2,3,4]  
#Note that this goes up to but does not include the stop index
print(my_nums[0::2])
>>[0,2,4,6,8,10]
#Step is hoe many indexes are skipped with each iteration

print(my_nums[::-1])
>> [10,9,8,7,6,5,4,3,2,1,0]
#Using only a step value of -1 returns the list reversed 
print(my_nums[0:10:3])
>> [0,3,6,9]

Dictionaries:
In contrast to list, dictionaries are unordered mappings for storing objects. Dictionaries store objects in key-value pairs wherein the key is a string which is used to retrieve its associated value.
Consider a dictionary of object – price key-value pairs:
menu_prices = {‘cheesburger’:2.99, ‘dbl_cheeseburger’: 3.99,’bacon_cheeserburger’: 3.49, ‘bacon_dbl_cheeseburger’: 4.49}
menu_prices[‘bacon_cheeseburger’]
>> 3.49

Unlike lists, dictionaries do not support indexing or slicing, which is really the deciding factor in whether to use a list or a dictionary. It comes down to whether you need/intend to use indexing/slicing.
Like lists, dictionaries can contain multiple object types simultaneously, to include nested dictionaries and nested lists. 
Both lists and dictionaries are mutable, meaning the values can be changed. 

Python variables do not need explicit declaration to reserve memory space. 

Here I will:
  • Describe the difference between explicit typed variables and implicit typed variables using examples.
  • In large scale applications, explain whether or not explicit declaration has a better impact over implicit declaration.

Type expression can be either explicit or implicit. 

  • Explicit typed variables are manually set. That is their type is stated clearly and in detail.
  • Implicit typed variables are typed by their context. 

Is there any performance difference?

Strictly speaking, there shouldn't be much (if any) performance difference when it comes to the use of implicit declaration vs explicit declaration in large scale applications.
The key is that variables don't have types, per se - values do. In Python, variables aren't so much declared (as in other languages), rather variables are assigned a name. 
  • If I were to say myint = 5, then I should be able to infer pretty easily that x is an int. 
  • Similarly, myfloat = 2.0 is quite clearly a floating point number. 
  • And mystring = "I'm a string" is quite clearly a string. 

With all that said...

I've always been under the impression that explicit typing lends itself toward easier maintainability of code, which is important when the majority of the work done on code is maintenance. 
Honestly, I think this will be my first time grappling with a dynamically typed language and the paradigm shift is...interesting. 

What are your thoughts?




Pete the Piranha Scratch Project: https://scratch.mit.edu/projects/317422602/

Compelled to do so by an assignment for my INT100 coursework, I created a relatively simple game in MIT's block language Scratch. The link to the project is above but I enjoyed making the game and it appears that my wife, kids, friends, and coworkers are all fans. So it's inspired me to recreate the game as a mobile app! Will provide more info on this as work on that app progresses. 

Having made simple programs before, Scratch proved to be a bit of a headache at for two reasons.
  1. There’s a learning curve associated with the graphic user interface and the specific limitations of the language.  
  2. Having to hunt for the appropriate block(s) when I could have typed out the code was frustrating.

How did I get around these issues?

These difficulties were primarily solved by a thorough use of Google and Youtube, as well as looking at projects that other people have shared. What I gained from this experience were some insights into how modern games are coded and how variables in the program are manipulated to provide some of the mechanics for the game.

Assessment of the languages
It’s plainly evident that Scratch makes programming many simple programs significantly easier. The exercises involving Python, named for Monty Python, were my first real experience programming in the language and, to be frank, it also took some getting used to. Given my recent self-education in C++ and C#, the differences in syntax required constant attention. That said, I would prefer Python over Scratch for most software development projects given what I can only assume are numerous limitations that Scratch has as a very high-level language.

The differences in these languages stem from the era of their development. Machine language is a means of communicating with a CPU in binary. Humans have had thousands of years to develop languages comprised of thousands of symbols and phonemes in order to communicate complex messages – while communication of this nature is possible in binary it is very difficult. As such, Assembly language was developed to make it easier for programmers to instruct CPUs in a human-readable manner.  

Python is a comparatively new high-level language which utilizes indentation, common amongst programmers for increased readability, instead of curly-brackets to structure its programs and scripts into blocks and it significantly easier to work with than Assembly language. Scratch is a block programming language created to help children learn to break problems into chunks of logic and apply that logic toward the creation of programs – that is, to help children learn to think like programmers.

Machine code is used anywhere a traditional computer is in use – higher-level languages are translated into machine code. This includes assembly language which is typically found in drivers and the like. While you could accomplish in assembly anything you could with higher level languages, it becomes impractically long and difficult to debug. Python, on the other hand, can be used to create desktop programs, web applications and more. Recently, it has gained popularity as a language for data analysis. Scratch is useful for its intended purpose – helping newcomers to the art of programming learn to think in a way that enables them to create programs from code.

Which language is most popular? – That depends on how popularity is defined. 

Of those discussed, Machine language is certainly the most omnipresent (as nearly all programs are eventually converted into those ones and zeros), however Python is most likely to be selected for nearly any software development project not requiring direct processor interaction. It’s comparative ease of use without the limitations of a language like Scratch make it ideal for most development (in comparison to the languages discussed herein).