1. 程式人生 > 其它 >Python tips

Python tips

  1. input()、len()

因為 input()函式總是返回一個字串(即使使用者輸入的是數字),所以使用 int(myAge)返回字串的整型值。
這個整型值隨後在表示式 int(myAge) + 1 中與 1 相加。
相加的結果傳遞給 str()函式:str(int(myAge) + 1)。然後,返回的字串與字串'You will be '和' in a year.'連線,求值為一個更長的字串。

# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')
myName = input()               # input()函式等待使用者在鍵盤上輸入一些文字,並按下回車鍵。將使用者輸入的文字即字串賦值給變數myName
print('It is good to meet you,' + myName)
print('The length of your name is:')
print(len(myName))             # 向len()函式傳遞字串或包含字串的變數,求字元的個數,為一個整數
print('What is your age')
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
  1. if語句
print('input you name')
name=input()
print('input you name')
age=input()
if name == 'Alice':
    print('Hi,Alice.')
elif int(age) < 12:
    print('You are not Alice,Kiddo.')
elif int(age) > 200:
    print('Unlike you,Alice is not an undead,immortal vampire.')
elif int(age) > 100:
    print('You are not Alice,grannie.')
  1. random模組

import random
for i in range(5):
print(random.randint(1,10))

range()表示隨機取值:0-4,不超過5的值。
random.randint()函式呼叫求值為傳遞給它的兩個整數之間的一個隨機整數;
因為 randint()屬於 random 模組,必須在函式名稱之前先加上 random.,告訴 python 在random 模組中尋找這個函式

#使用sys.exit()提前結束程式
import sys
while True:
    print('Type exit to exit.')
    response = input()
    if response == 'exit':
        sys.exit()
    print('You typed ' + response + '.')
  1. def 定義函式

def 定義一個叫hello的函式,def 語句後的程式碼塊為函式體。
在函式呼叫時執行,不是在函式第一次定義執行hello()為函式呼叫,就是函式名後跟括號,或在括號之間有一些引數。
執行到函式的末尾,就回到呼叫函式那行,繼續向下執行程式碼。

def hello():
print('Howdy!')
print('Hoell')
print('Hello there.')

hello()
hello()


如果呼叫print()或len()函式,會傳一些值,稱為引數;
hello()函式定義,有一個為name()的變元(即變數,當函式被呼叫,引數就存放其中),儲存在變元裡的值,在函式返回後就丟失了。
如hello('Bob')之後新增 print(name),程式會報NameError,因為沒有名為 name 的變數。
在函式呼叫 hello('Bob')返回後,這個變數被銷燬了,所以 print(name)會引用一個不存在的變數 name。
這類似於程式結束時,程式中的變數會丟棄'''

def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')


r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
以上三行可以使用一行表示
print(getAnswer(random.randint(1, 9)))

在這個程式開始時,Python 首先匯入 random 模組。然後 getAnswer()函式被定義。因為函式是被定義(而不是被呼叫),所以執行會跳過其中的程式碼。
接下來,random.randint()函式被呼叫,帶兩個引數,1 和 9。它求值為 1 和 9 之間的一個隨機整數(包括 1 和 9),這個值被存在一個名為 r 的變數中。
getAnswer()函式被呼叫,以 r 作為引數。程式執行轉移到 getAnswer()函式的頂部,r 的值被儲存到名為 answerNumber 的變元中。
然後,根據 answerNumber中的值,函式返回許多可能字串中的一個。程式執行返回到程式底部的程式碼行,即原來呼叫 getAnswer()的地方。
返回的字串被賦給一個名為 fortune 變數,然後它又被傳遞給 print()呼叫,並被列印在螢幕上。
請注意,因為可以將返回值作為引數傳遞給另一個函式呼叫,所以你可以將下面 3 行程式碼
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
縮寫成一行等價的程式碼:
print(getAnswer(random.randint(1, 9)))
記住,表示式是值和操作符的組合。函式呼叫可以用在表示式中,因為它求值為它的返回值。'''

# 一般,函式呼叫求值的結果,稱為函式的“返回值”
# return,用def語句建立函式時,可以用return語句指定應該返回什麼值
import random

def getAnswer(answerNumber):
    if answerNumber == 1: 
       return 'It is certain' 
    elif answerNumber == 2:
       return 'It is decidedly so' 
    elif answerNumber == 3:
       return 'Yes' 
    elif answerNumber == 4:
       return 'Reply hazy try again' 
    elif answerNumber == 5:
       return 'Ask again later' 
    elif answerNumber == 6:
       return 'Concentrate and ask again' 
    elif answerNumber == 7: 
       return 'My reply is no' 
    elif answerNumber == 8:
       return 'Outlook not so good' 
    elif answerNumber == 9:
       return 'Very doubtful' 
  1. try except

將可能出錯的語句被放在 try 子句中。
如果錯誤發生,程式執行就轉到接下來的except子句開始處。執行那些程式碼後執行照常繼續'''

def spam(divideBY):
try:
return 42 / divideBY
except ZeroDivisionError:
print('Error: Invalid srgument.')

print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

# 如果是以下場景
def spam(divideBY):
    return 42 / divideBY
try:
    print(spam(2))
    print(spam(12))
    print(spam(0))
    print(spam(1))

except ZeroDivisionError:
    print('Error: Invalid srgument.')

'''結果是:
21.0
3.5
Error: Invalid srgument.
>>>
'''
# print(spam(1))從未被執行是因為,一旦執行跳到except子句的程式碼,就不會回到try子句。它會繼續照常向下執行。

  1. guessnumber game
# This is a guess the numner game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of number vetween 1 and 20.')

#Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
    print('Take a guess.')
    guess = int(input())

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break # this is condition is correct guess!
if guess == secretNumber:
    print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))