zoukankan      html  css  js  c++  java
  • python随笔6(用户输入input())

    6.1函数input()

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

    message = input("Tell me something:")
    print(message)

    函数input()接受一个参数。程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message中,接下来的print(message)将输入呈现给用户。

    Tell me something:hello everyone!
    hello everyone!

    编写清晰的程序

    每当你使用函数input()时,都应指定清晰而明白的提示,准确地指出你希望用户提供什么样的信息,如下:

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

    有时候,提示可能超过一行。在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input()。

    prompt = "If you tell us who you are,we can personalize the messages you see."
    prompt += "
    What is your first name? "
    
    name = input(prompt)
    print("
    Hello," + name + "!")

    这种示例演示了一种创建多行字符串的方式。第1行将消息的前半部分存储在变量prompt中;在第2行中,运算符 += 在存储在prompt中的字符串末尾附加一个字符串。

    使用int()来获取数值输入

    使用input()函数时,python将用户输入解读为字符串。请看下面让让用户输入其年龄的解释器会话:

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

    用户输入的是数字21,但我们请求python提供变量age的值时,它返回的是’21’——用户输入的数值字符串表示。

    >>> age = input("How old are you? ")
    How old are you? 21
    
    >>> age >= 18
    Traceback (most recent call last):
      File "<stdin>",line 1, in <module>
    TypeError: unorderable types: str() >= int()

    你试图将输入用于数值比较时,python会发生错误,因为它无法将数字与字符串比较。

    为解决这个问题,可以使用函数int(),它让python将输入是为数值。函数int()将数字的字符串表示转换为数值表示:

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

    在实际程序中使用函数int()。下面程序判断一个人的身高够不够坐过山车。

    height = input("How tall are you,in inches? ")
    height = int(height)
    
    if height >= 160:
        print("
    You are tall enough to ride!")
    else:
        print("
    You'll be able to ride when you're a little older.")

    求模运算符

    处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:

    >>> 4 % 3
    1
    >>> 5 % 3
    2
    >>> 6 % 3
    0

    你可以利用求模运算来判断一个数是奇数还是偶数。

    number = input("Enter a number, and I'll tell you if it's even or odd: ")
    number = int(number)
    
    if number % 2 == 0:
        print("
    The number " + str(number) + " is even.")
    else:
        print("
    The number " + str(number) + " is odd.")
  • 相关阅读:
    作业2(4)求m和n之间的和
    作业2(3)计算x的n次方
    作业3(6)查询水果的单价。有 4 种水果,苹果(apples)、梨(pears)、桔子(oranges)和葡萄(grapes),
    作业3(5)输入五级制成绩(A-E),输出相应的百分制成绩(0-100)区间,要求使用 switch语句。
    作业3(4)循环输入多个年份 year,判断该年是否为闰年。判断闰年的条件是:能被 4 整除但不能被100 整除,或者能被 400 整除。输入-1退出程序执行
    P39-习题2-5
    P39-习题2-7
    计算N户电费
    P39-习题2-4
    P39-习题2-3
  • 原文地址:https://www.cnblogs.com/wf1017/p/9403719.html
Copyright © 2011-2022 走看看