输入

作者: SeanPenn | 来源:发表于2018-08-18 22:59 被阅读0次
    1、input方法

      函数input() 让程序暂停运行, 等待用户输入一些文本。 获取用户输入后, Python将其存储在一个变量中, 以方便使用。

        name = input("Please enter your name: ")
        print("Hello, " + name + "!")
    

      函数中的字符串是提示字符串,提示用户应该输入什么样的信息。当提示字符串也可以先用变量保存,再在input()函数中使用该变量:

    prompt = "If you tell us who you are, we can personalize the messages you see."
    prompt += "\nWhat is your first name? "
    name = input(prompt)
    print("\nHello, " + name + "!")
    
    2、int方法

      使用函数input() 时, Python将用户输入解读为字符串。

    >>> age = input("How old are you? ")
    How old are you? 21
    >>> age
    '21'
    

      从上面示例中可以看到读入到age变量里面的是字符串'21',而不是数字21。如果这时候想要的是数字,就需要使用函数int()把输入的字符串转换为数值。

    >>> age = input("How old are you? ")
    How old are you? 21
    >>> age = int(age)
    >>> age
    20
    

      从上面可以看到,age变量经过int函数转换后,已经变成了数值。

    相关文章

      网友评论

          本文标题:输入

          本文链接:https://www.haomeiwen.com/subject/avjqiftx.html