vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Expanding from chriswelborn's code ...

''' crypt_table101.py
encrypt and decrypt using tables
'''

import string

''' make the from and to string
s_from = string.ascii_uppercase + string.ascii_lowercase
import random
q = list(s_from)
random.shuffle(q)
s_to = "".join(q)
print(s_from)
print(s_to)
'''

# strings have to be same length
# and contain all the characters
s_from = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
s_to   = "GhtUJdEcnbRFLiaguOQIPTYDpwNeqWrHZjfVsBXklxyoKAvzCSmM"

trans_table_encrypt = string.maketrans(s_from, s_to)
trans_table_decrypt = string.maketrans(s_to, s_from)

text = "Meet me at four thirty PM at the dog park elm tree"

encrypted = text.translate(trans_table_encrypt)
print(encrypted)

decrypted = encrypted.translate(trans_table_decrypt)
print(decrypted)

''' my result ...
LrrA Xr NA Hlvo AjfoAm gL NA Ajr WlZ xNos rBX Aorr
Meet me at four thirty PM at the dog park elm tree
'''

More of a game!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hint ...

digits = '123456'

size = len(digits)
# list of even indexed digits, positions 0,2,4, ...
evens = [int(digits[n]) for n in range(0, size, 2)]
# list of odd indexed digits
odds = [int(digits[n]) for n in range(1, size, 2)]

print(evens)  # [1, 3, 5]
print(odds)   # [2, 4, 6]

Assume that your indexing is zero based.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A closer look at some of Python's functions ...

''' zip_unzip_lists101.py
exploring Python's zip() function
dns
'''

numbers = [1, 2, 3, 4, 5]
letters = ['a', 'b', 'c', 'd', 'e']

# zip the two lists
numlet = zip(numbers, letters)

print(numlet)

''' result ...
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
'''

# this will actually unzip the zipped numlet
print(zip(*numlet))

''' result ...
[(1, 2, 3, 4, 5), ('a', 'b', 'c', 'd', 'e')]
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

May I suggest that you group things together in functions to get a better view and clarity...

data_input
processing the data (calculation)
data_output

Give your functions and arguments/variables meaningful names to help readability.

See also ...
https://www.daniweb.com/software-development/python/code/448171/a-simple-mortgage-calculator

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A location in the troubled downtown area would be less safe for the police.

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

"If you argue correctly, you're never wrong.”
... Christopher Buckley

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a little number trick ...

''' decimal_number_sequence101.py
after the decimal point there is a sequence of numbers from 000 to 022
you can go higher by increasing the precision
'''

import decimal

# set the precision
decimal.getcontext().prec = 64

# for convenience ...
dd = decimal.Decimal

x = dd(1)/dd(998001)
print(x)

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

"blameitonputin"

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The IDLE IDE that comes with your Python installation is a surprisingly good program and is Python specific. To my knowledge there have only been limited attempts to improve it in the last ten years.

One improvement is VIDLE that ships with Visual Python and the other is IDLEX that adds some well thought out extensions to IDLE.

To use IDLEX download
idlex-1.12.zip
from
http://idlex.sourceforge.net/download.html
and extract it into
C:\Python34\Lib
then run this little batch file ...

rem idlex34.bat
rem run IDLEX IDLE-extension with Python34
C:\Python34\pythonw.exe -u  C:\Python34\Lib\idlex-1.12\idlex.py
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
''' dict_dynamic101.py
create a dictionary dynamically
tested with Python27 and Python34
'''

# ----------------------------------------------
# add these few lines near the start of you code
import sys
# make string input work with Python2 or Python3
if sys.version_info[0] < 3:
    input = raw_input
# ----------------------------------------------


mydict = {}

while True:
    key = input("Enter the key (quit to exit): ")
    if key == 'quit':
        break
    val = input("Enter the value of the key  : ")
    mydict[key] = val

print(mydict)

''' possible result ...
Enter the key (quit to exit): Jim
Enter the value of the key  : 25
Enter the key (quit to exit): Bob
Enter the value of the key  : 19
Enter the key (quit to exit): Lisa
Enter the value of the key  : 32
Enter the key (quit to exit): quit
{'Jim': '25', 'Bob': '19', 'Lisa': '32'}
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Maybe this will help ...

s = "test01-15.dat"

q = s.split('.')
print(q)
print(q[0])

numeric = "".join(n for n in s.split('.')[0] if n in '0123456789-')
print(numeric)
print(numeric.split('-'))

''' result ...
['test01-15', 'dat']
test01-15
01-15
['01', '15']
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A Tkinter image button that toggles between an up and down button image.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I have sported a mustache on and off. Usually a bad cold comes up making a mess of it, so the thing is gone for a while.

diafol commented: that's rank :D +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sheep + People = Sheeple
Sheeple, most of us, are easily programmed particularly by the news media.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A blueberry scone and hot chocolate.

I eat a lot of blueberries ever since I read that they help improve your memory. However, I can't remember where I read this.

<M/> commented: lol +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A mild hint to help you along ...

// FuncByRef2.c
// pass function arguments by reference using pointers

#include <stdio.h>

void swap(int *x, int *y)
{
  int temp = *x;
  *x = *y;
  *y = temp;
}

int main()
{
  int x = 6, y = 10;

  printf("Before swap(), x = %d and y = %d\n\n", x, y);
  swap(&x, &y);
  printf("After swap(), x = %d and y = %d\n\n", x, y);

  getchar();  // console wait
  return 0;
}
rubberman commented: LOL - you are evit vegaseat! :-) +12
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another way is to create a folder like MyModules in a path
that Python has on its PYTHONPATH eg. C:\Python27\MyModules
Now save your module eg. module1.py in there.

You also have to create an __init__.py file (can be empty) in that folder,
so that Python assumes that it's dealing with a package name.

In your programs use for instance ...
import MyModules.module1 as module1

Remember that module names are case sensitive.

Sorry, I lost my Linux machine several years ago.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python is a high level language, really not written to do low level access needed for OS use like C.

There have been past attempts ...
https://github.com/tornewuff/pycorn

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Thanks SOS!
After running the code about a dozen times, I also found that Frank does not always count first in the sequence. The count however is still simultaneous.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Run two calls to a function simultaneously with this threading @background decorator.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The right game can be very refreshing to your mind.
BTW, I don't think getting old is in your control. It simply sneaks up on you!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Create a website about your home town or neighborhood.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Worrying does not take away tomorrow's troubles; it takes away today's peace."
... Armando Worcester

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can also use
print(type(ans))

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This worked for me ...

''' Py2ExeConSetup.py

Py2Exe (version 6.6 and higher) setup file for a console program.
Creates a single .exe file.

Simply add this file into the same folder with your source file (s).
Change your main source filename at the bottom to whatever you called
your main code file.  Now run Py2ExeConSetup.py ...

Two subfolders will be created called build and dist.
The build folder is for info only and can be deleted.
Distribute whatever is in the dist folder.

'''

from distutils.core import setup
import py2exe
import sys
# these .py modules will be converted to .pyo and included in the .exe
import file1
import file2
import file3

sys.argv.append("py2exe")
sys.argv.append("-q")

setup(
  options = {"py2exe": {"compressed": 1,
                        "optimize": 2,
                        "ascii": 1,
                        "bundle_files": 1}},
  zipfile = None,
  console = [{"script": 'main.py'}]
)

For testing I changed main.py ...

# main.py

import sys
import file1
import file2
import file3

def main(a,b):
    c=file1.somme(a,b)
    d=file2.mul(a,b)
    file3.div(a,b)
    print c,d

    # console wait
    raw_input("press enter to go on ...")

if __name__ == '__main__':
    #a,b=sys.argv[1:]
    a,b=3,7  # test
    a=int(a)
    b=int(b)

    main(a,b)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One idea, the result of glob.glob(path) is a list, so you could add the two lists
list_py_txt = glob.glob("c:/temp/*.py") + glob.glob("c:/temp/*.txt")

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have a Windows machine, it might be worth to investigate
Portable Python that allows you to run Python from the hard drive, or any USB flash card that can be used on a Windows computer that does not have Python installed. It comes with just about all the extra (third party) modules you need.

For instance
http://portablepython.com/wiki/PortablePython2.7.6.1/
now gives you a choice of some nice IDEs like
PyScripter v2.5.3
or
PyCharm Community Edition 3.1.2

The Python3 version is also available.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I have read that Microsoft has withdrawn support for IronPython. I guess they have grown worried about the popularity of Python (not one of the languages under their control).

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use the PySide (PyQT) GUI toolkit to play animated gif files.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Maybe this will help ...

# pick images you have in the working directory
# or give full path
image1 = tk.PhotoImage(file='Farm.gif')

# create a label to display the image
label = tk.Label(root, image=image1, relief='raised', bd=10)
label.grid(row=1, column=1)

# save label image from garbage collection!
label.image = image1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Class in a nutshell ...
a class combines a number of methods/functions that belong together. A class can be passed to another class to inherit it's behavior.

A class definition is just code running in a namespace.

rubberman commented: Other than changing "class definition" to "class implementation" on th last line, works for me! :-) +12
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The print function is full of surprises (at least for me) ...

''' list_print3.py
printing out a list
tested with Python27 and Python34
'''

# optional, allows Python27 to use Python3 print() options
# needs to be at beginning of your program code
from __future__ import print_function

mylist = ['Fred', 'Lisa', 'Anton']

print(*mylist, sep='\n')
print('-'*5)
print(*mylist, sep=', ')

''' result ...
Fred
Lisa
Anton
-----
Fred, Lisa, Anton
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python 3.4.0 has just been released and has a nice new module called statistics. Here is a test ...

''' statistics_test101.py
testing Python 3.4.0 and its module statistics
'''

import statistics as st  # needs Python 3.4 and higher

mylist = [1, 2, 3, 5, 7, 4, 2, 8]

print(mylist)
print('-'*30)
print("mean               = {:2.5f}".format(st.mean(mylist)))
print("variance           = {:2.5f}".format(st.variance(mylist)))
print("standard deviation = {:2.5f}".format(st.stdev(mylist)))

''' result ...
[1, 2, 3, 5, 7, 4, 2, 8]
------------------------------
mean               = 4.00000
variance           = 6.28571
standard deviation = 2.50713
'''
Gribouillis commented: it looks great +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A print format hint given by our friend Gribouillis ...

''' print_format101.py
tested with Python27, Ironpython27 and Python33
'''

# print a given value in different numeric formats
# each field is 10 characters wide, precision of 2 digits
sf = "{val:^10.2e}{val:^10.2f}{val:^10.2g}{val:^10.2n}{val:^10.2%}"

print(sf.format(val=0.1))

''' result ...
 1.00e-01    0.10      0.1       0.1      10.00%
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Drawing shapes with Tkinter ...

''' tk_canvas_shapes101.py
use the Tkinter GUI toolkit that comes with Python
to draw some shapes

for more shapes check canvas methods at ...
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/canvas.html
http://effbot.org/tkinterbook/canvas.htm
'''

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

# create the main window
root = tk.Tk()
root.title("Drawing shapes on a Tkinter canvas")

# create the drawing canvas with white background
canvas = tk.Canvas(root, width=550, height=450, bg='white')
canvas.pack()

# upper left and lower right corner coordinates of rectangle
rect = (50, 110, 250, 310)
# draw the outline of the rectangle
canvas.create_rectangle(rect)

# now draw the oval to fit inside the above rectangle
# an oval is drawn within a rectangle
# a square will give a circle
canvas.create_oval(rect, fill='yellow')

# draw a triangle using polygon
# (endpoint of polygon is same as starting point)
x1 = 300
y1 = 110
x2 = 300
y2 = 310
x3 = 500
y3 = 310
canvas.create_polygon(x1, y1, x2, y2, x3, y3, fill="blue")

# draw a rectangle to fit around the triangle
canvas.create_rectangle(x1, y1, x3, y3)

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

Six engineers, 3 working for Apple, 3 working for Microsoft, were all traveling on a train to a conference.
The Apple engineers bought three tickets and sat down on their seats, and got comfy, the Microsoft engineers
however, bought one ticket, so the Apple engineers asked them "How on earth are all three of you going to ride
on this train with one ticket?" The Microsoft engineers replied, "Wait and see ..."

When it came to the time for the conductor to check the tickets, the Microsoft engineers all darted to the bathroom.
The conductor knocked on the door, "Tickets please" and they passed the one ticket under the door, and the conductor
looked at it and went on.

The Apple engineers were impressed by this, and decided to do the same on the journey back. So the apple engineers
bought one ticket, but this time the Microsoft engineers didn't buy one at all. The apple engineers enquired as to how,
and the Microsoft engineers said "Wait and see ..."

As they could hear the conductor come down the aisle, both groups darted off to their respective toilet, a short while later
one of the Microsoft engineers left the cubicle, ran to where the apple engineers were, knocked on the door and said
"Tickets please!" He of course kept the ticket and used it for the Microsoft group.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You could do something like this ...

import random

name = ("stephen", "bob", "robert", "bill")
word = random.choice(name)
correct = word
jumble = ""

while word:
    position = random.randrange(len(word))
    jumble += word[position]
    word = word[:position] + word[(position +1):]

print("\nThe jumble word is: ",jumble)
guess = input("\nTake a guess: ")

count = 0
while guess != correct and guess !="":
    print("\nYour guess is wrong: ")
    count += 1
    # add hints as the wrong guess count advances ...
    if count == 1:
        print("\nThe first letter of the correct word is {}".format(correct[0]))
    elif count == 2:
        print("\nThe second letter of the correct word is {}".format(correct[1]))
    guess = input("\nTake another guess: ")

if guess == correct:
    print("\nWell done you have guessed correctly.")
    print("\nGoodbye.")

input("\nPress the enter key to exit.")
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Mildly helpful hint for the loop ...

for c in range(0, 21):
    print("Celsius = {}".format(c))

''' result ...
Celsius = 0
Celsius = 1
Celsius = 2
Celsius = 3
Celsius = 4
Celsius = 5
Celsius = 6
Celsius = 7
Celsius = 8
Celsius = 9
Celsius = 10
Celsius = 11
Celsius = 12
Celsius = 13
Celsius = 14
Celsius = 15
Celsius = 16
Celsius = 17
Celsius = 18
Celsius = 19
Celsius = 20
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something like this ...

