python學習——如何判斷輸入是數字


笨辦法學python第35節

該節主要是講分支與函數,主要遇到的問題是python中如何判斷輸入是數字。

首先原代碼如下:

from sys import exit

def gold_room():
    print "This room is full of gold. How much do you take?"

    next = raw_input("> ")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")

def bear_room():
    print "There is a bear here."
    print "The bear has a bunch of honey."
    print "The fat bear is in front of another door."
    print "How are you going to move the bear?"
    bear_moved = False

    while True:
        next = raw_input("> ")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif next == "taunt bear" and not bear_moved:
            print "The bear has moved from the door. You can go through it now."
            bear_moved = True
        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print "I got no idea what that means."

def cthulhu_room():
    print "Here you see the great evil Cthulhu."
    print "He, it, whatever stares at you and you go insane."
    print "Do you flee for your life or eat your head?"

    next = raw_input("> ")
    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")
    else:
        cthulhu_room()

def dead(why):
    print why, "Good job!"
    exit(0)

def start():
    print "You are in a dark room."
    print "There is a door to your right and left."
    print "Which one do you take?"

    next = raw_input("> ")

    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")


start()

將改代碼的流程圖畫出來思路就很清晰(略)(哈哈哈哈想起來小時候看答案,答案“略”,sad)

其中,gold_room函數的一個判斷語句“if "0" in next or "1" in next:”,這句話就只能使得輸入的數字中有1或0的才可以進行how_much的判斷,那么python中有沒有一種方法可以直接判斷輸入是否是數字,有噠,就是可以用語句“if  next.isdigit():”判斷,將前一句換成這一句之后再運行,可以得到運行結果如下(其中我把raw_input("> ")換成了raw_input("please input a number: ")):

注:

補充:isdigit()方法檢查字符串是否只包含數字(全由數字組成)。也就是說“isdigit()本身就是處理字符串的函數,他不分辨你到底是數字還是字符串”

除了判斷raw_input()輸入的是否是數字,還可以判斷是否是字符串,如下

"if next.isdigit():" 都是數字
"if next.isalnum():" 都是數字或者字母
"if next.isalpha():" 都是字母
"if next.islower():" 都是小寫
"if next.isupper():" 都是大寫
"if next.istitle():" 都是首字母大寫,像標題
"if next.isspace():" 都是空白字符、\t、\n、\r

(其他的判斷還沒有試,有用到的話回來找)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM