vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This is how I would do it ...

''' kivy_button_label101.py
create a touch sensitive button with Python module kivy
add a label to show action

info:
http://kivy.org/docs/api-kivy.uix.button.html
http://kivy.org/docs/api-kivy.uix.label.html
http://kivy.org/docs/api-kivy.uix.boxlayout.html
'''

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


class TestApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')
        # use a (r, g, b, a) tuple
        blue = (0, 0, 1.5, 2.5)
        red = (2.5, 0, 0, 1.5)

        btn =  Button(text='Touch me!', background_color=blue, font_size=120)        
        btn.bind(on_press=self.callback)
        self.label = Label(text="------------", font_size='50sp')
        layout.add_widget(btn)
        layout.add_widget(self.label)
        return layout

    def callback(self, event):
        print("button touched")  # test
        self.label.text = "button touched"


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

Who ever heard of Caesar Cipher ...

encrypted = "Ifmmp!Xpsme"
print("".join(chr(ord(x)-1) for x in encrypted))

Anybody ready to use a GUI with a fancy font?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I thought it would be fun to code all the different ways to show Hello World on the display.

Let's start simple ...
print("Hello World")

Can anybody print out "Hello World" vertically?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sooner or later you will use the pygame module anyway ...

''' pg_playmp3f.py
play MP3 music files using Python module pygame
pygame is free from: http://www.pygame.org
(does not create a GUI frame in this case)
'''

import pygame as pg

def play_music(music_file, volume=0.8):
    '''
    stream music with mixer.music module in a blocking manner
    this will stream the sound from disk while playing
    '''
    # set up the mixer
    freq = 44100     # audio CD quality
    bitsize = -16    # unsigned 16 bit
    channels = 2     # 1 is mono, 2 is stereo
    buffer = 2048    # number of samples (experiment to get best sound)
    pg.mixer.init(freq, bitsize, channels, buffer)
    # volume value 0.0 to 1.0
    pg.mixer.music.set_volume(volume)
    clock = pg.time.Clock()
    try:
        pg.mixer.music.load(music_file)
        print("Music file {} loaded!".format(music_file))
    except pg.error:
        print("File {} not found! ({})".format(music_file, pg.get_error()))
        return
    pg.mixer.music.play()
    while pg.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)


# pick a MP3 music file you have in the working folder
# otherwise give the full file path
# (try other sound file formats too)
music_file = "Hot80s.mp3"

# optional volume 0 to 1.0
volume = 0.8

play_music(music_file, volume)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The SharpDevelop IDE is a drag and drop GUI builder that writes most of the code for you either in C# or IronPython. With Mono it should work on Linux too?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I used csv data readily available from http://www.weatherdatadepot.com/
to create a multiline plot of the average monthly temperatures of a given location.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It was a good game. The halftime show was exotic. The best commercial IMHO was the one from Fiat (blue pill).

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Some interesting itertools applications ...

''' itertools_groupby101.py
exploring the Python itertools module
itertools.count(start=0, step=1)
itertools.groupby(iterable, key)

'''

import itertools as it
import string

# us an iterable string for testing
# use string.ascii_lowercase for Python3
iterable = string.lowercase
print(iterable)
print('-'*26)

block_size = 5

# key is a function computing a key value for each element in iterable
key = lambda _, w=it.count(): next(w)//block_size

for number, rows in it.groupby(iterable, key):
    print("{} {}".format(number, list(rows)))

