Fork me on GitHub

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,这样就能解释通上边的问题了。

 

原文链接:https://www.cnblogs.com/mxh1099/p/5412299.html

 

posted @ 2022-07-16 09:38  MR_黄Python之路  阅读(209)  评论(0编辑  收藏  举报