python 输入与输出

这篇博客主要介绍了Python编程中关于输入和输出的操作,包括使用内置的input()和raw_input()函数进行用户交互,以及如何实现程序的数据输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python 的输入与输出

一、python 输入

1.1 使用内建函数 input()

>>> input()
"hello world"
'hello world'
>>> 
----这里输入字符串需要带 引号,输入数字则不用
>>> input()
1
1
>>> 
----错误例子,会报错
>>> input()
hello world
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    input()
  File "<string>", line 1
    hello world
              ^
SyntaxError: unexpected EOF while parsing
>>> 
----在 input() 时,可以提示 一下,需要输入什么,例:
>>> input("input string:")
input string:"hello world"
'hello world' 
>>> 

1.2 使用内建函数 raw_input()

>>> raw_input("input string: ")
input string: hello world
'hello world'
----raw_input()  会把所有 的输入当作字符串,故不用引号
>>> raw_input()
1
'1'
>>> 

二、python 输出

print 打印,在python中,它打印在 命令行、控制台。它操作的对象是一个 字符串
这里举了几个例来说明
1. print 后面跟字符串需要加引号,可以看一下有引号和没有引号的区别
>>> print "string"
string

# 错误的使用,没有用引号
>>> print string

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    print string
NameError: name 'string' is not defined

>>> print 1
1

>>> print 3.13
3.13

>>> print 1+1
2

>>> print "1+1"
1+1

>>> print 2 > 5
False
>>>

2. 在python 命令行(python shell)中,print 可以省略
>>> "string"
'string'

>>> 1
1

>>> 3.13
3.13

>>> 1+1
2

>>> "1+1"
'1+1'

>>> 2 > 5
False
>>>
3. 格式化输出<这里不作详解,字符串章节再细说>()
>>> string = "hello world"
>>> print "%s" % string
hello world

# 这里 hello world 会占15个字符,不足会左边补空格
>>> print "%15s" % string
    hello world
>>>





















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值