Saturday

Python 3 Tutorials and Notes

2to3.py
2to3 Python program that reads Python 2 source code and applies a series of fixers to transform it into valid Python 3 code.

example1.py file content of Python 2 code at "C:\Python3\" folder:
def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

C:\Python3> python example1.py
  File "example1.py", line 2
    print "Hello, {0}!".format(name)
                      ^
SyntaxError: invalid syntax

C:\Python3> python "C:\Python3\Tools\Scripts\2to3.py" -w example1.py

C:\Python3> python example1.py
What's your name?
Linux Mint Mate
Hello, Linux Mint Mate!
A backup of the original Python version 2 file is made and the new file name is called "example1.py.bak".

2to3.py writes the needed modification right back to the source file.
Writing the changes back is enabled with the -w flag.
example1.py file content of Python 3 code:
def greet(name):
    print("Hello, {0}!".format(name)) #changed
print("What's your name?") #changed
name = input() #changed
greet(name)

Note that, this is not a fool-proof conversion though, and you'll likely need to do some bug-fixing here and there, but it may well be quicker.

Program IDLE Python 3 GUI 64 bit: Shell and File Editor
Start Menu > Python 3 > IDLE (Python 3 GUI - 64 bit)

Python 3 Shell window:
>>> import os
>>> os.getcwd()
'C:\\Python3'
>>>

Python 3 File Editor:
Shell Menu > File > New File Ctrl+N
On the file editor window > press Ctrl+S
Save the file name as time_sleep_eg1.py
Click the Save button

time_sleep_eg1.py file content:
###
import time

repeat = "y"
sentence = []

def sentenceinput():
    global sentence, repeat
    sentence_length = input("Sentence length: ")
    sentence_length = int(sentence_length)
    iteration = 0
    while iteration < sentence_length:
        print("Sentence word ", iteration+1, "? ", sep="", end="")
        sentence.append(input())
        iteration += 1
    print(*sentence)
    repeat = input("Repeat? (y/n): ")

print("Let us create one sentence only.")
while True:
    time.sleep(1)
    if repeat == "y":
        sentenceinput()
    else:
        print("Goodbye!")
        break

###

On the file editor window, press F5 to run the module file

Shell output:
###
>>> ================================ RESTART ================================
>>>
Let us create one sentence only.
Sentence length: 3
Sentence word 1? word1
Sentence word 2? word2
Sentence word 3? word3
word1 word2 word3
Repeat? (y/n): y
Sentence length: 2
Sentence word 1? word4
Sentence word 2? word5
word1 word2 word3 word4 word5
Repeat? (y/n): n
Goodbye!
>>>
###

Edit your .py script and press F5 as needed to re-run the script.

Write your Own Function
Code:
def frange(start, stop, step):
    i = start
    # use floating point inequality check formula
    # avoid "while i < stop:"
    while (abs(stop-i) > 1e-6):
        #print("{0:.1f}".format(i))
        yield i
        i += step

#frange(0.0, 0.9, 0.1)

for i in frange(0.0, 0.9, 0.1):
    #print("{0:.1f}".format(i), end=" ")
    print(round(i,1), end=' ')
print()  #print new line
Output:
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8

Float point inequality test formula:
abs(b - a) > epsilon-error-tolerance

Control structure: while loop
Code:
*listofthings, loops = range(6)
print(listofthings)
print(loops)
loop = 0
while loop < loops:
    listofthings[loop] = "thing"+str(loop)
    loop += 1
print(listofthings)
Output:
[0, 1, 2, 3, 4]                                                                                     
5                                                                                                   
['thing0', 'thing1', 'thing2', 'thing3', 'thing4'] # listofthings is still a list data structure but the list values modified using array syntax

Function range()
In Python 2 range() produced a list.

In Python 3, the range() function got its own type. In basic terms, if you want to use range() in a for loop, then you're good to go. However you can't use it purely as a list object. For example, you cannot slice a range type.

sh-4.2# python                                                                                      
Python 2.7.5                                       
>>> range(5)                                                                                        
[0, 1, 2, 3, 4]                                                                                     
>>> type(range(5))                                                                                  
<type 'list'>                                                                                       
>>> exit                                                                                            
Use exit() or Ctrl-D (i.e. EOF) to exit                                                             
>>> exit()
sh-4.2#                                                                                        

sh-4.2# python3                                                                                     
Python 3.3.2                            
>>> range(5)                                                                                        
range(0, 5)                                                                                         
>>> type(range(5))                                                                                  
<class 'range'>                                                                                     
>>> exit()                                                                                          
sh-4.2#

Note that in Python 3, you can still produce a list by passing the generator returned to the list() function as follows:
list1 = list(range(5))
print(list1)
# output is [0, 1, 2, 3, 4] 

Human Input syntax
input([prompt])

Python 2 statement uses raw_input to get your input data.

Code:
name = input("What's your OS name? ")
print("My OS name is", name)
Output:
What's your OS name? Linux Mint Mate                                                               
My OS name is Linux Mint Mate  

Code:
a = input("Enter first number: ")
b = input("Enter second number: ")
a, *numbers, b = range(int(a),int(b)+1,1)
print("The first number is ", a, ",",
"\nthe second number is ", b, " and",
"\nthe numbers between them are ", numbers, ".", sep="")
Output:
Enter first number: 5                                                                               
Enter second number: 10                                                                             
The first number is 5,                                                                              
the second number is 10 and                                                                         
the numbers between them are [6, 7, 8, 9].

Data Structure Dictionary
Code:
dict1 = { "1":"word1", "2":"word2", "3":"word3" }
for key in dict1:
    print(key, ":", dict1[key])
Output:
1 : word1                                                                                           
2 : word2                                                                                           
3 : word3 

Data Structure List
list1=["word1", "word2", "word3", "."]
print(list1)
print(len(list1))
print(*list1)
del list1[:]
print(list1)
#Output:
# ['word1', 'word2', 'word3', '.']
# 4                                                                  
# word1 word2 word3 .                                                                                 
# []

The asterisk allows for each item to be called individually rather than the list.

print syntax
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

sep --- parts separator, by default it is a space, you can change it to any compatible character that Python allows - this can be used to make the line shorter or include mathematical operator such as >.
print("Hello, World!")

print("1","2","3", sep="<")
# output is 1<2<3

num = 4
print("The number num is ", num, " or 2*2=", 2*2, sep="")
# output is:
# python3 main.py                                                                             
# The number num is 4 or 2*2=4 

end --- end of the line, to leave a space rather than starting a new line, you can use print(x, end=' '). By default, it creates a line break.

print("line1","line1;",end=" ")
print("line1 also")
# output is line1 line1; line1 also 

file=sys.stdout --- you construct the string as you would normally to print out anything and then append the file option

From Python 2 code:
print >>sys.stderr, "an error"
print "no error"

To Python 3 code:
import sys
print("an error", file=sys.stderr)
print("fatal error", file=sys.stderr)
print("no error")

flush --- if True will force the print stream to flush after execution

Python Comment Symbol
Python comment symbol is #
# single line comment

Python Abbreviations
PEP --- Python Enhancement Proposal

PSF --- The Python Software Foundation is an organization devoted to advancing open source technology related to the Python programming language

PyPI --- Python Package Index

Python 3 Information
Python 3 was to make changes to the language primarily to remove the warts that had grown in the preceding versions.

Python 3 was not to be a complete redesign(revolution), but instead an evolution of the language.

Maintaining "full" backward compatibility, unnecessary syntax, unnecessary semantic acceptable with Python 2 were explicitly off-the-table.

Python 2 code can be translated fairly easily to Python 3, sometimes entirely mechanically by such tools as 2to3. There is also non-trivial subset of the language that will run without modification on both versions 2 and 3.

The end of life for Python 2.7 has been announced.
Python 2.7 itself is the last version of the Python 2.x line with firm plans to not release a Python 2.8.

Python 2.7 will stop receiving bug fixes and other updates in 2020.

Get your code ported over to Python 3.

Python 4 that is not going to happen any time soon so you should be fine to safely port to version 3 without worrying about a massive jump in the future.

Internet Resources
Download Python 3
https://www.python.org/downloads/
Online Python 2 Interpreter
http://repl.it/languages/Python

Online Python 3 Interpreter
http://www.tutorialspoint.com/execute_python3_online.php

Stack Overflow, this website operates on a reward system for correct answers, so people are always willing to pitch in and help out others
http://stackoverflow.com/

Linux Questions
http://www.linuxquestions.org/

What is new in Python 3.0
https://docs.python.org/3/whatsnew/3.0.html

If a hater attacked your age and not the goodness of you

Whether young or old, I've always been known what endures. I've known the very idea of people that were all created equal and deserv...