Home  >  Article  >  Backend Development  >  This article will help you understand the input and output of Python

This article will help you understand the input and output of Python

Go语言进阶学习
Go语言进阶学习forward
2023-07-25 13:59:586856browse

1. Why do we need input and output?

Whether it is "hello world" from the beginning or the previous examples, they are basically "talking to themselves" and showing code snippets of classes. Only a program that can receive user input, generate results based on the input code, and output them to the screen can be considered a relatively complete and simple program.


2. input input function

Get user input and save it as A string. If it's important, say it twice, the return value of the input function is a string type. Even if you enter a number 1, what will be returned to you will only be the string "1", not the integer 1. Here are some simple display examples:

#第一个例子
>>> inp  = input("please input your name: ")
please input your name: jack
>>> inp
'jack'
>>> type(inp)
<class &#39;str&#39;>


#第二个例子
age  = input("please input your age: ")
please input your age: 18
 print(age)
&#39;18&#39;


#第三个例子
>>> type(age)
<class &#39;str&#39;>


#第四个例子


>>> a = input("请输入一个字符:")
&#39;请输入一个字符:前后带有空白&#39; 
>>> a
&#39;   前后带有空白   &#39;

In the first example, inp = input("please input your name: "), a string can be provided in the input function to prompt the user for input. After the return value of the input function is assigned to the inp variable, the value entered by the user is stored in inp.

type是Python内置的函数之一,非常有用,用于查看对象的数据类型。

第二个例子,  输入了年龄18,但age里保存的是一个“18”的字符串。

第三个例子,什么都没输入,返回的是一个空字符串。

第四个例子,有效输入的前后空白被保留在了返回的字符串中。

从上面例子的展示中,不难发现,input函数将用户的输入原样不动的返回给了变量 ,并包装成一个字符串。这肯定是不行的,会带来很多问题,所以通常都需要对用户输入进行处理和判定。

  • 对空输入进行处理:

inp = input("请输入你的姓名:  ")


if inp == "":    
    inp = input("姓名不能为空,请重新输入:  ")
  • 将字符串转换成数字类型:

age = input("请输入你的年龄:")


age = int(age)   # 将字符串转化为整数


if age > 18:
    print("你已经成年!")
else:
    print("还没断奶?")
  • 去除开头的空白lstrip,去除结尾的空白rstrip以及去除两端的空白strip

inp = input("请输入你的姓名:  ")


inp = inp.strip()  # strip的用法在字符串数据类型有讲述


print(inp)
  • 判断输入的字符类型

前面在将字符串转化为整数用的是int()函数,这种方式有危险的,看下面的例子:

s = "123"
a = int(s)
print(a)


s = "something"
a = int(s)

This article will help you understand the input and output of Python

对于形如“123”, “283242”的字符串,转化没问题,但是对于包含字符、特殊字符的字符串就没办法转化了,会弹出异常错误。所以在使用int函数之前,要先对输入进行判断。 

修改一下上面的例子:

age = input("请输入你的年龄:")


if age.isdigit():   # 使用isdigit函数判断输入是否全是数字格式
    age = int(age)   # 将字符串转化为整数
    print("你的年龄是:", age)
else:
    print("输入不合法!")

This article will help you understand the input and output of Python

This article will help you understand the input and output of Python

  • input函数有时可以巧妙地用于阻塞或暂停程序

print("程序前面部分执行完毕......")


input("请按回车继续......")       # 在这里程序会暂停,等待你的回车动作


print("继续执行程序的后面部分......")

此时的input函数不会将输入保存下来,只是用作暂停程序动作。


三、 print输入函数

print函数用于将内容格式化显示在标准输出上,主要指的是屏幕显示器。

print可以接受多个字符串,字符串类型的变量或者可print的对象。每个字符串用逗号“,”隔开,连成一串输出。print会依次打印每个字符串,同时,每遇到一个逗号“,”就输出一个空格。

a = "i am"
b = "student"
print(a,"a", b)
# 自动以空格分隔
print(a+"a"+b)

This article will help you understand the input and output of Python

    对于形如print(a+"a"+b)的语句,其实是先计算a+"a"+b的值,然后再通过print打印它。print()会自动执行内部的语句,输出想要的结果。再看一个例子:

>>> a = 10
>>> b = 2
>>> print(sum((a, a*b)))        # 先求a*b,再求和,再打印
30   #结果

 看一下print函数的原型:print(self, *args, sep=' ', end='\n', file=None)

sep参数: 分隔的符号,默认是一个空格;

end参数: 打印后的结束方式,默认为换行符\n。如果,设置end='',则可以不换行,让print在一行内连续打印。活用print的参数,可以实现灵活的打印控制。

>>> a = "i am"
>>> b = "student"
>>> print(a,"a" , b, sep="*")
i am*a*student #输出结果

四、 print格式化输出

在Python2.6以后,有两种格式化输出的方式。

一种就是类似C语言的printf的%百分号格式化输出,也是Python最基础最常用的格式化输出方式。另一种就是str.format()的方式。

这里  重点讲述一下传统的%百分号格式化输出方式,

以下面的语句为例:

print ("我叫 %s 今年 %d 岁!" % (&#39;小明&#39;, 10))

首先构造一个字符串"我叫 %s 今年 %d 岁!",将其中需要用别的变量或值替代的部分,用%百分符加一个数据类型代号,比如%s%d来代替。然后在字符串的后面用%加一个同样数量变量或值的元组。

也就是前面有多少个%符号,后面就要提供多少个参数值,每个参数值之间用逗号隔开,所有参数用圆括号括起来。每个参数与前面的%一一对应,并且数据类型也要能够合法对应。

这是基本用法,更多的格式见下图,然后掌握格式的搭配方法。

格式化符号:

This article will help you understand the input and output of Python

格式化操作符辅助指令:

This article will help you understand the input and output of Python

经典案例:

s = "i am %s" % "jack"
print(s)


s = "i am %s age %d" % ("jack", 18)
print(s)


s = "i am %(name)s age %(age)d" % {"name": "jack", "age": 18}
print(s)
s = "percent %.2f" % 99.97623
print(s)
s = "i am %(pp).2f" % {"pp": 123.425556, }
print(s)
s = "i am %.2f %%" % 123.425556
print(s)

This article will help you understand the input and output of Python

    需要特别说明的是,如果你想在print中打印一个%百分符号本身,那么你需要使用%%,两个百分符转义出一个百分符,也就是print("%%")。

    如果你对print复杂的格式化控制无爱,对美观也没有要求,那么简单傻瓜式的一路用%s作为占位符,是种省事的做法。例如:

print("%s %s %s %s %s" % (a, b, c, d, e))

五、总结

    本文基于Python基础,介绍了常见的几种输入和输出的几种方式,通过一个个项目的实际操作,能够更好的理解输入和输出语句的用法。在项目实践过程中遇到的难点,需要注意的点做了详细讲解。

The above is the detailed content of This article will help you understand the input and output of Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete