交互:在终端中输入用户信息

Python可以允许用户在终端中输入一些信息。

Input功能

接受输入字符串

# -*- coding: utf-8 -*-
name = input("Please input your name:")
print("Hello " + name + "!")

其运行结果如下:

Please input your name:Cedar
Hello Cedar!

接受输入数字

age = input("How old are U:")
print("age " + age );
if age > 18:
    print("U are %d" % age)

其运行结果如下:

How old are U:33
age 33
Traceback (most recent call last):
  File "F:\python_test\input.py", line 8, in <module>
    if age > 18:
       ^^^^^^^^
TypeError: '>' not supported between instances of 'str' and 'int'

从上面的结果来看,age 这个变量接收的输入应该是字符串,而不是数值类型。这个地方应该使用int()来将类型转换。

age = input("How old are U:")
print("age " + age );
age = int(age)
if age > 18:
    print("U are %d" % age)

其运行结果如下:

How old are U:33
age 33
U are 33
posted on 2025-09-25 18:58  小樊童鞋  阅读(8)  评论(0)    收藏  举报