basic python syntax

len

輸出文字長度

len("aaa")
1

output: 3

len(str(1234))
1

output: 4

if else

if 2 > 5:
    print('2 > 5')
else:
    print('2 <= 5')
1
2
3
4

output: 2<=5

for loop

def hi(name):
    print('Hi ' + name + '!')

names = ['A', 'B', 'C', 'D', 'E']

for name in names:
    hi(name)
    print('Next girl')
1
2
3
4
5
6
7
8

output:

> python test.py
Hi Michelle!
Next girl
Hi Ola!
Next girl
Hi Mosky!
Next girl
Hi Phoebe!
Next girl
Hi you!
Next girl
1
2
3
4
5
6
7
8
9
10
11

function

def hi():
    print('Hi there!')
    print('How are you?')

hi()
1
2
3
4
5

output:
Hi there!
How are you?

def hi(name):
    print('Hi ' + name + '!')

hi("tom")
1
2
3
4

output:
Hi Tom!

Call the Funciton using python file

save the file as xxx.py,

$ python xxx.py
1

class

 class Cat:
    def __init__(self, name):
        self.name = name

    def meow(self):
        print(self.name + ' Meow!')

pusheen = Cat('Pusheen')
pusheen.meow()
1
2
3
4
5
6
7
8
9

output

$ python my_program.py
Pusheen Meow!
1
2

The init are call magic functions, they serve special purpose in python magic method list

class Cat:
    def __init__(self, name):
        self.name = name

    def meow(self):
        print(self.name + ' Meow!')

    def __str__(self):
        return 'Cat: ' + self.name

pusheen = Cat('Pusheen')
pusheen.meow()
print(pusheen)
1
2
3
4
5
6
7
8
9
10
11
12
13
> python my_program.py
Pusheen Meow!
Cat: Pusheen
1
2
3

import other files

import module

import Module
1

import a function form module only

form Module import function
1

import and change module name

import Module as new_name
1
Last Updated: 1/14/2019, 12:15:15 AM