Coding Path Questions?

Hello there,

I am relatively new to programming using Codecademy. I am highly interested in wanting to work in a couple of different areas of coding. I am interested in making apps, websites and games. I just recently started with python and am currently at the loops section in my studies. With all this said, am I on the right track with python being my first language?

Thank you for you time and help.

TBH, it’s as good a place to start as any. The language is very straight forward, with easy to learn syntax. It has a great collection of built-in functions and can cover many disciplines, science, maths, information, data, &c. The main thing is to focus on learning all the basics: data structures, algorithms, logic, while acquiring skills with each concept and built-in.

Keep an open mind and don’t try to do something big and complicated. Write simple programs to perform one task and study how to refactor and improve as you go. It all takes time, so set aside lots of it on a regular basis. Do routine review and practice, and experiment until the cows come home. Be sure to keep the documentation close at hand, always, and read it thoroughly for each new concept or built-in. Most of all, don’t try to hurry or jump ahead. Steady as you go…

Great advice!

Thank you so much for your help with this. I feel pretty good with a lot of the concepts I have been learning. There has been challenges as to be expected. Loops that are comprehensible have an interesting syntax to comprehend and is a little bit confusing but I am working through it as best as I can. Lately, I have been trying to alter some of the code during the exercises and it has been helping with practicing the topic at hand which has been helpful.

A few questions maybe you can help me with if you don’t mind.
1.) I know we have an editor built into codecademy which is great. What editor would you suggest to use if I wanted to work on creating my own code?
2.) What would be some examples of how to implement the code I create and apply it to a real world job or personal activity that I enjoy? Just trying to see how python relates to adding my code to accomplish small tasks.
3.) What are frameworks and libraries? Are they a collection of functions that are previously written to apply or import into my python code?
4.) As far as passion projects, I would love to eventually create apps, websites and games. Is python able to accomplish these passion projects or would I have to work with other languages?

Thank you again for your time and help. It is greatly appreciated.

1 Like

Go with the bare-bones latest version of IDLE, which you can download for free from python.org. Master that shell interface/text editor before moving up to a more advanced IDE. IDLE is all I ever use, but I only do small programs and utilities for my own use.

The program can be installed in your User account, so does not need administrative permissions, afaik. It will go into the path,

Users/AppData/Local/Programs/Python/Python3xx

on a Windows machine. Not sure about Mac, or Linux.

When you install, be sure to add a shortcut to your taskbar. When the install is complete, click that shortcut to open the interactive shell. It should look something like,

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 

My version is a little old, but it works for me. Yours will be the newest.

The main menu is pretty simple to understand. To open a new text editor window, click File and select New File. All the common features of a basic text editor are available. Syntax highlighting is built in and customizable, but I would leave that for later. Get completely used to working the default settings.

When you have typed some code, Save in the provided Scripts folder since it is right there and always easy to find. Python defaults to that folder, or the one just above it (where the .exe lives). Click on Scripts, give your file a name and Save.

There is a recent files option in the File menu for convenient access to your most recently saved files. It won’t hurt to create a shortcut to the Scripts folder and pin it to the Start menu. Keep all your Python code in that folder, or in folders inside that one. Back it up to stick once in a while.

When you get the program installed, feel free to ask for assistance.

As to your second question, just take it day to day and think of ways to improve your work flow. For instance, I work with a lot of scientific papers and have my own str_tools module that contains utilities to help me with accessioning new papers into my library (a Users/Geology folder where every author has their own folder). I use the utilities a lot, and they work to my specifications.

One of the utilities is a function called, reverse_order that takes a list of names, and changes from first initial last to, last comma first. It will sort them if I supply a second argument, True.

Eg.

>>> reverse_order('''William L. Griffin
    Elena A. Belousova
    Craig O'Neill
    Suzanne Y. O'Reilly
    Vladimir Malkovets
    Norman J. Pearson
    Zdislav V. Spetsius
    Simon A. Wilde'''.split('\n'), True)
