Total Pageviews

Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

2016/03/07

[Python] Exception Handling

Problem
Here is my Python program:
1
2
3
4
5
6
def checkNum(num):
  try:
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")

The parameter in checkNum method only accept number data type. If I provide String data type...
1
2
3
4
5
6
7
8
>>> import myUtil
>>> myUtil.checkNum("-20")
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    myUtil.checkNum("-20")
  File "C:\Users\albert\AppData\Local\Programs\Python\Python35-32\lib\site-packages\myUtil.py", line 2, in checkNum
    if(num>0):
TypeError: unorderable types: str() > int()

How To
We can use try...except to do exception handling in Python program, and given more friendly exception message:
1
2
3
4
5
6
7
8
def checkNum(num):
  try:
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")
  except TypeError as err:
    print('只接受數字型態(Only Accept Number Data Type)! ' + err.args[0])

Test:
1
2
3
4
>>> import myUtil
>>> myUtil.checkNum("-20")
只接受數字型態(Only Accept Number Data Type)! unorderable types: str() > int()
>>> 









2016/03/06

[Python] TypeError: Can't convert 'int' object to str implicitly

Problem
I have a Python program as bellows:
1
2
3
4
5
def checkNum(num):
    if(num>0):
        print("* number > 0 ( you input " + num + " ).")
    else:
        print("* num < 0 ( you input " +  num + " ).")

As I try to do test, it showed error message as following:
1
2
3
4
5
6
7
8
>>> import myUtil
>>> myUtil.checkNum(10)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    myUtil.checkNum(10)
  File "C:\Users\albert\AppData\Local\Programs\Python\Python35-32\lib\site-packages\myUtil.py", line 3, in checkNum
    print('* number > 0 ( you input ' + num +' )')
TypeError: Can't convert 'int' object to str implicitly


How To
You need to use str function to convert number to String
1
2
3
4
5
def checkNum(num):
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")

Test result:
1
2
3
4
5
6
>>> import myUtil
>>> myUtil.checkNum(89)
* number > 0 ( you input 89 ).
>>> myUtil.checkNum(-20)
* num < 0 ( you input -20 ).
>>> 


Reference
[1] http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly

2016/03/05

[Python] File I/O in Python : UnicodeDecodeError

Problem
I would like to open a text file and prints its content
1
2
3
4
5
>>> import os
>>> os.chdir ("D:\python")
>>> data = open("txt\AJokeADay1.txt")
>>> for eachLine in data :
 print(eachLine)

But it throw this exception:
1
2
3
4
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    for eachLine in data :
UnicodeDecodeError: 'cp950' codec can't decode byte 0xe2 in position 70: illegal multibyte sequence


How To
Assign encoding to utf-8 as open this file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> data = open("txt\AJokeADay1.txt", "r", encoding="utf-8")
>>> for eachLine in data :
 print(eachLine)

 
[In Office Jokes]

A guy shows up late for work. 

The boss yells, You shouldve been here at 8.30!’ 

He replies. Why? What happened at 8.30?’ 
>>> data.close()






2016/03/04

[Python] Module your Python Code

In Java, if some source code will be reused by others. We may create a utility class, if someone need this function, he/she can import this class and reuse this function. Do not need to reinvent the wheel.

Assume I have a simple Python code which named printLoop.py, the code is as bellows:
1
2
3
4
""" print movie list"""
def printMovies(movies):
 for movie in movies :
  print(movie)

Supposed that many people may need this function to print the content of array. Therefore, you need to package this Python program as a module.

Step 1. Create a folder for my module which name printLoop


Step 2. Create a setup.py in printLoop folder
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from distutils.core import setup
setup(
 name = 'printLoop',
 version = '1.0.0',
 py_modules = ['printLoop'],
 author = 'albert',
 author_email = 'xxx@gmail.com',
 url = 'http://xxx.com',
 description = 'simple example for building module',
)

Step 3. Build distribution file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
D:\python\printLoop>python setup.py sdist
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)

warning: sdist: standard file not found: should have one of README, README.txt

writing manifest file 'MANIFEST'
creating printLoop-1.0.0
making hard links in printLoop-1.0.0...
hard linking printLoop.py -> printLoop-1.0.0
hard linking setup.py -> printLoop-1.0.0
creating 'dist\printLoop-1.0.0.zip' and adding 'printLoop-1.0.0' to it
adding 'printLoop-1.0.0\PKG-INFO'
adding 'printLoop-1.0.0\printLoop.py'
adding 'printLoop-1.0.0\setup.py'
removing 'printLoop-1.0.0' (and everything under it)

Step 4. Install the distribution file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
D:\python\printLoop>python setup.py install
running install
running build
running build_py
creating build
creating build\lib
copying printLoop.py -> build\lib
running install_lib
copying build\lib\printLoop.py -> C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages
byte-compiling C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop.py to printLoop.cpython-35.pyc
running install_egg_info
Removing C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop-1.0.0-py3.5.egg-info
Writing C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop-1.0.0-py3.5.egg-info

Test.
1. Import printLoop module
2. Create a movie list
3. utilize printLoop.printMovies to print movie list
1
2
3
4
5
6
7
8
9
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import printLoop
>>> movies = ["Inside Out", "The Intern", "Our Brand is Crisis"]
>>> printLoop.printMovies(movies)
Inside Out
The Intern
Our Brand is Crisis
>>> 



2016/03/03

[Python] How to Change Working Directory in IDLE

Problem
As I open IDLE, how do I know my current working directory? And how to change to another working directory?

How To
1. you need to import os module first
2. use os.getcwd() to get current working directory
3. use os.chdir("XXX") to change working directory

1
2
3
4
5
6
7
8
9
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import os
>>> os.getcwd()
'C:\\Users\\albert\\AppData\\Local\\Programs\\Python\\Python35-32'
>>> os.chdir("D:\python")
>>> os.getcwd()
'D:\\python'
>>> 


Reference
[1] http://stackoverflow.com/questions/15821121/whats-the-working-directory-when-using-idle


2016/03/02

[Python] Set Up Python Environment

Step 1. Download Python from https://www.python.org/downloads/windows/


Step 2. Install Python














Step 3. If you are Windows users, you need to configure Python installation path and Scripts path to path (environment variables)
i.e. C:\Python35-32\ and C:\Python35-32\Scripts


If you are Mac user, you can ignore this step.

Step 4. Open command prompt, and type in python3 -V to do verification. 



Write a first and simple Python program
1
2
3
4
# encoding: utf-8

print("Hello, Python")
print("哈囉,派森")




Then you can use IDLE to help you learn Python


IDLE knows all about Python syntax
Ex1. Use terminal


Ex2. Use IDLE


IDEL also offers "code completion" when you use build-in functions, ex. print()