Текст книги "Python Handbook For Beginners"
Автор книги: Roman Gurbanov
сообщить о нарушении
Текущая страница: 2 (всего у книги 2 страниц)
5 Strings Concatenation And Variables
Note that we can concatenate a string only with another string. Or a string-formatted value. For example, if we created a variable and assigned a string-formatted value to it, we can also concatenate such a variable with another string. In the example below, I created a variable (hero) and assigned a string-formatted value (Super Cat) to it. Then I displayed this value in concatenation with another string (VS Duper Dog).
hero = «Super Cat»
print(hero + " VS Duper Dog")
Try this code out. What message do you get? Now, change the code as you like. You can even concatenate more than two strings! Alter and run the code. See how the output changes!
6 String Formatting
Now let's talk about what string formatting is. We have already learned how to concatenate strings using the + operator. The + operator can only concatenate a string with another string. But what if we want to concatenate a string with something that doesn't have a string format? In this case, we use string formatting to turn a value that doesn't have a string format into a string-formatted value. To do so, we need two things:
The format() method to format the non-string value and insert it inside the string's placeholder.
The placeholder itself – {} for the non-string value.
Let me show you how it works in the example below:
print(«My name is Super Cat, and I'm {} years old».format(2))
Please write this code into the console and run it. Here is the result you should get:
Now let's break it down.
1) We created a placeholder in our string. You can identify it by the curly brackets – {}. This placeholder is for the age of the Super Cat, which has a numeric value.
2) After the string end, we put the format() method and passed our numeric value, 2, to its brackets.
3) As a result of this operation, Python took our numeric value, formatted it into a string value, and passed it to the placeholder. So now it belongs to the entire string in the same string format.
4) After that, we displayed the entire string using the print function.
I encourage you to play with the given code and experiment with placeholders and values you pass to the format() method. Here is another way to accomplish the above exercise:
print(«My name is {}, and I'm {} years old». format(«Super Cat»,2)
Can you explain how it works now? Can you come out with your ideas?
7 Wrapping Up Chapter Four
In chapter four, we have accomplished the following:
1) Learned what are strings in Python;
2) Learned how to store a string in a variable;
3) Learned how to concatenate strings;
4) Learned how to concatenate strings with variables values;
5) Leaned string formatting.
8 Chapter Four Test
1. What is a string?
1) A string is a line that goes through the code.
2) A string is text data enclosed in quotes.
3) A string is an integer formatted value.
4) A string is a float formatted value.
2. How do we create a string?
1) We write a text and enclose it in curly braces.
2) We write a text and enclose it in parentheses.
3) We write a text and enclose it and enclose it in quotes.
3. Arrange the code so that you get a variable with a value as a string. And then display the value of the variable on the screen.
(message)
message
"Hello, John Doe!"
=
CHAPTER FIVE: BOOLEANS
1 Comparison Operators
When we compare numbers to each other, we usually use the symbols like > (greater), < (less), = (equal), and so on. They work in Python too. And here's how they look:
Greater >
Less <
Equal ==
Not equal !=
Greater than or equal > =
Less than or equal <=
As you noticed, instead of the equal sign =, we need to use the double equal sign ==.
We need the double equal sign so that Python doesn't think we are trying to create a variable.
These symbols are called comparison operators in Python. And we need them to let our program compare different data, for instance: numbers, strings, variables, etc.
2 True or False
Boolean logic has Boolean values: True and False: True – when the condition is true. False – when the condition is false. Let's play! I will compare numbers, and you will answer in your head – True if it is true, or False if it is false. Let's go!
2 > 4
10 < 20
3 == 3
5 != 7
Now, let's check yourself. Run the console and hit the REPL button. Then, input the above comparisons into the input field, one by one, and hit enter. If your comparison is correct, the program will respond: True. If not, then False. Let's see how the examples above look in the console:
See that? This is how Boolean logic and values work. But what if we try comparing strings? Try comparing apples to oranges using the following:
"apples" == "oranges"
See the output? Now, try changing comparison operators and values to your liking. See what happens? Now you know that Boolean logic works not only with numeric but with other data formats in programming.
3 True and False in Variables
Let us see how we can use True and False values in variables. We can store results from comparisons that return True or False in variables. This is how it works:
result = «apples» == «oranges»
print(result)
Run the above code in the console and see what it returns. Let's break it down.
I've created a variable named result in this code and assigned it a Boolean value from comparing the two strings "apples" and "oranges ".
Then I went down one line and printed the value of the "result" variable on the screen, passing the variable name in parentheses to the print function.
Does it make sense?) Now, alter the code by indicating that apples and oranges are not equal. What does the program return?
4 Comparing Variables
Not only can we compare numbers and strings, but the entire variables too! See how we can do it:
fruit = «Kiwi»
result = fruit == "Apple"
print(result)
Before you write the code into the console and hit enter, think of what output it will return? Let's break it down:
Конец ознакомительного фрагмента.
Текст предоставлен ООО «ЛитРес».
Прочитайте эту книгу целиком, купив полную легальную версию на ЛитРес.
Безопасно оплатить книгу можно банковской картой Visa, MasterCard, Maestro, со счета мобильного телефона, с платежного терминала, в салоне МТС или Связной, через PayPal, WebMoney, Яндекс.Деньги, QIWI Кошелек, бонусными картами или другим удобным Вам способом.