print() 's end keyword argument to skip newlines.
Most of the games in this book will have simple text for input and output. The input is typed by the user on the keyboard and entered to the computer. The output is the text displayed on the screen. In Python, the print() function can be used for displaying print() function, but there is more to learn about how strings and print() work in Python.
What do you get when you cross a snowman with a vampire? Frostbite! What do dentists call an astronaut's cavity? A black hole! Knock knock. Who's there? Interrupting cow. Interrupting cow wh-MOO!
Here is the source code for our short jokes program. Type it into the file editor and save it as jokes.py. If you do not want to type this code in, you can also download the source code from this book's website at the URL http://inventwithpython.com/chapter5.
jokes.py
This code can be downloaded from http://inventwithpyt.hon.com/jokes.py
If you get errors after typing this code in, compare it to the book's code with the online
diff tool at http://inventwithpython.com/diff or email the author at
al@inventwithpython.com
1. print('What do you get when you cross a snowman with a vampire?')
2. input ()
3. print('Frostbite ! ' )
4. print()
5. print('What do dentists call a astronaut\'s cavity?')
6. input ()
7. print('A black hole!')
8. print()
9. print('Knock knock.')
10. input ()
11. print("Who's there?")
12. input()
13. print('Interrupting cow.')
14. input ()
15. print('Interrupting cow wh', end='')
16. print('-MOO!')
Don't worry if you don't understand everything in the program. Just save and run the program. Remember, if your program has bugs in it, you can use the online diff tool at http://inventwithpython.com/chapter5.
Let's look at the code more
1. print('What do you get when you cross a snowman with a vampire?')
2. input ()
3. print('Frostbite ! ' )
4. print()
Here we have three print() function calls. Because we don't want to tell the player what the joke's input() function after the first print (). The player can read the first line, press Enter, and then read the
The user can still type in a string and hit Enter, but because we aren't storing this string in any variable, the program will just forget about it and move to the next line of code.
The last print() function call has no string argument. This tells the program to just print a blank line. Blank lines can be useful to keep our text from being bunched up together.
5. print('What do dentists call a astronaut\'s cavity?')
6. input ()
7. print('A black hole!')
8. print()
In the first print()above, you'll notice that we have a \ is a backslash, / is a print() the
We have to have the
What if you really want to display a backslash? This line of code would not work:
>>> print('He flew away in a green\teal helicopter.')
That print() function call would show up as:
He flew away in a green eal helicopter.
This is because the "t" in "teal" was seen as an
Instead, try this line:
>>> print('He flew away in a green\\teal helicopter.')
Here is a list of
| What Is Actually Printed | |
|---|---|
\\
| Backslash (\) |
\'
| |
\"
| |
\n
| Newline |
\t
| Tab |
Strings don't always have to be in between
>>> print('Hello world')
Hello world
>>> print("Hello world")
Hello world
But you cannot mix quotes. This line will give you an error if you try to use them:
>>> print('Hello world")
SyntaxError: EOL while scanning single-quoted
string
>>>
I like to use
But remember, just like you have to use the
>>> print('I asked to borrow Abe\'s car for a
week. He said, "Sure."')
I asked to borrow Abe's car for a week. He said,
"Sure."
>>> print("He said, \"I can't believe you let him
borrow your car.\"")
He said, "I can't believe you let him borrow your
car."
Did you notice that in the
9. print('Knock knock.')
10. input ()
11. print("Who's there?")
12. input()
13. print('Interrupting cow.')
14. input ()
15. print('Interrupting cow wh', end='')
16. print('-MOO!')
Did you notice the second parameter on line 15's print()? Normally, print() adds a newline character to the end of the string it prints. (This is why a blank print() function will just print a newline.) But the print() function can optionally have a second parameter (which has the name end.) The blank string we are passing is called a keyword argument. The end parameter has a specific name, and to pass an argument to this specific parameter we need to use the end= syntax.
Notice that when you type the keyword and the keyword argument, you use only one = sign. It is end='', and not end==''.
By passing a blank string for the end we tell the print() function to not add a newline at the end of the string, but instead add a blank string. This is why '-MOO!' appears next to the previous line, instead of on its own line. There was no newline printed after the 'Interrupting string.
This chapter briefly covered how software (including our Python programs) runs on your computer. Python is a higher-level programming language that the Python interpreter (that is, the Python software you have downloaded and installed) converts into machine language. Machine language are the 1s and 0s that make up instructions that your computer can understand and process.
The rest of this chapter explores the different ways you can use the print() function. \ followed by a single letter for the \n would print out a newline. To display a backslash, you would use the \\.
The print() function automatically appends a newline character to the end of the string we pass it to be displayed on the screen. Most of the time, this is a helpful shortcut. But sometimes we don't want a newline character at the end. To change this, we pass the end keyword argument with a blank string. For example, to print "spam" to the screen without a newline character, you would call print('spam', end='').
By adding this level of control to the text we display on the screen, we have much more flexible ways to display text on the screen the exact way we want to.
Для получения официальных документов о завершении программы дополнительного профессионального образования (удостоверения о повышении квалификации, дипломов о профессиональной переподготовке и MBA) необходимо предоставить:
Внимание! Вы можете не заказывать доставку бумажной версии официального документы, а скачать его в электронном виде и распечатать самостоятельно. Информация о выданном документе в течение 1 месяца загружается в Федеральную информационную систему «Федеральный реестр сведений о документах об образовании и (или) о квалификации, документах об обучении» - ФИС ФРДО.
Доступ на новый сайт осуществляется с использованием адреса электронной почты, который был указан вами при регистрации на "старом". Мы постарались перенести все ваши данные с прежнего ресурса, однако не исключена вероятность потери части информации.
При возникновении проблемы со входом, воспользуйтесь функцией сброса пароля
Если вы обнаружите несоответствия, пожалуйста, сообщите нам.