个Python程序——在屏幕上输出文本

1年前 (2024-04-26)
本节我将给大家介绍最简单、最常用的 Python 程序——在屏幕上输出一段文本,包括字符串和数字。

Python 使用 print 函数在屏幕上输出一段文本,输出结束后会自动换行。

在屏幕上输出字符串

字符串就是多个字符的,由双引号" "或者单引号' '包围,例如:

"Hello World"
"Number is 198"

'Pyhon教程:http://c.biancheng网站站点" rel="nofollow" />

print("字符串内容")

或者

print('字符串内容')

字符串要放在小括号( )中传递给 print,让 print 把字符串显示到屏幕上,这种写法在 Python 中被称为函数(Function)

需要注意的是,引号和小括号都必须在英文半角状态下输入,而且 print 的所有字符都是小写。Python 是严格区分大小写的,print 和 Print 代表不同的含义。

print 用法举例:

print("Hello World!") #输出英文

print("Number is 198") #输出数字

print("Pyhon教程:http://c.biancheng网站站点" rel="nofollow" /> print函数用法举例

图 1 print 函数用法举例


也可以将多段文本放在一个 print 函数中:

print(

"Hello World!"

"Number is 198"

"http://c.biancheng网站站点" rel="nofollow" /> 将多个字符串放在一个print中

图 2 将多个字符串放在一个 print 中

对分号的说明

有编程经验的读者应该知道,很多编程语言(比如C语言、C++、Java 等)都要求在语句的加上分号;,用来表示一个语句的结束。但是 Python 比较灵活,它不要求语句使用分号结尾;当然也可以使用分号,但并没有实质的作用(除非同一行有更多的代码),而且这种做法也不是 Python 的。

修改上面的代码,加上分号:

print(198);

print("Hello World!"); print("Python is good!");

print("Pyhon教程:http://c.biancheng网站站点" rel="nofollow" /> 198
Hello World!
Python is good!

Pyhon教程:http://c.biancheng网站站点" rel="nofollow" />

print 198

print "Hello World!"; #末尾也可以加上分号

print "Pyhon教程:http://c.biancheng网站站点" rel="nofollow" /> print( 100 )
print( 65 )
print( 100 + 12 )

print( 8 * (4 + 6) )

注意,输出数字时不能用引号包围,否则就变成了字符串。下面的写法就是一个反面教材,数学表达式会原样输出:

print("100 + 12")

运行结果是100 + 12,而不是 112。

另外,和输出字符串不同,不能将多个数字放在一个 print 函数中。例如,下面的写法就是错误的:

print( 100 12 95 );

print(

80

26

205

);

总结

Python 程序的写法比较简单,直接书写功能代码即可,不用给它套上“外壳”。下面我们分别使用C语言、Java 和 Python 输出C语言中文网的网址,让大家对比感受一下。

使用C语言:

#include <stdio.h>

int main()

{

puts("http://c.biancheng网站站点" rel="nofollow" />

public class HelloJava {

public static void main(String[] args) {

System.out.println("http://c.biancheng网站站点" rel="nofollow" />

print("http://c.biancheng网站站点" rel="nofollow" />