search
HomeBackend DevelopmentPython TutorialThis article will help you understand the input and output of Python


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
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!