''' result ...
abcdefghijklmnopqrstuvwxyz
--------------------------
0 ['a', 'b', 'c', 'd', 'e']
1 ['f', 'g', 'h', 'i', 'j']
2 ['k', 'l', 'm', 'n', 'o']
3 ['p', 'q', 'r', 's', 't']
4 ['u', 'v', 'w', 'x', 'y']
5 ['z']
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

About time for a blonde joke ...
A blonde cop stops a blonde motorist and asks for her driver's license.
The motorist digs around in her purse but can't find it. She says to the cop, "I must have left it at home, officer."

The cop says, "Well, do you have any kind of identification?"

The motorist searches her purse again and finds a pocket mirror. She looks at it and says to the cop, "All I have is this picture of myself."

The cop says, "Let me see." So the blonde motorist gives the mirror to the blonde cop, who looks at it, and replies, "Well, if I'd known you were a police officer, I wouldn't have pulled you over."

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A man walks into a bar and asks for 1.4 root beers. The mixologist says "I'll have to charge you extra, that's a root beer float". The man says "In that case, better make it a double."

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A group of software folks take a trip through the mountains when the car's brakes fail and they end up in a ditch. The software analyst amongst them suggests: "Let's push the car out of the ditch and see if it does it again!"

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

About 75% of exploits abused by cybercrime groups take advantage of flaws in Adobe's Flash, Acrobat and Reader programs.

Source: http://www.bbc.com/news/technology-30948123

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

C++ and Python complement each other, so you should have a good knowledge of those two languages. Once you are learning C++ then Java isn't far off. Unless you are a genius, it will take a lot of coding and exploring to get to know Python thoroughly enough to pass an employer's hiring test.

The basic syntax of Python is easier to learn then C++ or Java, but the real power comes in the use of its many modules. You need to be able to produce well tested programs.

For me Python was a good application language for scientifc projects. Where you needed to know the underlying science very well and develop a program rather quickly.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Knowing the longitude and latitude coordinates of two cities you can calculate the distance between them.

Use the code in
https://www.daniweb.com/software-development/python/code/490561/postal-code-zips-and-location-python
to find the coordinates.

ddanbe commented: Nice! +15
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using http://download.geonames.org/export/zip/ you can get postal information for most countries in the world. The raw data string can be transformed into a Python list of lists that can be searched for zip codes, locations, longitude and latitude coordinates.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

@L7Sqr
In all fairness SneeKula answered the original question. Sometimes it is fun to experiment a little to get to know the language better. Yes, I would rather use the tested tolower() and toupper() functions.

Some instructors give these kind of problems to their students to make them think.

cambalinho commented: thanks +3
L7Sqr commented: Agreed. I sometimes forget about the fun of exploration as a result of having been burnt in the past. +9
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python's double ended queue module makes Caesar's cipher easy.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One way to show a picture with PySide (public PyQT) ...

''' ps_designer_dialog_picture101.py
use the Designer program that comes with the PySide installation, 
for instance in C:\Python33\Lib\site-packages\PySide\Designer.exe

1) create a dialog widget
2) put a label on it with a pixmap picture from a file
3) save as mydialog2.ui
the .py, .ui and the picture file should be in the working directory 

the .ui file is an xml file you can edit with some care
for instance you can change the name of the picture file
'''

from PySide.QtGui import QApplication
from PySide.QtUiTools import QUiLoader
import sys


def main():
    application = QApplication([])
    loader = QUiLoader()
    dialog = loader.load('mydialog2.ui')
    dialog.show()
    sys.exit(application.exec_())


if __name__ == '__main__':
    main()

Here is the xml file mydialog2.ui created with the PySide Designer program ...

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>240</y>
     <width>341</width>
     <height>32</height>
    </rect>
   </property>
   <property name="orientation">
    <enum>Qt::Horizontal</enum>
   </property>
   <property name="standardButtons">
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
   </property>
  </widget>
  <widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>22</y>
     <width>341</width>
     <height>201</height>
    </rect>
   </property>
   <property name="text">
    <string/>
   </property>
   <property name="pixmap">
    <pixmap>myline.png</pixmap>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>Dialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel">
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>Dialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel">
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Dress up your Tkinter programs with a background image ...

''' tk_Image_label_button1.py
put a background picture and a button on a Tkinter label
'''

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

def on_button():
    root.title("Button has been pressed!")

root = tk.Tk()

# pick a .gif image file you have in the working folder
# (or give full path) Linux fname is case sensitive
fname = "LAKE.GIF"
image_tk = tk.PhotoImage(file=fname)
w = image_tk.width()
h = image_tk.height()
info = "size of {} = {}".format(fname, (w, h))
print(info)  # test
root.title(info)
root.geometry("%dx%d+310+210" % (w, h))

label = tk.Label(root, image=image_tk)
label.pack(side='top', fill='x', expand='yes')
label.pack_propagate(0)

# put the button on the label with the picture
btn = tk.Button(label, text="press me", command=on_button)
btn.pack(pady=10)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In case you need to know ...

''' np_version.py
get the version of numpy you have installed
'''

import numpy

print(numpy.__version__)

''' possible result ...
1.9.0
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The government of Zimbabwe is printing money even faster than the US government. They recently issued a 100 trillion Dollar note. Go ahead and be a trillionair, as you can actually buy a brandnew official Zimbabwe 100 trillion Dollar bill at Amazon.com for US $20, or five of them for US $80.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have pip installed, check with ...