fname_in = "names_nocaps.txt"

# write a test data file
data = '''\
frank
heidi
karl
'''
with open(fname_in, 'w') as fout:
    for name in data:
        fout.write(name)

fname_out = "names_caps.txt"

# read the file back in and write the modified data back out
with open(fname_in, 'r') as fin, open(fname_out, 'w') as fout:
    for name in fin:
        name = name.capitalize()
        fout.write(name)

''' resulting file "names_caps.txt" shown with an editor ...
Frank
Heidi
Karl

'''

Note: You are not writing or reading a list object. To do so, you need to use the pickle module.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Q: "What's 10, 9, 8, 7, 6, 5, 4, 3, 2, 1?"
A: "Bo Derek getting older."

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

At a recent computer software engineering course in the US, the
participants were given an awkward question to answer:

"If you had just boarded an airliner and discovered that your team of
programmers had been responsible for the flight control software, how
many of you would disembark immediately?"

Among the ensuing forest of raised hands only one man sat motionless.
When asked what he would do, he replied that he would be quite content to
stay onboard. With his team's software, he reasoned, the plane was unlikely
to even taxi as far as the runway, let alone take off.

mattster commented: Excellent ;) +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I take my wife everywhere, but she keeps finding her way back.

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

These two strings walk into a bar and sit down.
The bartender says, "So what'll it be?"
The first string says, "I think I'll have a beer quag fulk boorg jdkCjfdLk jk3s d#f67howeU r89nvyowmc63Dz x7xvcu"
"Please excuse my friend," the second string says, "He isn't null-terminated."

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The example at the Target stores shows that data security was criminally sloppy, allowing a 17 year old teenager from Russia to get in with a piece of homecoded malware and steal all the customer data.

joseph_7 commented: can anyone help with python please +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

When it comes to chocolate, resistance is futile.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This works ...

''' urllib2_info_getheaders.py

tested with Python275
'''

import urllib2
import os

def download(url, download_dir):
    file_name = url.split('/')[-1]
    u = urllib2.urlopen(url)
    f = open(os.path.join(download_dir, file_name), 'wb')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)


url = "http://www.cs.cmu.edu/~enron/enron_mail_20110402.tgz"
download_dir = "C:/Python27/Atest27/Bull" # future download option

download(url, download_dir)

''' result ...
Downloading: enron_mail_20110402.tgz Bytes: 443469519
'''

Try to test print meta and the type.

see:
http://nbviewer.ipython.org/github/ptwobrussell/Mining-the-Social-Web-2nd-Edition/blob/master/ipynb/Chapter%206%20-%20Mining%20Mailboxes.ipynb

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A Tkinter drawing example ...

''' tk_canvas_shapes101.py
use the Tkinter GUI toolkit that comes with Python
to draw some shapes
for more shapes check canvas at ...
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html
or
http://effbot.org/tkinterbook/canvas.htm
'''

# for Python3 use: import tkinter as tk
import Tkinter as tk

# create the main window
root = tk.Tk()
root.title("Drawing shapes on a Tkinter canvas")

# create the drawing canvas
canvas = tk.Canvas(root, width=600, height=500, bg='white')
canvas.pack()

rect = (50, 110, 250, 310)
# draw the outline of the rectangle
canvas.create_rectangle(rect)

# now draw the oval to fit inside the above rectangle
# an oval is drawn within a rectangle
# a square will give a circle
canvas.create_oval(rect, fill='yellow')

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

You can apply an endless while loop (with an exit condition) like this ...

import random

# optional, make string input work with Python2 or Python3
try: input = raw_input
except: pass

info = '''
Which sided dice would you like to roll? You can choose a
4-sided dice, a 6-sided dice or a 12-sided dice.
(Type 0 to exit the loop)
'''
print(info)

while True:
    dice = random.randrange(1,5)
    dice2 = random.randrange(1,7)
    dice3 = random.randrange(1,13)
    sides = int(input("Input number 4, 6 or 12 > "))
    if sides == 0:
        break  # exit the endless while loop
    elif sides == 4 :
        print("The 4-sided dice has rolled to", dice)
    elif sides == 6 :
        print("The 6-sided dice has rolled to", dice2)
    elif sides == 12:
        print("The 12-sided dice has rolled to", dice3)
    else:
        print("Please input a number 4, 6 or 12")

Study the example code closely so you learn.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Shows you how to play sound files with the pySFML module and Python.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

PySide's QWebView can load a given url and display the web page associated with it with just a few lines of code.