vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You are better off drawing three triangles ...

''' turtle_triangle_up.py
use Python module turtle to draw a triangle pointing up
draw three triangles and fill with different colors
'''

import turtle as tu

tu.title("triangle up")

def triangle_up(x, y, side, color='black'):
    """
    draw an equilateral triangle of size side starting at
    coordinates x, y (lower right corner of triangle)
    color is pen/fill color
    """
    tu.up()  # pen up
    tu.goto(x, y)
    tu.down()  # pen down
    tu.color(color)
    tu.begin_fill()
    for k in range(3):
        tu.left(360/3)
        tu.forward(side)
    tu.end_fill()


# optional ...
# speeds from 1 to 10 enforce increasingly faster animation
tu.speed(speed=8)

# center is x=0, y=0
side = 250
x1 = 0
y1 = 0
triangle_up(x1, y1, side, 'red')
# use Pythagorean theorem to calculate offset
h = (side**2 - (0.5*side)**2)**0.5
w = ((0.5*side)**2 - (0.5*h)**2)**0.5
x2 = w
y2 = -h/2
triangle_up(x2, y2, side, '#00d900')  # mod-green
# now draw smaller yellow triangle
triangle_up(x1, y1, side/2, 'yellow')


# keep showing until window corner x is clicked
tu.done()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you can't be replaced, you cannot be promoted!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

My neighbor made beefstew and I brought the beer.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have a lot of tension and you get a headache, do what it
says on the aspirin bottle: Take two and keep away from children.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A fine is a tax for doing wrong.
A tax is a fine for doing well.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Short skirts have a tendency to make men polite. Have you ever seen a man get on a bus ahead of one?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sometimes it's easier to pick an image from the internet to display in your Python Tkinter GUI toolit program.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Print a simple table using the string format function ...

''' format_table101.py
an example of a table created with format()
'''

# name,age,weight lines read from a csv file
data_str = """\
Heidi Kalumpa,36,127
Frank Maruco,27,234
Larry Pestraus,19,315
Serge Romanowski,59,147
Carolus Arm,94,102
Michel Sargnagel,21,175"""

# create a list of [name, age, weight] lists
data_list = [line.split(',') for line in data_str.split('\n')]
#print(data_list)  # test

# header list
header = ['Name', 'Age', 'Weight']

sf = "{:<18s} {:>6s} {:>7s}"
print(sf.format(*header))
print('-'*33)
for sublist in data_list:
    # unpack the sublist with *
    print(sf.format(*sublist))
print('-'*33)

''' result ...
Name                  Age  Weight
---------------------------------
Heidi Kalumpa          36     127
Frank Maruco           27     234
Larry Pestraus         19     315
Serge Romanowski       59     147
Carolus Arm            94     102
Michel Sargnagel       21     175
---------------------------------
'''
Slavi commented: Good one +6
BustACode commented: Thanks. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

We have had several snippets on the format() function. This one gives a condensed overview of the many options you have.

ddanbe commented: Nice overview. +15
mattster commented: Looks good ;) +7
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

By the time a programmer removes the last bug, the software is obsolete.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Programmers not only byte, the also nibble a bit.

(nipple was wishful thinking, corrected, thanks RJ)

Reverend Jim commented: Nipple? +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Counting days ...

''' datetime_diff_days103.py
get the difference in days between 2 given dates
'''

import datetime as dt

# user enters dates in yyyy-mm-dd format
dt_str1='2014-05-11'
dt_str2='2014-09-11'

date1 = dt.datetime.strptime(dt_str1, "%Y-%m-%d")
date2 = dt.datetime.strptime(dt_str2, "%Y-%m-%d")

date_diff = date2 - date1
print('Difference in days = {}'.format(date_diff.days))

