回答

收藏

[教程] 【一网打尽】Raspberry Pi Week 8 – Day 3 (Python Print Function)

Raspberry Pi Raspberry Pi 2030 人阅读 | 0 人回复 | 2015-03-29

Raspberry Pi Week 8 – Day 3 (Python Print Function)

The print function has already been introduced but we will expand on what you have already learned. The print function is used when you need to output data or informational messages. So far you have used the print command with a single argument. This argument was a string.

print(‘Hello Raspberry pi’)

You can also utilise the print function further to output some simple calculations as it spits out a message. Examine the line below.

print(‘Hello Raspberry pi ‘, 5+5)

The result will be

Hello Raspberry Pi 10

Another common desire is to produce a blank line so that the output does not become to cluttered. You can produce a blank line using the following methods

print(‘\n’)

or

print()

The first example uses an escape character which is indicated by a backslash \ followed by a character. In this case the \n indicates that a new line is required. The print function without any arguments will print a blank line but both produce the same result.

Download helloRaspberryPi.py

You can also apply formatting to strings. Although this isn’t the print() function it does however work in a similar way. The format() function is used to output a message and format it. Enter the following into IDLE or download the file.

Download printFormatting.py

>>> ‘I drive a {0} and it can reach speeds of {1}.’.format(‘car’,’42 mph’)

‘I drive a car and it can reach speeds of 42 mph.’

The {0} is used to substitute the first occurrence of the string in the format option. In this case the ‘car’ word will be displayed. You can also repeat the word multiple times throughout the sentence.

‘I drive a {0} and the {0} can reach speeds of {1}.’.format(‘car’,’42 mph’)

It can be a little confusing remembering all those numbers in the correct order so it is better to use variables. Enter the following into IDLE.

‘I drive a {car} and it can reach speeds of {speed}.’.format(car=’Porche’,speed=’180 mph’)

You can also donwload the file below.

Download simplePrintFormatting.py

‘I drive a Porche and it can reach speeds of 180 mph.’

Download the PDF file for Week 8 – Day 3 – Python Print Function

Day-3-Python-print-function.pdf (47.38 KB, 下载次数: 1)


截止到当前时间,这是作者最后的一篇文章了
分享到:
回复

使用道具 举报

您需要登录后才可以回帖 注册/登录

本版积分规则

关闭

站长推荐上一条 /3 下一条