''' modules_pip101.py
list all the installed modules
'''

import pip

for item in pip.get_installed_distributions():
    print(item)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you draw a series of close spaced shapes your eyes get fooled to see Moire patterns. Here is one example of this.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Change line 9 to ...
for t in range(0, 1200+1):

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

C++ has the Standard Template Library (STL) that makes your life so much easier when it comes to strings and vectors/arrays.

See ...
https://www.sgi.com/tech/stl/stl_introduction.html

Also take a wiff of ...
https://www.daniweb.com/software-development/cpp/code/216400/an-array-can-use-stl-functions

Introduce yourself to classical OOP gradually, C++ allows this. A language that complements C++ very well is Python.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just in time for the season, a star.
(Playing with my grandson on the Raspberry Pi computer)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I usually keep Python2 and Python3 on my Windows machine and you can do the same on a Linux computer. On Windows the trick is to tell your IDE which version to use. On Linux you can use the shebang line.

My $35 Raspberry Pi computer (Linux) came with both Python2 and Python3 installed, and from the desktop uses IDLE for Python2 and IDLE3 for Python3. Running Python code from the terminal you have to trust the shebang line. Make the first line in your code #!/usr/bin/python and it will use Python2.

Hopefully there will a time when we all use Python3.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Virginia City in Nevada. Pretty wild area, home of the Bonanza western.

GrimJack commented: do they still do that gunfight in the street? +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example ...

''' pg_mouseposition1.py
show mouse position with module pygame

to see a list of event constants use:
import pygame.constants
help(pygame.constants)
'''

import pygame as pg

# create a 640x400 window/screen
screen = pg.display.set_mode((640, 400))
screen.fill((255, 0, 0))  # red

running = True
while running:
    event = pg.event.poll()
    # quit when window corner x is clicked
    if event.type == pg.QUIT:
        running = False
    elif event.type == pg.MOUSEMOTION:
        mouse_pos = "mouse at (%d, %d)" % event.pos
        pg.display.set_caption(mouse_pos)
    elif event.type == pg.MOUSEBUTTONDOWN:
        mouse_pos = "mouse click at (%d, %d)" % event.pos
        pg.display.set_caption(mouse_pos)

    # update display
    pg.display.flip()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Why did the chicken cross the road?

BARACK OBAMA:
The chicken crossed the road because it was time for a CHANGE! The chicken wanted CHANGE!

GEORGE W. BUSH:
We don't really care why the chicken crossed the road. We just want to know if the chicken is on our side of the road, or not. The chicken is either against us, or for us. There is no middle ground here.

DR SEUSS:
Did the chicken cross the road? Did he cross it with a toad? Yes, the chicken crossed the road, but why it crossed I've not been told.

ERNEST HEMINGWAY:
To die in the rain. Alone.

ALBERT EINSTEIN:
Did the chicken really cross the road, or did the road move beneath the chicken?

AL GORE:
I invented the chicken!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Roadrunner, fast and smart.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

For word or character counting use Counter from the Python module collections ...

''' char_frequency_tuple3.py
create a list of (char, frequency) tuples
using he most_common() method of collections.Counter
'''

import collections

# sample text, could come from a file
text = """\
add two even numbers together and you get an even number
add two odd numbers together and you get an even number
the only way to get an odd number is to add an even number to an odd one
"""

# remove newline characters
text = text.replace('\n', '')

# this creates a list of (char, frequency) tuples
# by default the list is sorted by frequency
mylist = collections.Counter(text).most_common()

print("Sorted by frequency:")
for character, freq in mylist:
    print("%r  %d" % (character, freq))

''' result...
Sorted by frequency:
' '  37
'e'  23
'n'  19
'd'  14
'o'  14
't'  13
'a'  11
'r'  8
'u'  8
'b'  6
'm'  6
'g'  5
'v'  4
'y'  4
'h'  3
's'  3
'w'  3
'i'  1
'l'  1
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
    import os.path

    directory = r"C:\Python27\mystuff"  # Windows
    filename = "New.txt"
    path = os.path.join(directory, filename)

    # test
    print(path)  # result --> C:\Python27\mystuff\New.txt

    # then ...
    with open(path, 'r') as fin:
        text = fin.read()

Note: Windows allows you to replace \ with / in the directory string

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In general ...

mydict = {
'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
'W':'J', 'X':'K', 'Y':'L', 'Z':'M'
}

text = "Hello!"

cipher_text = ""
for c in text:
    # look up dictionary value for key = c and build up cipher_text
    # if c is not a dictionary key use the original c
    if c in mydict.keys():
        cipher_text += mydict[c]
    else:
        cipher_text += c

print(cipher_text)  # result --> Uryyb!

To decode use the reversed dictionary.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An example how to use Tkinter's OptionMenu() as a combobox to allow one year to be selected from an option list of let's say the past 15 years.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You need to use at least Python version 3.4 ...

''' enum_test101.py
module enum is new in Python34
see: http://legacy.python.org/dev/peps/pep-0435/
'''

from enum import Enum

class Colour(Enum):
    WHITE = (255,255,255)
    BLACK = (0,0,0)
    RED = (215,45,45)
    BLUE = (45,87,214)
    YELLOW = (230,223,48)
    GREEN = (45,194,64)

print(Colour.BLACK.value)  # (0, 0, 0)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Even simpler ...

def length(seq):
    n = 0
    for c in seq:
        n += 1
    return n

s = "vegaseat"
print(length(s))  # result --> 8
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

From the grandkids. What do you call a dog with no legs? Nothing, he won't come anyway.

Slavi commented: wow thats a bit mean xD +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"When we fail to invest in children, we have to pay the cost."
... Bob Keeshan

Reverend Jim commented: The human equivalent of technical debt? +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Select 6 unique lotto numbers from 1 - 49

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another way to look at this ...

''' mpm_stuff.py 
comparing Python module mpmath result to C 64bit double results
'''

from mpmath import *

# convert to mpmath float
x = mpf(65536)

# set precision
mp.dps = 16

print("Factorial of 65536:")
print(fac(x))
print("5.162948523097533e+287193  (C)")
print("65536 to the Power of 65536:")
print(x**x)
print("6.741140125499081e+315652  (C)")


''' result ...
Factorial of 65536:
5.162948523097509e+287193
5.162948523097533e+287193  (C)
65536 to the Power of 65536:
6.741140125499073e+315652
6.741140125499081e+315652  (C)
'''

I would say you are close!

Gribouillis commented: yes! +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use Python to show that factorial(0.5) = sqrt(pi)/2

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Apple, with a $668 billion market cap, is three times bigger than the dollar value of illegal drug sales in the U.S. each year.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sometimes you want to know the version of the Tkinter GUI toolkit in your Python installation ...

''' tk_version.py
get the version number of Tkinter and its underlying TCL
'''

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

print("Tkinter version = {}".format(tk.TkVersion))
print("Its TCL version = {}".format(tk.TclVersion))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"If we knew what it was what we were doing, it wouldn't be called research, wouldn't it?"
... Albert Einstein (3/14/1879 - 4/18/1955)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you are too open minded, your brain will fall out.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Why is it that nobody understands me and everybody likes me?"
... Albert Einstein

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hearing problems:
Three seniors are out for a stroll.
One of them remarks, “It’s windy.”
Another replies, “No way. It’s Thursday.”
The last one says, “Me too. Let’s have a soda.”

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Oh yes, it is necessary for the NSA to know how much fibre you are getting in your diet. With the cost of the affordable care act going up, the government needs to know that you are living healthy.

Also, eating a Middle Eastern diet would make you a potential suspect.

Slavi commented: =D +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I think I will write a password manager in Python, seems like a good idea. Copy and paste avoids the keyboard use that can be malware monitored. There is also a way to enter a password without the use of the keyboard using GUI dropdown comboboxes. Keep talking friends!

My bank has an interesting approach. You give them an 8 to 15 letter word of your choice as a keyword. When you log in they pick 3 letters out of your keyword at random and ask you at what index each of these letters are. You answer via 3 spinwheels with index numbers from 1 to 15. No keyboard entry is used.