Belousova, Elena
Griffin, William
Malkovets, Vladimir
O'Neill, Craig
O'Reilly, Suzanne
Pearson, Norman
Spetsius, Zdislav
Wilde, Simon
>>>

Note the newline separation.

I can now copy that list into my working notes and compile the catalog entries which then get added to another Python file, catalog.py that mirrors the folder structure inside Geology. The file is one long newline separated string.

Another file I maintain is the name index, geology_dir.py which is an alphabetical list, as in list object. When I create the list above, I check the index to see if the name is already recorded (meaning there is a folder in the volume) and if not, I insert it into the list and immediately create a new folder by the same name.

Another string utility I use often is, title():

>>> title('The origin and evolution of Archean lithospheric mantle')
'the Origin and Evolution of Archean Lithospheric Mantle'
>>> 

The title (mind the different example) then gets whittled down to become the file name.

2014_Griffin_HadeanArcheanCrustMantleEvolution.pdf

Now that I have a name for my local file, and a folder awaiting it, I then download the file with that name and save it in the primary author’s folder. I compose the catalog entry, or update the existing one.

Eg.


Griffin, William
	2003_Griffin_OriginEvolutionArcheanLithosphericMantle.pdf
	2014_Griffin_HadeanArcheanCrustMantleEvolution.pdf
Griffin, William\et al
	[]

To save space the PDF file is only saved in the primary author’s folder, nowhere else. All the other named co-authors get a shortcut to this file added to the, et al folder inside their folders.


O’Neill, Craig
	{}
O’Neill, Craig\et al
	2014_Griffin_HadeanArcheanCrustMantleEvolution

Note the empty line above and below the entry. This is an entry separator, as in, '\n\n'.

I call this a “poor man’s database”. At the same time, I maintain a stick as a backup and update that each time new items are added to the main volume. It has one folder, ‘Geology’ that mirrors the local volume, and one folder, shortcuts/Geology that also mirrors the local volume, but the shortcuts are to the file on the stick so it can work in any machine.

The backup process also involves a working notes file where I construct the entries that go into my cross-reference file, tracking every shortcut and confirming each step.

None of this is automated. It’s all manual, hands on work. Python is my assistant, and can help me audit the catalog and index, do string operations, search and collate, and so on.

Bottom line, keep practicing and eventually you will find ways to put Python to work for you. It’s just a language which promises certain things. We are the ones who will fashion practical code to meet our needs as they arise.

Frameworks are something you may or may not get involved in. There are some frameworks for webpages, or apps, but I know nothing about that. I’m strictly a scratch programmer.

Libraries are modules that can be imported that contain select programs (functions or classes) and they are generally purpose based. Take for instance the math library:

>>> import math
>>>

It contains all the essentials for doing maths: Constants, functions, etc.

There are many libraries out there, and some do come bundled with your install.

  • math
  • datetime
  • functools
  • itertools
  • random

The documentation will help you familiarize yourself with what’s built in, but not a lot about what will need to be brought in from elsewhere. This can all wait for the time being. Just focus on what is on your machine, at time of installation.

Everything in Python is either an object or a module. We can create our own modules to fit our own needs, such as the one described above:

>>> from str_tools import reverse_order, title

Anyway, best let you get on with your work. Take the weekend to familiarize yourself with the shell, IDLE, and learning what you have on board. As always, we’re here anytime you have questions.

1 Like

Hello @mtf !

Thank you for being so thorough and helping me with all the questions I had. I am excited about continuing to learn and applying it to my future coding endeavors. I will for sure check out IDLE. Thank you for also sharing what you have built. I think it is really cool what you have been able to accomplish.

I will definitely reach out as soon I have any other questions.

Thank you again for your time.

1 Like

Definitely install IDLE. No questions asked. It’s a no-brainer.

When you have the interactive shell open, perform some basic code task, like,

>>> from random import randint as rand
>>> print (rand(1, 100))
73
>>>

You can now save this work, even in the Shell. Click File, then Save As and create a new folder, Shells then save it with today’s date, ‘20240301.py’ and now look at the title bar of the Shell. Every time you run an experiment, just Save and it will all be logged in that file. You never need to lose your work, even in the Shell. Any time you open a new Shell, repeat this procedure and never lose your trial work again. Note that it is just a text file.

1 Like

Errata

Users/%You%/AppData/Local/Programs/Python/Python3xx/
1 Like

@mtf That is great to know! I am looking forward to messing around with some of the modules and writing some code. I was just reading some of the documentation on the python site and it is cool how there is so much information on the language. I am looking forward to seeing what cool things I can make with python.

1 Like

Hello @mtf!

I hope you are doing well today. I have been taking my time and going back into the material in which I didn’t understand. Good news is going through the material the 2nd time allowed the information to stick much better. I am having an issue understanding the following code:

hairstyles = [“bouffant”, “pixie”, “dreadlocks”, “crew”, “bowl”, “bob”, “mohawk”, “flattop”]

prices = [30, 25, 40, 20, 20, 35, 50, 35]

last_week = [2, 3, 5, 8, 4, 4, 6, 2]

total_price = 0

#created a loop to sum up the total of all our prices for our cuts

for price in prices:

total_price += price

#created a variable to get the average price of our cuts

average_price = total_price/len(prices)

#printing out the average price of our cuts

print(“The average price of our cuts are:”, average_price, “\n”)

#prices were too expensive. Created a for loop to cut the price of each haircut but $5 using a compreshive list

new_prices = [price - 5 for price in prices]

print(“The new price for each of our custs are:\n”, new_prices, “\n”)

#finding out the total revenue of our income from last week

total_revenue = 0

for i in range(8):

total_revenue += prices[i] * last_week[i]

print(“Total Revenue is:”, total_revenue, “\n”)

#Finding out our daily average of our total_revenu

average_daily_revenue = total_revenue / 7

print(“Your average daily revenue is:”, average_daily_revenue, “\n”)

#list comprehension to advertise haircuts that are under 30 dollars

cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]

print(“Here are the cuts that are under $30 dollars:”, cuts_under_30)

I have no idea what this comprehensive list above is doing when it shows i in range(len(new_prices))

Any help is greatly appreciated.

Best Regards!

The range is used to generate indices and the length is needed to know how many indices to generate. We cannot reach non-existent indices so must have a stopping point.

We know that both lists have the same length since one corresponds with the other, hence, hairstyles[i] and new_prices[i].

2 Likes

Hello @mtf,

Thank you so much for your response. I really appreciate you taking the time to help.

In the following code: cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]

I had originally thought cuts_under_30 = [hairstyles[i] for i in new_prices[i] if new_prices[i] < 30]

would have worked.

Do you happen to know why it wouldn’t work since new_prices are the same length as that of hairstyles?

Thank you for your time and help.

If it actually works (which I doubt), it will only iterate on that one value, assuming it is not a number. new_prices[i] is a single value. If the value is a number it will raise an exception since numbers are not iterable.

Now consider when we write,

for x in iterable:

x is not an index. It is a value. The iterable is iterated over from left to right, without the need for an index. I have always called this a, ‘read-only loop’ since we cannot mutate the list inside this loop.

We need the index since we are polling two corresponding lists, not by value, but by position in the list.

Hello again @mtf

Thank you for being so patient with me in regards to understanding this material. I appreciate your response. I still need help if you can help me.

In the following code: for i in range(8):
total_revenue += prices[i] * last_week[i]

print(“Total Revenue is:”, total_revenue, “\n”)

I believe that the code is able to go through prices[i] and last_week[i] and get the data within list’s elements and give the total_revenue. Which makes sense to me but when looking at the following code:

cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]

I am seeing a variable that is assigned to cuts_under_30 which will print the hairstyles[i] which I can understand. But when I look at the next part of the code i see "for i in range(len(new(new_prices)) if new prices[i] < 30
This part is confusing to me mostly where we see "for i in range(len(new_prices))

I don’t yet understand why I couldn’t use for i in new_prices[i], if new_prices[i] should iterate through this list and determine if new_prices[i] < 30.

Sorry for seeming so lost. I really want to understand this concept and I am needing baby steps help lol. Thank you for your time and patience with me.

I am now learning functions which seem to be pretty good so far. I learned you can declare variables within a user defined function and return the variable you are needing info from which is pretty cool.

I also got the chance to read some documentation on new built in functions like max(), min() and round(). Had to read some python documentation and the only documentation that tripped me up with round(). I didn’t know that i can pass an argument for the decimal place. Oh well I guess this part of the journey. lol

Thanks again for your time and help

Consider,

hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]
prices = [30, 25, 40, 20, 20, 35, 50, 35]
last_week = [2, 3, 5, 8, 4, 4, 6, 2]

All three of the above objects have an __iter__ attribute. They are iterable and subscriptable. And we know that they correspond, by position.

Just to illustrate,

>>> n = 3
>>> h, p, w = hairstyles[n], prices[n], last_week[n]
>>> print (f" Style: {h}\nPrice: {p}\nLast Week: {w}")
    Style: crew
    Price: 20
    Last Week: 8
>>> 

Okay, so we have the corresponding relationship between the three lists. With that knowledge, we can work with multiple lists at a time and carry out actions as apply.

The first action is to use a list comprehension to reduce the price by $5 and assign the discounted prices to a new price list:

new_prices = [price - 5 for price in prices]

Here is where we need to be sure you are getting the picture, as in understand what you see, above. I’ll leave you to reply.

1 Like

Hello @mtf,

Thank you so much for the help with question I had. I am onboard with understanding now that the lists are iterable and subscriptable. Got it!

I haven’t see the code below before that you had written. Would you be able to explain that please?

print (f" Style: {h}\nPrice: {p}\nLast Week: {w}")
Style: crew
Price: 20
Last Week: 8

Now that I know lists are iterable and subscriptiable (I can use “i” for a variable like in haristyles[i]), Can you help me understand

cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]

The whole range new_prices thing above is really messing with me.

Thank you as always and I look forward to hearing from you soon.

>>> n = 3
>>> h, p, w = hairstyles[n], prices[n], last_week[n]
>>> print (f" Style: {h}\nPrice: {p}\nLast Week: {w}")
    Style: crew
    Price: 20
    Last Week: 8
>>> 

The >>> is the command prompt in the Python interactive Shell. Each line is entered, one at a time right into the shell. Any execution is immediate.

The second line is a feature of Python, multiple assignments. Any time Python sees a sequence (comma separated expressions) on the right hand side it treats it as a tuple. We can unpack the tuple with an assignment (to the left hand side of =) just by having variables waiting for the unpacked values. Above there are three values packed on the right side, so three variables to unpack on the left side.

If you are not yet familiar with tuples, they are very much like lists, but immutable. We can create a tuple, but we cannot change, add or remove any values to the sequence like we can with a list object.

>>> z = (4, 7, 11, 16, 21)
>>> type (z)
<class 'tuple'>
>>> z[1]
7
>>> z[1] = 9
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    z[1] = 9
TypeError: 'tuple' object does not support item assignment
>>> 

Likewise we cannot .pop(), .append(), or .insert() any data. Try it and see what to expect. Unpacking (without removing any items), is totally fair game.

>>> a, b, c, d, e = z
>>> a
4
>>> e
21
>>> 