''' result ...
Difference in days = 123
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

print("Oct{0:o} = Dec{0:d}".format(25))

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I get errors when I try to compile this code ...

typedef struct n{int a:3,
b:29;struct n*c;}t;t*
f();r(){}m(u)t*u;{t*w,*z;
z=u->c,q(z),u->b=z->b*10,
w=u->c=f(),w->a=1,w->c=z->
c;}t*k;g(u)t*u;{t*z,*v,*p,
*x;z=u->c,q(z),u->b=z->b,v
=z->c,z->a=2,x=z->c=f(),x
->a=3,x->b=2,p=x->c=f(),p
->c=f(),p->c->a=1,p->c->c=
v;}int i;h(u)t*u;{t*z,*v,*
w;int c,e;z=u->c,v=z->c,q(
v),c=u->b,e=v->b,u->b=z->b
,z->a=3,z->b=c+1,e+9>=c&&(
q(z),e=z->b,u->b+=e/c,w=f(
),w->b=e%c,w->c=z->c,u->c=
w);}int(*y[4])()={r,m,g,h};
char *sbrk();main(){t*e,*p,*o;
o=f(),o->c=o,o->b=1,e=f(),
e->a=2,p=e->c=f(),p->b=2,
p->c=o,q(e),e=e->c,(void)write
(1,"2.",2);for(;;e=e->c){q(e),
e->b=write(1,&e->b["0123456789"],
1);}}t*f(){return i||(i=1000,
k=(t*)sbrk(i*sizeof(t))),k+--i;
}q(p)t*p;(*y[p->a])(p);}

I am using Windows7.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I have used module prettytable in the past this way ...

''' prettytable102.py
explore module prettytable

