python 中的input


  渣渣之路。

一、 在python編程初學者指南中的第六章、使用參數和返回值的例子中:

# -*- coding: utf-8 -*-


def display(message):
print message


def give_me_five():
five = 5
return five


def ask_yes_no(question):
"""
Ask a yes or no questions.
"""
response = None
while response not in ('y', 'n'):
response = input(question).lower()
return response

display("here is a message for you\n")
number = give_me_five()
print "Here's what I got from give_me_five():", number
answer = ask_yes_no("\nPlease enter 'y' or 'n': ")
print "Thank you for entering:", answer

發現自己在pycharm下輸入的:y會報錯

Please enter 'y' or 'n': y
Traceback (most recent call last):
File "E:/Project/actneed411/furion/static/js/template/testa.py", line 25, in <module>
answer = ask_yes_no("\nPlease enter 'y' or 'n': ")
File "E:/Project/actneed411/furion/static/js/template/testa.py", line 19, in ask_yes_no
response = input(question).lower()
File "<string>", line 1, in <module>
NameError: name 'y' is not defined

但是,輸入:'y'或者"y"卻是對的:  

here is a message for you

Here's what I got from give_me_five(): 5

Please enter 'y' or 'n': 'y' "y"
Thank you for entering: y 

 

二、探究python中的input【1】

   由【1】中的文檔中,python2.7中輸入函數有兩種:

      1、raw_input():返回的是字符串--string類型,即輸入:1+2,返回顯示的是:"1+2"

      2、input():返回的是數值類型,int,float等,即輸入:1+2,返回顯示的是:3

  而在python3中輸入只有一種:

    input():返回的是字符串--string類型,沒有數值類型了相當於原來的raw_input()

    【2】以前有分raw_input和input, raw_input讀什么東西都是string, input會解析數據,

    版本3合並了raw_input和input, 只能讀到string了, 原先的可解析版本不安全,

    如果要讀到數值,使用類型轉換:

      a = int(input("a="))

  恰好數中使用的是python是python3,這樣就能解釋通上邊的問題了。

 

 

 

------------420 三--

   參考鏈接:【1】、python輸入函數input 2-----

        【2】、python3中的input raw_input()變成了input()

 

 

 

 

 

 

 

 

 

  

 
       


免責聲明!

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



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