As for the print statement, it uses the latest iteration of template interpolation and formatting called, f-string which you can read up online to learn about the various type supports, spacing, padding, etc. I’ll leave that for you to learn on your own time. I recommend using this type of print formatting in all your future work and forget about concatenation and .format(). They are old hat.

Note where the f is placed. Always outside of the string, immediately before the quote, no spaces.

 f"..."

Now lets look at the two functions in your comprehension:

  • range()
  • len()

range() returns a range object that is in sequence, lowest on the left, highest on the right (typically) and is used in the above example to generate indices for the list, new_prices. We need to know the length of the list in order to create a valid range. The len() function can be used on any iterable, including tuples:

>>> len(z)
5
>>> range(len(z))
range (0, 5)
>>> list(range(0, 5))
[0, 1, 2, 3, 4]
>>>

The initial value (start of the range) defaults to zero if not specified.

>>> list(range(5))
[0, 1, 2, 3, 4]
>>>

The upper value we specify will NOT be in the range, but we will have that many indices to work with in our for loop.

>>> for i in range(len(z)):
        print (i)

4
7
11
16
21
>>> 

Like above, I’ll leave you to look up the documentation and learn about all the ways we can use range() to generate any sequence, forward, backward, by two’s, by three’s, by n, etc.

Last note, a range object is not a list, but a non-consumable iterator. You’ll learn about this later, so don’t dwell on it now. Just know that it is an object that can be iterated and re-used. What’s cool about the object is that no matter how large the sequence, it always takes the same amount of memory, a small amount at that. As I recall, 48 bytes.

>>> from sys import getsizeof
>>> r = range(100)
>>> getsizeof(r)
48
>>> r = range(1000)
>>> getsizeof(r)
48
>>> 

What this means is that when we have a sequence, don’t store it as a list. Leave it as a range. A thousand item list will use up thousands of bytes of memory. We only ever need a list if we need to access a data point within the list. Even then, all we need is a shorter range of the same sequence, plus one, then capture the last value. More on this later when you get a little more into the esoterics of programming with Python. For now concentrate on what’s in front of you in the lessons.

Always here if you still need more answers.

1 Like

Unless you deliberately did so as an attention check, the code

z = (4, 7, 11, 16, 21)
for i in range(len(z)):
    print(i)

will not print 4, 7, 11, 16, 21 (on separate lines). It will print 0, 1, 2, 3, 4 (on separate lines).

To print the actual elements,

z = (4, 7, 11, 16, 21)
for i in range(len(z)):
    print(z[i])

# OR

z = (4, 7, 11, 16, 21)
for i in z:
    print(i)
1 Like

Was buzzing along and letting my fingers do the walking. D’oh! Shows what not testing can result in. Touché!

1 Like

@mtrtmk @mtf

Hey guys!

Thank you so much for all your help with me trying to understand this material. I been progressing and reading over your comments left here in the forum.

Please correct me if I am wrong. We are using the rang() to generate indices for the new_prices list in the following code:

cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]

Then the len() will allow us to access each item in that list?

Sorry to beat a dead horse with a stick but I am hoping this is correct?

As a side note, I am excited to say I have been working with functions. So far so good I think … lol!

Thank you guys for all your help and time.

1 Like

The length will tell us how many elements are in the list (the iterable) which plugs directly into range() to give us corresponding indices, as you observe.

Sometimes variable names can make something look more complicated than it is. For that reason, in your practice, use symbols rather than long names.

y = [x for x in s if x]
     1     2    3   4

Break it down:

      1             2           3         4
[ expression for variable in iterable conditional ]

We’ve seen that range() returns an iterable range object. When using a range, we iterate that, and not the lists, proper. In the above example we iterate a list directly and expose values from left to right.

for x in s

The above is what I call a ‘read-only’ loop as it allows us to iterate over the values, but we cannot mutate them.

for i in range(len(s))

The above is what I call an ‘accessor loop’ as it supplies the indices to values that we can access and/or mutate by index.

1 Like