hannah dong


Introduction to Python - Lesson 1

The reason why I learn Python is to prepare for Machine Learning.

Quick Start

Download Python

Download here if you haven’t yet.

Check if you have already downloaded Python

1
$ python --version

If the terminal displays as below, you have already downloaded it; Otherwise you haven’t.

1
Python 2.7.10

Run a Python File

Create a folder

1
$ mkdir python

Make a file

1
$ >hello.py

Edit hello.py

1
$ vi hello.py

Enter “i” and input the following

1
2
3
4
5
6
7
# Define a main() function that prints a little greeting
def main():
print "Hello Alice"
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()

Press esc, then input “:x” to exit
Input

1
python hello.py

The result is

1
Hello Alice

The above example shows how to make a basic python file, then we will see how to use the existing functions within Python, rewrite hello.py as following

1
2
3
4
5
6
7
8
9
10
11
12
13
import sys
def Hello(name):
name = name + '!!!'
print 'Hello', name
# Define a main() function that prints a little greeting
def main():
Hello(sys.argv[1])
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()

Press esc, then input “:x” to exit
Input

1
python hello.py Alice

The result is

1
Hello Alice!!!

The above example shows how to make inputs through command line, then we will see how to use if/else function, rewrite hello.py as following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import sys
def Hello(name):
if name == 'Alice' or name == 'Nick':
name = name + '???'
else:
name = name + '%%%'
name = name + '!!!'
print 'Hello', name
# Define a main() function that prints a little greeting
def main():
Hello(sys.argv[1])
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()

Press esc, then input “:x” to exit
Input

1
python hello.py Alice

The result is

1
Hello Alice???!!!

Run Python Command

1
$ python

The usage of ‘’ and “”

1
2
3
4
5
>>> "I "love" this exercise"
>>> 'I "love" this exercise'
>>> "isn't"
>>> "isn't"
>>>

Press cmd+d to exit

1
>>> help(sys)

Long press q to exit

This is the first day I learned Python, keep going!


Reference here