get
prettytable-0.7.2.zip
from
https://pypi.python.org/pypi/PrettyTable
extract the zip file and copy prettytable.py to /Lib/side-packages
'''

from prettytable import PrettyTable

mylist = [['a', 'b', 'c'], ['a', 'b', 'c'],
['a', 'bbbbbbbbbbbbbbbbbbb', 'c'],
['k', 'k', 'l'], ['a', 'b', 'c']]

header = ["Column1", "Column2", "Column3"]
pt = PrettyTable(header)
# left align the following columns (center is default)
pt.align["Column1"] = "l"
pt.align["Column2"] = "l"
pt.align["Column3"] = "l"
# space between column edges and contents (1 = default)
pt.padding_width = 2

for sublist in mylist:
    pt.add_row(sublist)

print(pt)

''' result ...
+-----------+-----------------------+-----------+
|  Column1  |  Column2              |  Column3  |
+-----------+-----------------------+-----------+
|  a        |  b                    |  c        |
|  a        |  b                    |  c        |
|  a        |  bbbbbbbbbbbbbbbbbbb  |  c        |
|  k        |  k                    |  l        |
|  a        |  b                    |  c        |
+-----------+-----------------------+-----------+
'''

Gribouillis' module is smoother.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example ...

# use a Tkinter label as a panel/frame with a background image
# (note that Tkinter reads only GIF and PGM/PPM images)
# put a button on the background image

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

root = tk.Tk()
root.title('background image')

# pick a .gif image file you have in the working directory
# or give full path to the image file
image = tk.PhotoImage(file="roses.gif")
# get the width and height of the image
w = image.width()
h = image.height()
# position coordinates of root 'upper left corner'
x = 200
y = 50
# size the root to fit the image
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# tk.Frame has no image argument
# so use a label as a panel/frame
panel = tk.Label(root, image=image)
panel.pack(side='top', fill='both', expand='yes')

# put a button widget on the panel
button = tk.Button(panel, text='button widget')
button.pack(side='top', pady=5)

# save the panel's image from 'garbage collection'
panel.image = image

# start the event loop
root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A dictionary in this case would be a list of special names you expect to find. Simply create a text file with each name on its own line that you can read into Python code and form a list or a set (removes any duplicates). You could assume that each name starts with a capital letter, be it the name of the composer, performer, group, title etc.

Start with a small list for testing and add more names as you find them.
You might be able to find these special names on the internet.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Computers make excellent and efficient servants, but I have no wish to serve under them."
... Spock, Star Trek

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Japan has the largest public debt of any country on Earth with 226% of GDP.
That makes Greece with 144% of GDP, Belgium with 97%, and the USA with 72% look harmless.

The numbers at
https://www.cia.gov/library/publications/the-world-factbook/rankorder/2186rank.html
are mostly 2013 values.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An example ...

# assume you have this url ...
url = "https://www.python.org/downloads/release/python-343/"
# the base (scheme + netloc) would be ...
base = "https://www.python.org/"
# the path would be ...
path = "downloads/release/python-343/"
# however you want to select one of these paths ...
path_list = ["community/", "doc/", "community/jobs/"]

# to create a full url use ...
new_url = urlparse.urljoin(base, path_list[2])
print(new_url)  # https://www.python.org/community/jobs/
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One more addition. You can turn a function into a loop ...

int countdown_loop(int count) {
  // a recursive function to count down from count to zero
  cout << count << "  ";
  if (count == 0)
    return 0;
  else
    return countdown_loop(count - 1);
}
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Nice tutorial!
Sometimes an endless loop comes in handy ...

  // an endless loop with break condition
  int k = 0;
  while(true) {
    k++;
    cout << k << "  ";
    if (k >= 10)
        break;
  }

You can put this into a function and replace break with return.

Also, put your deeply nested loops into a function and use return instead of the much besmirched goto.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am finding out that Go is unforgivingly strict with data typing.

Wit ...

// data_typing_test101.go
// Go 'gotcha' stuff

package main

import "fmt"

func main() {

    fmt.Println(7 + 3.14) // 10.14
    fmt.Println(5 / 2)    // 2
    fmt.Println(5 / 2.0)  // 2.5

    var a int = 5
    fmt.Println(a / 2.0) // 2  oops! gotcha!

    // console wait till enter is pressed
    fmt.Println("\nPress Enter key ...")
    fmt.Scanln()
}

In C++

    int a = 5;
    cout << a / 2.0 << endl;  // 2.5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This might help ...
http://pymotw.com/2/urllib/

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To return several labels, return the layout in which the labels are ...

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

class LabelApp(App):
    def build(self):
        mytext2 = str(1234567)
        self.label2 = Label(text=mytext2, font_size=60)
        mytext3 = str(7654321)
        self.label3 = Label(text=mytext3, font_size=60)
        layout = BoxLayout(orientation='vertical')
        layout.add_widget(self.label2)
        layout.add_widget(self.label3)
        # return layout containing several widgets                
        return layout

LabelApp().run()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

How about ...

from kivy.app import App
from kivy.uix.label import Label

class LabelApp(App):
    def build(self):
        mytext = str(1234567)
        # you can only return one widget, aka the root widget
        return Label(text=mytext, font_size=60)

LabelApp().run()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

At first create a folder like Atest in your Python directory C:\Python34 where you can save your newly created Python files.

On your Windows machine there should be a file called idle.bat in the folder
C:\Python34\Lib\idlelib
Double click on idle.bat and the IDE that comes with your Python installation called IDLE will come up.

If it comes up with a nice clean Editor Window, you can start typing Python code into it. For instance ...

''' hello.py
my first Python code
ask for a name and print a hello message
'''

name = input("Enter your name: ")
# {} is a placeholder for the name
print("Hello {}".format(name))

Put information/comments between the ''' ''' or in a line starting with a # character. These code lines are for your info and will be ignored by the Python interpreter.

The nice thing about an IDE is that you can run the code you have written directly from IDLE by pressing the F5 key. If your code has not been saved as a file, you will be prompted to do so. Save the code to a file, call it something like hello.py (the .py extension indicates a Python code file) in your Atest folder. After saving, a new window will pop up called the Shell Window, where the code is executed. So it will ask you for your name, type it in and press Enter. The comment line will be ignored, the print() function will execute next.

The Shell …

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is one example that might help ...

""" tk_treeview101.py

see also ...
http://stackoverflow.com/questions/16746387/tkinter-treeview-widget
"""


import os
try:
    # Python2
    import Tkinter as tk
    import ttk
except ImportError:
    # Python3
    import tkinter as tk
    import tkinter.ttk as ttk


class DirectoryBrowser(tk.Frame):
    def __init__(self, master, path):
        self.path = os.path.abspath(path)
        self.entries = {"": self.path}
        self.root = None

        # setup treeview and scrollbars

        tk.Frame.__init__(self, master)
        self.tree = ttk.Treeview(self)

        ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
        xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview)

        self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.tree.heading('#0', text='Path', anchor='w')
        self.tree.bind("<<TreeviewSelect>>", self.update_subtree)

        # fill treeview with root dir and the subdirs
        iid = self.insert("", "end", self.path)
        self.tree.focus(iid)
        self.process_directory(iid, self.path)

        # add tree and scrollbars to frame
        self.tree.grid(in_=self, row=0, column=0, sticky="nsew")
        ysb.grid(in_=self, row=0, column=1, sticky="ns")
        xsb.grid(in_=self, row=1, column=0, sticky="ew")

        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        self.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.Y)

        # testing ...
        # returns a list of children belonging to last iid
        print(self.tree.get_children(iid))

    def insert(self, parent, index, path, name="", **kwargs):
        """
        add new element to TreeView
        """
        if "text" in kwargs:
            err = "arg 'text' not available"
            raise ValueError(err)

        kwargs["text"] = path
        if name:
            kwargs["text"] = name

        iid = self.tree.insert(parent, index, **kwargs)
        self.entries[iid] = path
        return iid

    def process_directory(self, parent, path, depth=3):
        if depth == 0:
            return
        for p in os.listdir(path):
            abspath = os.path.join(path, p)
            if os.path.isdir(abspath):
                iid = self.insert(parent,
                                  'end',
                                  path=abspath,
                                  name=p,
                                  open=False)
                self.process_directory(iid, abspath, depth-1)

    # Callbacks

    def update_subtree(self, event):
        iid = self.tree.focus()
        path = self.entries[iid]
        print("%s: %s" % (iid, path))
        print(iid in self.entries.keys())
        #self.process_directory(iid, path)


def test():
    root = tk.Tk()
    mypath = "C:/Python34"
    app = DirectoryBrowser(root, path=mypath)
    # testing …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

As I keep playing with Go I keep finding little gems.

You can use
var name string = "Frank"
or its shorthand version
name := "Frank"

The := operator is really an assignment and infer type operator. In Pascal it is only assignment..

You could also have used

var name string
name = "Frank"

The := operator comes in handy, for instance the usual for loop can be written this way ...

for k := 0; k < 10; k++ {
  // do something inside the loop
}

... since you assign integer 0 to k, it will be type integer by inference.
A little bit like C++ int k = 0.

Somewhere is also a big integer package. Need to read up on that.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can only edit within one hour after posting.

Try this ...

import datetime as dt

now = dt.datetime.today()
year = now.year
# Persian new year march 21 at 2:15:11
pnewy = dt.datetime(year, 3, 21, 2, 15, 11)
differ = pnewy - now
print("There are {} seconds till Persian New Year".format(differ.seconds))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something like this ...

mylist = [2,4,4]
number = int("".join(str(n) for n in mylist))
print(number, type(number))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Can be as simple as ...

import pip
print(pip)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

PyCharm is a pretty complex IDE for beginners.
Why not start with the Idle IDE that comes with Python?

Also check out ...
http://ninja-ide.org/
Ninja is free

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This will do, create a custom list append ...

def list_append(item, tlist=[], limit=3):
    '''
    append max limit items to a list
    list cannot exceed given limit size
    '''
    if len(tlist) < limit:
        tlist.append(item)
    return tlist

# testing
mylist = list_append('red')
print(mylist)

mylist = list_append('green')
print(mylist)

mylist = list_append('blue')
print(mylist)

mylist = list_append('orange')
print(mylist)

''' result ...
['red']
['red', 'green']
['red', 'green', 'blue']
['red', 'green', 'blue']
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
mylist = [6, '/', 3, '+', 9, '+', 8, '+', 1, '/', 2]
print(mylist)
# replace mylist with an empty list
mylist = []
print(mylist)   # --> []

mylist = [6, '/', 3, '+', 9, '+', 8, '+', 1, '/', 2]
# delete part of a list, keep the first 7 elements
del mylist[7:]
print(mylist)   # --> [6, '/', 3, '+', 9, '+', 8]

mylist = [6, '/', 3, '+', 9, '+', 8, '+', 1, '/', 2]
# delete part of a list, keep the last 3 elements
del mylist[:-3]
print(mylist)   # --> [1, '/', 2]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Not sure why you want to do this, but one way is to build a ringbuffer ...

import collections

def ringbuffer_append(item, dq=collections.deque(maxlen=3)):
    '''
    mimics a ringbuffer of length 3
    you can change maxlen to your needs    
    '''
    dq.append(item)
    return list(dq)

# testing
mylist = ringbuffer_append('red')
print(mylist)

mylist = ringbuffer_append('green')
print(mylist)

mylist = ringbuffer_append('blue')
print(mylist)

# first item will pop to make room for new item 3
mylist = ringbuffer_append('orange')
print(mylist)

mylist = ringbuffer_append('yellow')
print(mylist)

''' result ...
['red']
['red', 'green']
['red', 'green', 'blue']
['green', 'blue', 'orange']
['blue', 'orange', 'yellow']
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using Windows .NET or Linux Mono with IronPython ...

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference('System.Drawing')

from System.Windows.Forms import Application, Form
from System.Drawing import Color

class IForm(Form):

    def __init__(self):
        # set form title, bg_color, size, position
        self.Text = 'Hello World'
        self.BackColor = Color.Green
        self.Width = 250
        self.Height = 200
        self.CenterToScreen()

Application.Run(IForm())
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can use Python module json to save (dump) and read (load) certain Python objects ...

''' json_dictionary1.py
Python module json can be used to dump and load dictionay objects
json --> JavaScript Object Notation
You can also dump and load list objects
'''

import json

pfolio_dict = {
'GOOG': ('Google', 200, 549.85), 'YHOO': ('Yahoo', 900, 16.81),
'AAPL': ('Apple', 400, 188.0), "MSFT": ('Microsoft', 300, 26.5)
}

fname = "portfolio.jsn"
# dump the dictionary object to file
# you can look at the .jsn file with an editor
with open(fname, "w") as fout:
    json.dump(pfolio_dict, fout)

# read the dictionary object back in from file
with open(fname) as fin:
    pfolio_dict2 = json.load(fin)

# testing ...
print(type(pfolio_dict2))
print('-'*20)
print(pfolio_dict2)

''' result (Python34) ...
<class 'dict'>
--------------------
{'AAPL': ['Apple', 400, 188.0], 'MSFT': ['Microsoft', 300, 26.5], ... }
'''

# pretty print with json.dumps()
s = json.dumps(pfolio_dict2, sort_keys=True, indent=2)
print(type(s))
print('-'*20)
print(s)

''' result (Python34) ...
<class 'str'>
--------------------
{
  "AAPL": [
    "Apple",
    400,
    188.0
  ],
  "GOOG": [
    "Google",
    200,
    549.85
  ],
  "MSFT": [
    "Microsoft",
    300,
    26.5
  ],
  "YHOO": [
    "Yahoo",
    900,
    16.81
  ]
}

'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Make sure the data is presented to the OptionMenu() as a list that is unpacked with the * operator. Testprint choices and use *choices as an argument.

Ene Uran commented: Sharp +12
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am a scientist and studied biology. chemistry, computers, process automation, physics, management and engineering. I am gainfully retired now, but had one heck of a good time in my job. Almost 50 years later I am still learning and love it!

My advice is "learn as much as you can" and don't waste your time on TV and games.

Slavi commented: pretty much my moto :D +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Every person has a unique tongue print.

Reverend Jim commented: The problem is getting the ink off once you get the print. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Actually
https://www.youtube.com/watch?v=tKTZoB2Vjuk
and its sequals are pretty good.

For a whole collection of Python videos take a look at
https://www.youtube.com/playlist?list=PL61E606149255B362

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Highlight your code and press Code on the bar above to preserve your indentations.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

“Oh Beautiful for smoggy skies, insecticided grain,
For strip-mined mountain's majesty above the asphalt plain.
America, America, man sheds his waste on thee,
And hides the pines with billboard signs, from sea to oily sea.”
... George Carlin

I hope we are not quite there yet!

Reverend Jim commented: We're not only there, we're looking at it in the rear view mirror. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Python manual at
https://www.python.org/doc/
contains a tutorial you may play with. Use the IDLE IDE that comes with your Python installation and start typing the code and try it out. Python makes it easy to experiment.

John Guttag's video lectures are excellent but a little heavy on Computer Science and your brain. Sometimes I wish he would use a little humor.

Here is a simple introduction:
http://en.wikipedia.org/wiki/Python_programming_language
lots of exercises (online):
http://learnpythonthehardway.org/book/
online tutorial series:
http://www.tutorialspoint.com/python/index.htm

There is always ...
https://www.daniweb.com/software-development/python/threads/20774/starting-python

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

abs(x) where x is an argument for the function abs()

For example ...

x = -123
print(x)
print(abs(x))

From the manual ...
abs(x)
Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.

See also ...
https://www.daniweb.com/software-development/python/threads/20774/starting-python#post104853

MustafaScript commented: Thank you very much +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Growing up ...
You believe in Santa Claus
You don't believe in Santa Claus
You are Santa Claus
You look like Santa Claus

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Line
pg.mixer.init(freq, bitsize, channels, buffer)
initializes the pygame mixer (player) with the given arguments

while pg.mixer.music.get_busy():
is the pygame event loop

These lines explain themselves:
pg.mixer.music.load(music_file)
pg.mixer.music.play()

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

in line
def play_music(music_file, volume=0.8):
volume=0.8 is the default volume in case you did not supply a value

Basic Python knowledge!