Чтение онлайн

на главную - закладки

Жанры

Python Handbook For Beginners
Шрифт:

Hence, Python will add 5 and 5, which will result in 10. And multiply 10 by 3, which will result in 30. Was your answer – 30? Or was it something else?)

6 Numbers and Variables

By this time, we've learned print function, variables, and numbers in Python. Let's combine them all!

Let's write an example with numbers, save its result in a variable, and then display it. Here is how it looks like:

result = 2+2

print(result)

Guess what the output will be? Please take the above code and run it in the console to check it out.

Let's break it down:

1) First, we declared a variable, giving it the name "result" and the value "1 + 1";

2) Then we went down one line, wrote the print function, and passed the name of our variable in its brackets;

3) When we ran the code, Python calculated the value of the variable by adding 2 + 2;

4) The calculation returned 4, and Python assigned this value to the variable "result";

5) Then Python saw that we want to display the result's value because of the print (result) and print it accordingly.

As you can see, numbers and variables work well together in Python.

Let's practice some more and create your examples with numbers and variables, similar to what we just saw. Here are some boilerplate examples for you:

___________

result = 2+2

print(result)

___________

result = 10-5

print(result)

___________

result = 5*5

print(result)

___________

result = 10/2

print(result)

___________

7 Wrapping Up Chapter Three

In chapter three, we have accomplished the following:

1) Refreshed on what are integers and fractional numbers;

2) Learned basic math operators used in Python;

3) Learned how to divide a number without remainder in Python;

4) Got to know the order of calculation in Python;

5) Combined numbers and variables in math examples.

8 Chapter Three Test

1. What types of numbers are there in Python?

1) There are three types of numbers in Python: Integers, almost whole numbers, and fractional.

2) There are two types of numbers in Python: Integers and half integers.

3) There are two types of numbers in Python: Integers – integer and fractional numbers.

2. How does Python divide 10 by 5? (Multiple selection)

1) 10:5

2) 10/5

3) 10-5

4) 10 * 5

5) 10 // 5

3. Arrange the parts of the code so that you get the integer 4.

five

10*2

//

4. This code should display 5. But what is missing?

result = 10/2

_____(result)

CHAPTER FOUR: STRINGS

1 Strings in Python

Do you remember the messages we displayed in chapter one, like "Hey! This is my first line of code!" or "Once upon a time.." They are all strings. In other words, a string is a data type that has a text format, or just a text, enclosed in quotes. Hence, to create a string, we have to type a text and enclose it in quotes.

2 Strings And Print Function

Let's write a code that would display the string – "Now I know what a string is in Python." You already know how to display strings in Python, right? Here is the code.

print("Now I know what a string is in Python.")

Write the above line into the console and hit run. Now it's your turn. Think of some different string, rewrite and run the above code.

3 Saving Strings in Variables

Do you remember our first variable: film = "Super Cat"? Now you know that the value of the variable – "Super Cat" had a string format, as we enclose it in quotes. Let's take our knowledge further, create a message in a string format, save it in a variable, and display the variable value on your screen using the print function. Let me do it first:

message = "Hello, Super Cat!"

print(message)

Run this code in the console. What do you see? Now it's your turn. Following the above example, think of any message. Right it down as a string. Save it in a variable and display the variable value using the print function. What you've got?

4 Strings Concatenation

We can combine strings. There is a method for that, called – concatenation. All we have to do to concatenate strings is to put addition operator + between them. Easy right? If so, let's get concatenating!

"Super Cat" + "saves the day!"

Now, let's display the two concatenated strings:

print("Super Cat" + "saves the day!")

Write this code into the console and hit run. Have you noticed something weird? Hmm. It looks like our lines stuck together. No worries. We can quickly fix that. There are several ways to do it but let's stick with the most simple – leave a space between the quote and string:

print("Super Cat" +" saves the day!")

Have you fixed that? Hit run again.

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).

Поделиться:
Популярные книги

Брачный сезон. Сирота

Свободина Виктория
Любовные романы:
любовно-фантастические романы
7.89
рейтинг книги
Брачный сезон. Сирота

Адвокат империи

Карелин Сергей Витальевич
1. Адвокат империи
Фантастика:
городское фэнтези
попаданцы
фэнтези
5.75
рейтинг книги
Адвокат империи

Лейб-хирург

Дроздов Анатолий Федорович
2. Зауряд-врач
Фантастика:
альтернативная история
7.34
рейтинг книги
Лейб-хирург

Измена. Верни мне мою жизнь

Томченко Анна
Любовные романы:
современные любовные романы
5.00
рейтинг книги
Измена. Верни мне мою жизнь

На границе империй. Том 5

INDIGO
5. Фортуна дама переменчивая
Фантастика:
боевая фантастика
попаданцы
7.50
рейтинг книги
На границе империй. Том 5

Бастард Императора. Том 2

Орлов Андрей Юрьевич
2. Бастард Императора
Фантастика:
фэнтези
попаданцы
аниме
5.00
рейтинг книги
Бастард Императора. Том 2

На изломе чувств

Юнина Наталья
Любовные романы:
современные любовные романы
6.83
рейтинг книги
На изломе чувств

Буревестник. Трилогия

Сейтимбетов Самат Айдосович
Фантастика:
боевая фантастика
5.00
рейтинг книги
Буревестник. Трилогия

Убивать чтобы жить 6

Бор Жорж
6. УЧЖ
Фантастика:
боевая фантастика
космическая фантастика
рпг
5.00
рейтинг книги
Убивать чтобы жить 6

Приватная жизнь профессора механики

Гулиа Нурбей Владимирович
Проза:
современная проза
5.00
рейтинг книги
Приватная жизнь профессора механики

Башня Ласточки

Сапковский Анджей
6. Ведьмак
Фантастика:
фэнтези
9.47
рейтинг книги
Башня Ласточки

Два мира. Том 1

Lutea
Фантастика:
фэнтези
попаданцы
мистика
5.00
рейтинг книги
Два мира. Том 1

Отрок (XXI-XII)

Красницкий Евгений Сергеевич
Фантастика:
альтернативная история
8.50
рейтинг книги
Отрок (XXI-XII)

Все ведьмы – стервы, или Ректору больше (не) наливать

Цвик Катерина Александровна
1. Все ведьмы - стервы
Фантастика:
юмористическая фантастика
5.00
рейтинг книги
Все ведьмы – стервы, или Ректору больше (не) наливать