automated terminal push

This commit is contained in:
2025-06-05 07:33:41 -04:00
parent 19decb39cc
commit 1cb989b04d
619 changed files with 10585 additions and 0 deletions

View File

@@ -0,0 +1,486 @@
# Chapter 2.2. Simple Calculations Exam Problems
In the previous chapter, we explained how to work with the system console how to **read numbers** from it and how to **print the output**. We went through the main arithmetical operations and briefly mentioned data types. Now, we are going to practice what we have learned by solving a few **more complex exam problems**.
## Reading Numbers from The Console
Before going to the tasks, we are going to revise the most important aspects of what we have studied in the previous chapter. We will start by reading numbers from the console.
### Reading an Integer
We need to create a variable to store the integer (for example, **`num`**) and use a standard command for reading input from the console (the function **`input(…)`**), combined with the function **`int(…)`** which converts a string to an integer:
```python
num = int(input())
```
### Reading a Floating-Point Number
We read a floating-point number, the same way we read an integer one, but this time we use the function **`float(…)`**:
```python
num = float(input())
```
## Printing Text Using Placeholders
A **placeholder** is an expression that is replaced with a particular value while printing an output. The function **`print(…)`** supports printing a string based on a placeholder, there are a few ways to do that, as we reviewed in the previous chapter:
- The first argument that we pass to the function is the formatted string, followed by the symbol **`%`** and the number of arguments, equal to the number of placeholders, placed in brackets:
```python
print("You are %s %s, a %d-years old person from %s." % ("Ivan", "Ivanov", "16", "Burgas"))
```
- The second way is the so-called "f-strings", where before the formatted string we put the symbol **`f`** and the arguments are in the string between curled brackets **`{}`**:
```python
first_name = "Ivan"
last_name = "Ivanov"
age = 21
town = "Burgas"
print(f"You are {first_name} {last_name}, a {age}-years old person from {town}.")
```
There are other ways to format a string and the more curious of you can check them in the following article, as well as find the difference between them:[https://cito.github.io/blog/f-strings/](https://cito.github.io/blog/f-strings/)
## Arithmetic Operators
Let's revise the main arithmetic operators for simple calculations.
### Operator +
```python
result = 3 + 5 # the result is 8
```
### Operator -
```python
result = 3 - 5 # the result is -2
```
### Operator \*
```python
result = 3 * 5 # the result is 15
```
### Operator / and //
```python
result = 5 / 2 # the result is 2.5 (fractional division)
result2 = 7 // 3 # the result is 2 (integer division)
```
## Concatenation
By using the operator **`+`** between string variables (or between a string and a number), concatenation is being performed (combining strings):
```python
firstName = "Ivan";
lastName = "Ivanov";
age = 19;
str = firstName + " " + lastName + " is " + age + " years old";
# Ivan Ivanov is 19 years old
```
## Exam Problems
Now, after having revised how to make simple calculations and how to read and print numbers from the console, let's go to the tasks. We will solve a few **problems from a SoftUni practical exam**.
## Problem: Training Lab
**A training lab** has a rectangular size **l** x **w** meters, without columns on the inside. The hall is divided into two parts- left and right, with a hallway approximately in the middle. In both parts, there are **rows with desks**. In the back of the hall, there is a big **entrance door**. In the front, there is a **podium** for the lecturer. A single **working place** takes up **70 x 120 cm** (a table with size 70 x 40 cm + space for a chair and passing through with size 70 x 80 cm). **The hallway** width is at least **100 cm**. It is calculated that due to the **entrance door** (which has 160 cm opening) **exactly one working space is lost**, and due to the **podium** (which has a size of 160 x 120 cm) exactly **two working spaces** are lost. Write a program that reads the size of the training lab as input parameters and calculates the **number of working places in it** (look at the figure).
### Input Data
**Two numbers** are read from the console, one per line: **l** (length in meters) and **w** (width in meters).
Constraints: **3 ≤ w ≤ l ≤ 100**.
### Output Data
Print an integer in the console: **the number of working places** in the training lab.
### Sample Input and Output
| Input | Output | Figure |
| ---------- | ------ | ------------------------------------------------------ |
| 15<br>8.9 | 129 | ![](/assets/chapter-2-2-images/01.Training-lab-01.png) |
| 8.4<br>5.2 | 39 | ![](/assets/chapter-2-2-images/01.Training-lab-02.png) |
#### Clarification of The Examples
In the first example, the hall length is 1500 cm. **12 rows** can be situated in it (12 _ 120 cm = 1440 + 60 cm difference). The hall width is 890 cm. 100 cm of them are for the hallway in the middle. The rest 790 cm can be situated by **11 desks per row** (11 \* 70 cm = 770 cm + 20 cm difference). \*\*Number of places = 12 _ 11 - 3** = 132 - 3 = **129\*\* (we have 12 rows with 11 working places = 132 minus 3 places for podium and entrance door).
In the second example, the hall length is 840 cm. **7 rows** can be situated in it (7 \* 120 cm = 840, no difference). The hall width is 520 cm. 100 cm from them is for the hallway in the middle. The rest 420 cm can be situated by **6 desks per row** (6 \* 70 cm = 420 cm, no difference). **Number of places = 7 \* 6 - 3** = 42 - 3 = **39** (we have 7 rows with 6 working places = 42 minus 3 places for podium and entrance door).
### Hints and Guidelines
Try to solve the problem on your own first. If you do not succeed, go through the hints.
#### Idea for Solution
As with any programming task, **it is important to build an idea for its solution**, before having started to write code. Let's carefully go through the problem requirements. We have to write a program that calculates the number of working places in a training lab, where the number depends on the hall length and height. We notice that the provided input data will be **in meters** and the information about how much space the working places and hallway take, will be **in centimeters**. To do the calculations, we will use the same measuring units, no matter whether we choose to convert length and height into centimeters or the other data in meters. The first option is used for the presented solution.
Next, we have to calculate **how many columns and how many rows** with desks will fit. We can calculate the columns by **subtracting the width by the necessary space for the hallway (100 cm)** and **dividing the difference by 70 cm** (the length of a workplace). We find the rows by dividing **the length by 120 cm**. Both operations can result in **a real number** with a whole and a fractional part, but we have to **store only the whole part in a variable**. In the end, we multiply the number of rows by the number of columns and divide it by 3 (the lost places for entrance door and podium). This is how we calculate the needed value.
#### Choosing Data Types
From the example, we see that a real number with whole and fractional parts can be given as an input, therefore, it is not appropriate to choose data type **`int`**. This is why we use **`float`**. Choosing a data type for the next variables depends on the method we choose to solve the problem. As with any programming task, this one has **more than one way to be solved**.
#### Solution
It is time to go to the solution. We can divide it into three smaller tasks:
- **Reading input from the console**.
- **Doing the calculations**.
- **Printing the output on the console**.
The first thing we have to do is read the input from the console. With **`input(…)`** we read the values from the console and with the function **`float(…)`** string is converted into **`float`**.
![](/assets/chapter-2-2-images/01.Training-lab-03.png)
Let's move to the calculations. The special part here is that after having divided the numbers, we have to store only the whole part of the result in a variable.
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td><b>Search in Google!</b> Whenever we have an idea how to solve a particular problem, but we do not know how to write it in Python or we are dealing with one that many other people have had before us, the easiest way to solve it is by looking for information on the Internet.</td>
</tr></table>
In this case, we can try with the following search: "[**_Python gets whole number part of float_**](https://www.google.com/?q=python+get+whole+number+part+of+float)". One possible way is to use the method **`math.trunc(…)`** and don't forget to refer to the **`math`** library. The code down below is blurred on purpose and it should be completed by the reader:
![](/assets/chapter-2-2-images/01.Training-lab-04.png)
With **`print(…)`** we print the result in the console:
![](/assets/chapter-2-2-images/01.Training-lab-05.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#0](https://judge.softuni.org/Contests/Practice/Index/1048#0).
## Problem: Vegetable Market
A gardener is selling his harvest on the vegetable market. He is selling **vegetables for N BGN per kilogram** and **fruits for M BGN per kilogram**. Write a program that **calculates the earnings of the harvest in Euro**. (Assume that **1 EUR** is equal to **1.94 BGN**).
### Input Data
**Four numbers** are read from the console, one per line:
- First line: Vegetable price per kilogram a floating-point number.
- Second line: Fruit price per kilogram a floating-point number.
- Third line: Total kilograms of vegetables an integer.
- Fourth line: Total kilograms of fruits an integer.
**Constraints: all numbers will be within the range from 0.00 to 1000.00.**
### Output Data
Print on the console **one floating-point number: the earnings of all fruits and vegetables in EUR**.
### Sample Input and Output
| Input | Output |
| ------------------------- | ------ |
| 0.194<br>19.4<br>10<br>10 | 101 |
**Clarification for the first example:**
- Vegetables cost: 0.194 BGN. \* 10 kg. = **1.94 BGN.**
- Fruits cost: 19.4 BGN. \* 10 kg. = **194 BGN.**
- Total: **195.94 BGN. = 101 EUR**.
| Input | Output |
| ---------------------- | ---------------- |
| 1.5<br>2.5<br>10<br>10 | 20.6185567010309 |
### Hints and Guidelines
First, we will give a few ideas, followed by particular hints for solving the problem and the essential part of the code.
#### Idea for Solution
Let's first go through the problem requirements. In this case, we have to calculate **the total income** from the harvest. It equals **the sum of the earnings from the fruits and vegetables** which we can calculate by multiplying **the price per kilogram by the quantity**. The input is given in BGN and the output should be in euros. It is assumed that 1 EUR equals 1.94 BGN, therefore, to get the wanted **output value, we have to divide the sum by 1.94**.
#### Choosing Data Types
After we have a clear idea of how to solve the task, we can continue with choosing appropriate data types. Let's go through the **input**: we have **two integers** for total kilograms of vegetables and fruits, therefore, the variables we declare to store their values will be of **`int`** type. The prices of the fruits and vegetables are said to be **two floating-point numbers** and therefore, the variables will be of **`float`** type.
We can also declare two variables to store the income from the fruits and vegetables separately. The **output** should be a **floating-point number**, so the result should be **`float`** type.
#### Solution
It is time to get to the solution. We can divide it into three smaller tasks:
- **Reading input from the console**.
- **Doing the calculations**.
- **Printing the output** on the console.
To read the input, we declare variables, which we have to name carefully so that they can give us a hint about the values they store. With **`input(…)`**, we read values from the console and with the functions **`int(…)`** and **`float(…)`**, we convert the particular string value into int and double:
![](/assets/chapter-2-2-images/02.Vegetable-market-01.png)
We do the necessary calculations:
![](/assets/chapter-2-2-images/02.Vegetable-market-02.png)
The task does not specify a special output format, therefore, we just have to calculate the requested value and print it on the console. As in mathematics and so in programming, the division has a priority over addition. However, in this task, first, we have to **calculate the sum** of the two input values and then **divide by 1.94**. To give priority to addition, we can use brackets. With **`print(…)`** we print the output on the console:
![](/assets/chapter-2-2-images/02.Vegetable-market-03.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#1](https://judge.softuni.org/Contests/Practice/Index/1048#1).
## Problem: Change Tiles
On the ground in front of an apartment building **tiles need to be placed**. The ground has a **square shape with a side of N meters**. The tiles are **"W" meters wide** and **"L" meters long**. There is one bench on the ground with a **width of "M" meters and a length of "O" meters**. There is no need to place tiles under it. Each tile is replaced for **0.2 minutes**.
Write a program that **reads from the console the size** of **the ground, the tiles and the bench**, and calculates **how many tiles are needed** to cover the ground and what is the total **time for placing all of the tiles**.
**Example: ground with size 20 m** has an **area of 400 $$m^2$$**. **A bench** that is **1 m** wide and **2 m** long, has an area of **2 $$m^2$$**. One **tile** is **5 m wide** and **4 m long** and has an **area of 20 $$m^2$$**. **The space** that needs to be covered is **400 - 2 = 398 $$m^2$$**. **398 / 20 = 19.90 tiles** are necessary. The **time** needed is **19.90 \* 0.2 = 3.98 minutes.**
### Input Data
The input data comes as **5 numbers**, which are read from the console:
- **N length** of **a side** of **the ground** within the range of [**1 … 100**].
- **W width** per **tile** within the range of [**0.1 … 10.00**].
- **L length** per **tile** within the range of [**0.1 … 10.00**].
- **M width** of **the bench** within the range of [**0 … 10**].
- **O length** of **the bench** within the range of [**0 … 10**].
### Output Data
Print on the console **two numbers**:
- **number of tiles** needed for the repair
- **total time for placing them**
Each number should be on a new line and rounded to the second decimal place.
### Sample Input and Output
| Input | Output |
| ---------------------- | ------------ |
| 20<br>5<br>4<br>1<br>2 | 19.9<br>3.98 |
**Explanation of the example:**
- **Total area** = 20 \* 20 = 400.
- **Area of the bench** = 1 \* 2 = 2.
- **Area for covering** = 400 2 = 398.
- **Area of tiles** = 5 \* 4 = 20.
- **Needed tiles** = 398 \/ 20 = 19.9.
- **Needed time** = 19.9 \* 0.2 = 3.98.
| Input | Output |
| -------------------------- | ------------------------------------ |
| 40<br>0.8<br>0.6<br>3<br>5 | 3302.08333333333<br>660.416666666667 |
### Hints and Guidelines
Let's make a draft to clarify the task requirements. It can look the following way:
![](/assets/chapter-2-2-images/03.Change-tiles-01.png)
#### Idea for Solution
It is required to calculate the **number of tiles** that have to be placed, as well as the **time for placing them**. To **find that number**, we have to calculate **the area that needs to be covered** and **divide it by the area per tile**. By the requirements of the problem, the ground is square, therefore, we find the total area by multiplying its side by its value **`N * N`**. After that, we calculate **the area that the bench takes up** by multiplying its two sides as well **`M * O`**. After subtracting the area of the bench from the area of the whole ground, we obtain the area that needs to be repaired.
We calculate the area of a single tile by **multiplying its two sides with one another** **`W * L`**. As we already stated, now we have to **divide the area for covering by the area of a single tile**. This way, we find the number of necessary tiles. We multiply it by **0.2** (the time needed for changing a tile). Now, we have the wanted output.
#### Choosing Data Types
The length of the side of the ground, the width and the length of the bench will be given as **integers**, therefore, to store their values, we can use the system function **`int(…)`**. We will be given floating-point numbers for the width and the length of the tiles and this is why we will use **`float(…)`**.
#### Solution
As in the previous tasks, we can divide the solution into three smaller tasks:
- **Reading the input**.
- **Doing the calculations**.
- **Printing the output** on the console.
The first thing we have to do is go through **the input** of the task. It is important to pay attention to the sequence they are given in. With **`input(…)`** we read values from the console and with **`int(…)`** and **`float(…)`**, we convert the particular string value into **`int`** or **`float`**:
![](/assets/chapter-2-2-images/03.Change-tiles-02.png)
After we have initialized the variables and have stored the corresponding values in them, we move to the **calculations**. The code below is blurred on purpose, so the reader can think by himself over it:
![](/assets/chapter-2-2-images/03.Change-tiles-03.png)
**We calculate the values** that we have to print on the console. **The number** of necessary **tiles** is obtained by **dividing the area** that needs to be covered **by the area of a tile**:
![](/assets/chapter-2-2-images/03.Change-tiles-04.png)
In the task is specified that the number of the output should be rounded **to the second decimal place**. That is why we cannot just print the value with **`print(…)`**. We will use the method **`round(…)`**, which is rounding to the closest integer number with exactly n-numbers after the decimal place. For example, the number 1.35 will be rounded to 1, and 1.65 - to 2:
![](/assets/chapter-2-2-images/03.Change-tiles-05.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#2](https://judge.softuni.org/Contests/Practice/Index/1048#2).
## Problem: Money
Some time ago, **Pesho bought Bitcoins**. Now, he is going on vacation in Europe **and he needs euros**. Apart from Bitcoins, he has **Chinese yuans** as well. Pesho wants to **exchange his money for euros** for the tour. Write a program that **calculates how much euro he can buy, depending on the following exchange rates**:
- **1 Bitcoin = 1168 BGN.**
- **1 Chinese yuan (CNY) = 0.15 USD.**
- **1 USD = 1.76 BGN.**
- **1 EUR = 1.95 BGN.**
The exchange office has a **commission fee of 0% to 5% from the final sum in euro**.
### Input Data
Three numbers are read from the console:
- On the first line **number of Bitcoins**. Integer within the range of [**0 … 20**].
- On the second line **number of Chinese yuans**. Floating point number within the range of [**0.00 … 50 000.00**].
- On the third line **commission fee**. Floating point number within the range of [**0.00 … 5.00**].
### Output Data
Print one number on the console **the result of the exchange of currencies**. The output should be rounded **to the second decimal place**.
### Sample Input and Output
| Input | Output |
| ----------- | ------ |
| 1<br>5<br>5 | 569.67 |
**Explanation**:
- 1 Bitcoin = 1168 BGN
- 5 Chinese yuan (CNY) = 0.75 USD
- 0.75 USD = 1.32 BGN
- **1168 + 1.32 = 1169.32 BGN = 599.651282051282 EUR**
- **Commission fee:** 5% of 599.651282051282 = **29.9825641025641**
- **Result**: 599.651282051282 - 29.9825641025641 = 569.668717948718 = **569.67 EUR**
| Input | Output | Input | Output |
| ----------------- | -------- | ------------------ | -------- |
| 20<br>5678<br>2.4 | 12442.24 | 7<br>50200.12<br>3 | 10659.47 |
### Hints and Guidelines
Let's first think of the way we can solve the task, before having started to write code.
#### Idea for Solution
We see that the **number of bitcoins** and **the number of Chinese yuans** will be given in the input. The **output** should be in euros. The exchange rates that we have to work with are specified in the task. We notice that we can only exchange the sum in BGN to EUR, therefore, we **first have to calculate the whole sum** that Pesho has in BGN, and then **calculate the output**.
As we have information for the exchange rate of Bitcoins to BGN, we can directly exchange them. On the other hand, to get the value of **Chinese yuans in BGN**, first, we have to **exchange them in USD**, and then the **USD to BGN**. Finally, we will **sum the two values** and calculate how much euro that is.
Only the final step is left: **calculating the commission fee** and subtracting the new sum from the total one. We will obtain a **floating-point number** for the commission fee, which will be a particular **percent of the total sum**. Let's divide it by 100, to calculate its **percentage value**. Then we will multiply it by the sum in euro and divide the result from the same sum. Print the final sum on the console.
#### Choosing Data Types
**Bitcoins** are given as **an integer**, therefore, we can declare a variable using the **`int(…)`** function. For **Chinese yuan and commission fee**, we obtain **a floating-point number**, therefore, we are going to use **`float(…)`**.
#### Solution
After we have built an idea on how to solve the task and we have chosen the data structures that we are going to use, it is time to get to **writing the code**. As in the previous tasks, we can divide the solution into three smaller tasks:
- **Reading input from the console**.
- **Doing the calculations**.
- **Printing the output** on the console.
**We declare the variables** that we are going to use and again we have to choose **meaningful names**, which are going to give us hints about the values they store. We initialize their values: we create variables, where we will store the string arguments passed to the function and convert them to int or double:
![](/assets/chapter-2-2-images/04.Money-01.png)
Then we do the necessary calculations:
![](/assets/chapter-2-2-images/04.Money-02.png)
Finally, we **calculate the commission fee** and **subtract it from the sum in euro**. Let's pay attention to the way we could write this: **`euro -= commission * euro`** is the short way to write **`euro = euro - (commission * euro)`**. In this case, we use a **combined assignment operator** (**`-=`**) that **subtracts the value of the operand to the right from the one to the left**. The operator for multiplication (**`*`**) has a **higher priority** than the combined operator, this is why the expression **`commission * euro`** is performed first and then its value is divided.
Finally, we have to print the result in the console. We should notice that we have to format the output **to the second decimal place**. The difference between this and the previous task is that here, even if the number is an integer, **we have to print it to the second decimal place** (for example **`5.00`**). One way to do so is to use the function **`print(…)`** and to format a string using a placeholder(**`%.2f`**). By using it, we can covert a number into a string, saving the specified numbers after the decimal point:
![](/assets/chapter-2-2-images/04.Money-03.png)
Let's pay attention to something that applies to all other problems of this type: written like that, the solution of the task is pretty detailed. As the task itself is not too complex, in theory, we could write one big expression, where right after having taken the input, we calculate the output. For example, such an expression would look like this:
![](assets/chapter-2-2-images/04.Money-04.png)
This code would print a correct result, **but it is hard to read**. It won't be easy to find out how it works and whether it contains any mistakes, as well as finding such and correcting them. **Instead of one complex expression**, it is **better to write a few simpler ones** and store their values in variables with appropriate names. This way, the code is cleaner and easily maintainable.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#3](https://judge.softuni.org/Contests/Practice/Index/1048#3).
## Problem: Daily Earnings
Ivan is a programmer in an American company, and he **works** at home **approximately N days per month** by earning **approximately M USD per day**. At the end of the year, Ivan **gets a bonus**, which **equals 2.5 of his monthly salary**. In addition, **25% of his annual salary goes for taxes**. Write a program that **calculates what is the amount of Ivan's net average earnings** in BGN per day, as he spends them in Bulgaria. It is accepted that one year has exactly 365 days. The exchange rate of US USD to BGN will **be passed to a function**.
### Input Data
**Three numbers** are read from the console.
- On the first line **workdays per month**. An integer within the range of [**5 … 30**].
- On the second line **daily earnings**. A floating-point number within the range of [**10.00 … 2000.00**].
- On the third line **exchange rate of USD to BGN** /1 dollar = X BGN/. A floating-point number within the range of [**0.99 … 1.99**].
### Output Data
Print one number on the console **the average daily earnings in BGN**. The result will be **rounded up to the second digit after the decimal point**.
### Sample Input and Output
| Input | Output |
| ------------------- | ------ |
| 21<br>75.00<br>1.59 | 74.61 |
**Explanation**:
- **One monthly salary** = 21 \* 75 = 1575 USD.
- **Annual income** = 1575 \* 12 + 1575 \* 2.5 = 22837.5 USD.
- **Taxes** = 25% of 22837.5 = 5709.375 USD.
- **Net annual income in USD** = 17128.125 USD = 27233.71875 BGN.
- **Average earnings per day** = 27233.71875 / 365 = 74.61 BGN.
| Input | Output | Input | Output |
| ----------------- | ------ | -------------------- | ------ |
| 15<br>105<br>1.71 | 80.24 | 22<br>199.99<br>1.50 | 196.63 |
### Hints and Guidelines
Firstly, we have to analyze the task and think of a way to solve it. Then, we will choose data types and, finally, we will write the code.
#### Idea for Solution
Let's first calculate **how much the monthly salary** of Ivan is. We do that by **multiplying the working days per month by his daily earnings**. We **multiply the result** by 12, to calculate his salary for 12 months, and then, we multiply it **by 2.5**, so that we can calculate the bonus. After having summed up the two values, we calculate **his annual income**. Then, we will reduce **the annual income by 25% taxes**. We can do that by multiplying the total income by **0.25** and subtracting the result out of it. Depending on the exchange rate, **we exchange the USD to BGN** and after that, we divide the result by 365.
#### Choosing Data Types
**The working days** per month are given as **an integer**, therefore, we can convert the string into an int with the function **`int(…)`**. For both **the earned money** and **the exchange rate of USD to EUR**, we will obtain **a floating-point number**, therefore, we will use the function **`float(…)`**.
#### Solution
Again: after we have an idea of how to solve the problem and we have considered the data types that we are going to use, we can start **writing the program**. As in the previous tasks, we can divide the solution into three smaller tasks:
- **Reading the input**.
- **Doing the calculations**.
- **Printing the output** on the console.
Then we **declare the variables** that we are going to use by trying to choose **meaningful names**. We create a variable to store the arguments passed to the function, by converting the string to integer or floating number by using **`int(…)/float(…)`**:
![](/assets/chapter-2-2-images/05.Daily-earnings-01.png)
After that we do the calculations:
![](/assets/chapter-2-2-images/05.Daily-earnings-02.png)
We could write an expression that calculates the annual income without brackets as well. As multiplication is an operation that has a higher priority over addition, it will be performed first. Despite that, **writing brackets is recommended when using more operators**, as this way the code is **easily readable** and chances of making a mistake are smaller.
Finally, we have to print the result on the console. We notice **that the number has to be rounded up to the second digit after the decimal point**. To do that, we can use the same placeholder, just like the previous task:
![](/assets/chapter-2-2-images/05.Daily-earnings-03.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#4](https://judge.softuni.org/Contests/Practice/Index/1048#4).

View File

@@ -0,0 +1,884 @@
# Chapter 2.1. Simple Calculations
In this chapter, we are going to become familiar with the following concepts and programming techniques:
- How to work with **data types and variables**, which are necessary when processing numbers and strings.
- How to **print** a result on the console.
- How to **read** user input.
- How to do simple **arithmetic operations**: addition, subtraction, multiplication, division, string concatenation.
- How to **round** numbers.
## Calculations in Programming
We know that computers are machines that process data. All **data** is held in the computer memory (RAM) as **variables**. Variables are named areas of the computer memory which hold data of a certain type, for example, a number or text. Each **variable** in Python has a **name** and **value**. Here is how to define a variable, assigning a value to it at the time of declaration:
![](/assets/chapter-2-1-images/00.Declaring-variables-01.png)
After processing, data is still held in variables (i.e. somewhere in the computer memory, allocated by our program).
## Data Types and Variables
In programming, each variable stores a certain **value** of a particular **type**. For example, data types can be: **number**, **letter**, **text** (string), **date**, **color**, **image**, **list** and others. Here are some examples of data types and their values:
- **int** - integer: 1, 2, 3, 4, 5, ...
- **float** - floating-point number: 0.5, 3.14, -1.5, ...
- **str** - text (string) of symbols: 'a', 'Hello', 'Hi', 'Beer', ...
- **datetime** - date: 21-12-2017, 25/07/1995, ...
In **Python**, the data type is defined by the value that is assigned and is not explicitly specified when declaring variables (as opposed to C#, Java and C++).
## Printing Results on The Screen
To print text, numbers, or another result on the screen, we need to call the built-in function **`print()`**. It allows us to print the value of a variable as well as to directly print a string or a number:
```python
print(9) # prints a number
print('Hello!') # prints text
msg = 'Hello, Python!'
print(msg) # prints value of a variable
```
## Reading User Input in Integer Type
To read a user input as an integer, it is necessary to **declare a variable** and use the built-in functions `input (…)` to read a text line from the console and `int (…)` to convert a text value to numerical:
```python
num = int(input())
```
If it weren't for this conversion, for the program **every number** will be just **text** with which **we wouldn't be able to do** arithmetic operations. When using `input(…)` we can include a prompt to the user to tell them what we want them to enter, for example:
```python
size = int(input('Enter the size = '))
```
### Problem: Square Area
Let's take the following program as an example. It reads an integer, multiplies it by itself (i.e. **squares it**) and prints the result of the multiplication. This is how we can calculate the area of a square by using a given length of its side **a**:
```python
a = int(input('a = '))
area = a * a
print('Square area = ', area)
```
Here is how the program would work for a square with a side equal to 3:
![](/assets/chapter-2-1-images/00.Square-area-01.png)
Try to type in an invalid number, for example "**hello**". You will receive an **error** message during the execution of the program (exception). This is normal. We will find out later how we can catch such errors and make the user re-enter a number.
#### How Does The Example Work?
The first line **`a = int(input('a = '))`** prints a message which tells the user to input the side of the square **a**, then it reads a text (string) and converts it into an integer (this is called parsing) utilizing the function **`int(…)`**. The result is assigned to a variable with the name **`a`**.
The next command **`area = a * a`** assigns to a new variable **`area`** the result of the multiplication of **`a`** by **`a`**.
The last line **`print('Square area = ', area)`** prints the given text and next to it, the calculated area of the square, held in the variable **`area`** is concatenated.
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#0](https://judge.softuni.org/Contests/Practice/Index/1047#0).
## Reading a Sequence of Numbers
When we want to read **several numbers from the console**, if they are given **each on a new line**, we read them sequentially like this:
```python
num1 = input()
num2 = input()
num3 = input()
print(num1, num2, num3)
```
If we type in the following input:
```
10
20
30
```
we will receive the following result:
```
10 20 30
```
When we want to read **several numbers from the console** and they are given **together on the same line**, separated by an interval, we can use the following construction:
```python
num1, num2, num3 = map(int, input().split())
print(num1 + num2 + num3)
```
If we type in the following input:
```
100 200 300
```
we will receive the following result:
```
600
```
How does the code mentioned above work? By using `.split(…)` we separate the elements from the given text line by the interval separator. If we type in the input from above, we will receive 3 elements: `'100'`, `'200'`, and `'300'`. After that, utilizing the function `map(int, elements)` we convert the sequence of elements from text to numbers.
## Reading Floating-Point Numbers
To read a user input as a **floating-point number**, we need to **declare a variable**, this time using the function **`float(…)`** which converts the given text value to a fractional number:
```python
num = float(input())
```
### Problem: Inches to Centimeters
Let's write a program that reads a fractional number in inches and converts it to centimeters:
```python
inches = float(input('Inches = '))
centimeters = inches * 2.54
print('Centimeters = ', centimeters)
```
Let's start the program and make sure that when we input a value in inches, we receive the correct result in centimeters:
![](/assets/chapter-2-1-images/02.Inches-to-centimeters-01.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#1](https://judge.softuni.org/Contests/Practice/Index/1047#1).
## Reading a Text from The Console
To read a **text** (string) from the console, again, we have to **declare a new variable** and use the standard **command for reading a text from the console**:
```python
str = input()
```
### Problem: Greeting by Name
Let's write a program that asks the user for their name and salutes them with the text "**Hello, _{name}_!**".
```python
name = input()
print('Hello, ', end='')
print(name, end='!')
```
By default, the built-in function **`print(…)`** prints the result and continues to the next line. This is because **`print(…)`** uses the parameter **`end`**, which by default has a value **`\n`** (new line). To stay on the same line, we can change the value of **`end=''`**.
Here is the result if we call the function with the name "John":
![](/assets/chapter-2-1-images/03.Greeting-by-name-00.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#2](https://judge.softuni.org/Contests/Practice/Index/1047#2).
## Concatenating Text and Numbers
When printing text, numbers and other data, **we can concatenate them** by using templates **`{0}`**, **`{1}`**, **`{2}`**, etc. In programming, these **templates** are called **placeholders**.
In **Python** we use the built-in method **`.format(…)`**, through which we list the variables we want to put in place of the templates (placeholders). Example: we type in **first name** and **last name** of a student as well as their **age** and **hometown** and we print text in the format “You are _{name}_ _{family name}_, a _{age}_-year-old person from _{hometown}_.”. The following is a solution with text templates:
```python
first_name = input()
last_name = input()
age = int(input())
town = input()
print('You are {0} {1}, a {2}-year-old person from {3}.'
.format(first_name, last_name, age, town))
```
Here is the result that we will get after the execution of this example:
![](/assets/chapter-2-1-images/00.Placeholders-01.png)
Note how each variable must be passed in the **order, in which we want it to print**. Essentially, the template (**placeholder**) **accepts all types of variables** and this creates great convenience when printing.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#3](https://judge.softuni.org/Contests/Practice/Index/1047#3).
### More on Printing Formatted Text
It is possible for one number of a **template** to be used several times and it is not required for the templates of the function **`.format(…)`** to be numbered consecutively. Here is an example:
```python
print('{1} + {1} = {0}'.format(1+1, 1))
```
The result is:
```python
1 + 1 = 2
```
## Arithmetic Operations
Let's examine the basic arithmetic operations in programming.
### Summing Numbers: Operator **`+`**
We can sum numbers by using the **`+`** operator:
```python
a = 5
b = 7
sum = a + b # the result is 12
```
### Subtracting Numbers: Operator **`-`**
Subtracting numbers is done with the **`-`** operator:
```python
a = int(input())
b = int(input())
result = a - b
print(result)
```
Here is the result of the execution of this program (with numbers 10 and 3):
![](/assets/chapter-2-1-images/00.Subtracting-01.png)
### Multiplying Numbers: Operator **`*`**
For multiplication of numbers we use the **`*`** operator:
```python
a = 5
b = 7
product = a * b # 35
```
### Dividing Numbers: Operator /
Dividing numbers is done with the **`/`** operator.
**Note:** **Dividing by 0** causes an **error** during execution (runtime exception) - **ZeroDivisionError**.
Here are a few examples with the division operator:
```python
print(10 / 2.5) # Result: 4
print(10 / 4) # Result: 2.5
print(10 / 6) # Result: 1.6666666666666667
print(5 / 0) # Result: ZeroDivisionError: division by zero
print(-5 / 0) # Result: ZeroDivisionError: division by zero
print(0 / 0) # Result: ZeroDivisionError: division by zero
print(2.5 / 0) # Result: ZeroDivisionError: float division by zero
```
### Raising to a Power: Operator \*\*
To **raise to power** in Python the operator `**` is used:
```python
print(2 ** 10) # 1024
print(2 ** 20) # 1048576
print(2 ** 30) # 1073741824
print(2 ** 64) # 18446744073709551616
print(2 ** 128) # 340282366920938463463374607431768211456
print(2.5 ** 1.5) # 3.952847075210474
```
As seen in the example, Python works efficiently with **big integer values**, without special requirements. Here is a bigger example:
```python
print(2 ** 1024)
```
The result is the following **big integer**:
```
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
```
## Concatenating Text and Numbers
Besides for summing numbers, the operator + is also used for joining pieces of text (concatenation of two strings one after another). In programming, joining two pieces of text is called "concatenation". Here is how we can concatenate a text with a number using the + operator:
```python
first_name = 'Maria'
last_name = 'Ivanova'
age = 19
str = first_name + ' ' + last_name + ' @ ' + str(age)
print(str) # Maria Ivanova @ 19
```
In Python, we cannot directly concatenate a number to a given text, so we first parse the number to text utilizing the **`str (…)`** function.
Here is another example:
```python
a = 1.5
b = 2.5
sum = 'The sum is: ' + str(a) + str(b)
print(sum) # The sum is 1.52.5
```
Did you notice something strange? Maybe you expected the numbers **`a`** and **`b`** to be summed? The concatenation works from left to right and the result above is correct. If we want to sum the numbers, we have to use **brackets**, to change the order of execution of the operations:
```python
a = 1.5
b = 2.5
sum = 'The sum is: ' + str(int(a + b))
print(sum) # The sum is: 4
```
### Repeating Text: Operator \*
The operator `*` can be used to **repeat a given text a number of times**:
```py
text = 'hi'
print(3 * text) # hihihi
```
This feature of the operator for multiplication can lead to the following **wrong result** if we don't keep in mind our value type:
```py
count = input() # Enter 20
print(5 * count) # 2020202020, not 100
```
If we want to multiply a number read from the console by 5, we first have to convert it to an integer using the function `int()`:
```py
count = int(input()) # Enter 20
print(5 * count) # 100
```
## Printing Formatted Text in Python
In Python, there are **several ways** to print **formatted text**, i.e. text, combined with numbers, values of variables, and expressions. We have already encountered some of them, but let's look at the issue in more detail.
### Printing with Commas
When printing using `print(…)` we can list multiple values with commas:
```python
width = 5
height = 7
print('width =', width, '; height =', height, '; area =', width * height)
```
The result is the following:
```
width = 5 ; height = 7 ; area = 35
```
As you can see from the example, in such printing every two values of the listed are separated by an **interval**.
### Concatenating Text with The Operator +
We already know how to concatenate text and numbers with the operator `+`. Using `+`, the example above can be written in the following way:
```python
width = 5
height = 7
print('width = ' + str(width) + ' ; height = ' + str(height) + ' ; area = ' + str(width * height))
```
The result is the same as in the last example:
```
width = 5 ; height = 7 ; area = 35
```
Because in Python text cannot be directly concatenated with numbers, they first have to be parsed to text using the function `str(num)`.
### Formatting Strings `%d`, `%s`, `%f`
Printing with templates can be done with **formatting strings** (also used in C and Java). Here is an example:
```python
width = 5
height = 7
text = "area"
print('width = %d ; height = %d ; %s = %d' % (width, height, text, width * height))
```
In the example above we use the operator `%`, which substitutes values in a **text template**, given as a sequence of elements in brackets. The following main **placeholders** are used (formatting strings): `%d` signifies an integer, `%f` signifies a floating-point number, `%s` signifies text. The outcome of the code above is the same as in the last examples:
```
width = 5 ; height = 7 ; area = 35
```
Using a wrong formatting string could result in an error.
When formatting floating-point numbers, we can round them to a specified number of digits after the decimal point, for example with the formatting string `%.2f` we can print a floating-point number rounded to 2 digits after the decimal point:
```python
print('price = %.2f \nVAT = %.3f' % (1.60, 1.60 * 0.2))
```
The result from the code above is the following:
```
price = 1.60
VAT = 0.320
```
In the example above we use the special symbol `\n`, which means „go to the next line“. Analogically, the special symbol `\b` returns the cursor with one position backward (deletes the last printed symbol), respectively the following code:
```python
print('ab\bc')
```
prints the following result:
```
ac
```
### Formatting Using `.format(…)`
We already looked at how we can format text and numbers using `.format(…)` and numbered templates `{0}`, `{1}`, `{2}` etc. Actually, when enumeration is not necessary, we can use just `{}`, to create a **placeholder**. Here is an example of how we can use formatting with `text.format(…)` to print the result from the last example:
```python
width = 5
height = 7
print('width = {} ; height = {} ; area = {}'.format(width, height, width * height))
```
The result is the same again:
```
width = 5 ; height = 7 ; area = 35
```
### Formatting Using F-String
Maybe the easieast, the most intuitive and the shortest way to **format text and numbers** in Python is to use the **f-string syntax**:
```python
width = 5
height = 7
print(f'width = {width} ; height = {height} ; area = {width * height}')
```
Using the **F-String formatting** is very easy: we put a prefix `f` in front of the string and insert values of variables and expressions in curly braces `{expression}` in random positions. In the example above we have three expressions: `{width}`, `{height}` and `{width * height}` which are calculated and are substituted by their text value. We can use text expressions, integer expressions, floating-point expressions, and all other kinds of expressions.
Formatting with **F-String** in Python is **the recommended method** for printing formatted text because it uses the shortest syntax and the code is easily read and understood.
## Numerical Expressions
In programming, we can calculate **numerical expressions**, for example:
```python
expr = (3 + 5) * (4 2) # 16
```
The standard rule for priorities of arithmetic operations is applied: **multiplication and division are always done before addition and subtraction**. In the case of an **expression in brackets, it is calculated first**, but we already know all of that from school math.
### Problem: Concatenate Data
Write a program, that reads a first name, last name, age and city from the console and prints a message of the following kind: **`You are <firstName> <lastName>, a <age>-year-old person from <town>`**.
#### Hints and Guidelines
We add to the existing PyCharm project one more Python file named "concatenate_data". We **write the code** which reads the input from the console:
![](/assets/chapter-2-1-images/04.Concatenate-data-01.png)
**The code**, which prints the message described in the condition of the task, is purposefully blurred and must be added by the reader:
![](/assets/chapter-2-1-images/04.Concatenate-data-02.png)
Next, the solution should be tested locally using [**Ctrl + Shift + F10**] or with right-click - [**Run**] and enter sample input.
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#3](https://judge.softuni.org/Contests/Practice/Index/1047#3).
### Problem: Trapeziod Area
Let's write a program that inputs the lengths of the two bases of a trapezoid and its height (one floating-point number per line) and calculates the area of the trapezoid by the standard math formula:
```python
b1 = float(input())
b2 = float(input())
h = float(input())
area = (b1 + b2) * h / 2
print('Trapezoid area = ' + str(area))
```
Because we want the program to work for both integer and floating-point numbers, we use **`float(…)`**. If we start the program and we input for the sides respectively **`3`**, **`4`** and **`5`**, we will get the following result:
![](/assets/chapter-2-1-images/05.Trapezoid-area-03.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#4](https://judge.softuni.org/Contests/Practice/Index/1047#4).
## Rounding of Numbers
Sometimes when we work with floating-point numbers we need to convert the numbers to the same type of format. This conversion is called **rounding**. **Python** offers several methods for rounding of numbers:
- **`math.ceil(…)`** - **rounding up**, to the next (bigger) integer number:
```python
up = math.ceil(23.45) # up = 24
```
- **`math.floor(…)`** - **rounding down**, to the previous (smaller) integer number:
```python
down = math.floor(45.67) # down = 45
```
- **`round(…)`** - rounding is done following the **basic rule for rounding** - if the decimal part is less than 5, the rounding is down and vice versa, if it is greater than 5 - up:
```python
round(5.439) # 5
round(5.539) # 6
```
- **`round(…, [number of symbols after the decimal point])`** - rounding to **the closest** number with a specified number of symbols after the decimal point:
```python
round(123.456, 2) # 123.46
round(123, 2) # 123.0
round(123.456, 0) # 123.0
round(123.512, 0) # 124.0
```
### Problem: Circle Area and Perimeter
Let's write a program that, when given the **radius r** of a circle, **calculates the area and the perimeter** of the circle.
Formulas:
- Area = π \* r \* r
- Perimeter = 2 \* π \* r
- π ≈ 3.14159265358979323846…
```python
import math
r = float(input('Enter circle radius => r = '))
area = math.pi * r * r
perimeter = 2 * math.pi * r
print('Area = ', area)
print('Perimeter = ', perimeter)
```
Let's try the program with **radius `r = 10`**:
![](/assets/chapter-2-1-images/00.Circle-area-01.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#5](https://judge.softuni.org/Contests/Practice/Index/1047#5).
### Problem: 2D Rectangle Area
A rectangle is given with **coordinates of its two opposite corners**. You have to calculate its **area and perimeter**:
<img alt="rectangleArea" src="/assets/chapter-2-1-images/00.Rectangle-area-01.png" width="250" height="200" />
For this exercise, we have to take into consideration that by subtracting the smaller **`x`** from the bigger **`x`** we can get the long side of the rectangle. Analogically, by subtracting the smaller **`y`** from the bigger **`y`**, we can get the height of the rectangle. Finally, we have to multiply them. Here is an example implementation of the described logic:
```python
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
width = max(x1, x2) - min(x1, x2)
height = max(y1, y2) - min(y1, y2)
area = width * height
perimeter = 2 * (width + height)
print('Area = ', area)
print('Perimeter = ', perimeter)
```
The function **`max(a, b)`** is used to find the bigger value between **`a`** and **`b`** and analogically **`min(a, b)`** - to find the smaller value between the two.
When starting the program with the values from the coordinate system, the following result is given:
![](/assets/chapter-2-1-images/00.Rectangle-area-02.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#6](https://judge.softuni.org/Contests/Practice/Index/1047#6).
## What Have We Learned from This Chapter?
Let's summarize what we have learned in this chapter:
- **Reading text**: **`str = input()`**.
- **Reading an integer**: **`num = int(input())`**.
- **Reading a floating point number**: **`num = float(input())`**.
- **Calculations with numbers** and using the suitable **arithmetic operators** [+, -, \*, /, ()]: **`sum = 5 + 3`**.
- **Printing a text by placeholders** on the console: **`print('{0} + {1} = {2}'.format(3, 5, 3 + 5))`**.
## Problems: Simple Calculations
Let's strengthen the knowledge gained throughout this chapter with a few more exercises.
### Creating a New Project in PyCharm
We have to create a new project in PyCharm (from [**Create New Project**] or [**File**] -> [**New Project**]) to better organize our problems for exercise. The idea of this **project** is for it to contain **one Python file for each problem** of the exercises:
- We start PyCharm.
- We create a new project: [**Create New Project**] (or [**File**] -> [**New Project**]).
![](/assets/chapter-2-1-images/00.New-project-PyCharm-01.png)
### Problem: Triangle Area
Write a program that reads from the console **aside and a height of a triangle** and calculates its area. Use the **formula** for triangle area: **area = a \* h / 2**. Round the result to **2 digits after the decimal point using `round(area, 2)`**.
#### Sample Input and Output
| Input | Output |
| ------------------- | --------------------- |
| 20 <br>30 | Triangle area = 300 |
| 15 <br>35 | Triangle area = 262.5 |
| 7.75 <br>8.45 | Triangle area = 32.74 |
| 1.23456 <br>4.56789 | Triangle area = 2.82 |
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#7](https://judge.softuni.org/Contests/Practice/Index/1047#7).
### Problem: Celsius to Fahrenheit
Write a program that reads **degrees on the Celsius scale** (°C) and converts them to **degrees on the Fahrenheit scale** (°F). Look on the Internet for a proper [formula](https://shorturl.at/irvMR "Search in Google") to do the calculations. Round the result to **2 digits after the decimal point**.
#### Sample Input and Output
| Input | Output |
| ----- | ------ |
| 25 | 77 |
| 0 | 32 |
| -5.5 | 22.1 |
| 32.3 | 90.14 |
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#8](https://judge.softuni.org/Contests/Practice/Index/1047#8).
### Problem: Radians to Degrees
Write a program, that reads **an angle in [radians](https://en.wikipedia.org/wiki/Radian)** (**`rad`**) and converts it to **[degrees](<https://en.wikipedia.org/wiki/Degree_(angle)>)** (**`deg`**). Look for a proper formula on the Internet. The number **π** in Python programs is available through **`math.pi`** but before that, we have to refer to **the math library** using **`import math`**. Round the result to the nearest integer number using the method **`round()`**.
#### Sample Input and Output
| Input | Output |
| ------ | ------ |
| 3.1416 | 180 |
| 6.2832 | 360 |
| 0.7854 | 45 |
| 0.5236 | 30 |
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#9](https://judge.softuni.org/Contests/Practice/Index/1047#9).
### Problem: USD to BGN
Write a program for the **conversion of US dollars** (USD) **to Bulgarian leva** (BGN). **Round** the result to **2 digits** after the decimal point. Use a fixed rate between a **dollar** (USD) and a **lev** (BGN): **1 USD = 1.79549 BGN**.
#### Sample Input and Output
| Input | Output |
| ----- | ---------- |
| 20 | 35.91 BGN |
| 100 | 179.55 BGN |
| 12.5 | 22.44 BGN |
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#10](https://judge.softuni.org/Contests/Practice/Index/1047#10).
### Problem: \* Currency Converter
Write a program for **conversion of money from one currency to another**. It has to support the following currencies: **BGN, USD, EUR, GBP**. Use the following fixed currency rates:
| Exchange Rate | USD | EUR | GBP |
| :-----------: | :-----: | :-----: | :-----: |
| 1 BGN | 1.79549 | 1.95583 | 2.53405 |
**The input** is the **sum for conversion**, **input currency**, and **output currency**. **The output** is one number the converted value of the above currency rates rounded **2 digits** after the decimal point.
#### Sample Input and Output
| Input | Output |
| -------------------- | ---------- |
| 20<br>USD<br>BGN | 35.91 BGN |
| 100<br>BGN<br>EUR | 51.13 EUR |
| 12.35<br>EUR<br>GBP | 9.53 GBP |
| 150.35<br>USD<br>EUR | 138.02 EUR |
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#11](https://judge.softuni.org/Contests/Practice/Index/1047#11).
### Problem: \* 1000 Days After Birth
Write a program that enters **a birth date** in the format **`dd-MM-yyyy`** and calculates the date on which **1000 days** are turned since this birth date and prints it in the same format.
#### Sample Input and Output
| Input | Output |
| ---------- | ---------- |
| 1995-02-25 | 20-11-1997 |
| 2003-11-07 | 02-08-2006 |
| 2002-12-30 | 24-09-2005 |
| 2012-01-01 | 26-09-2014 |
| 1980-06-14 | 10-03-1983 |
#### Hints and Guidelines
- Look for information about the data type **`datetime`** in Python and in particular look at the methods **`strptime(str, format)`**, **`timedelta(days=n)`**. With their help, you can solve the problem without the need to calculate days, months, and leap years.
- **Don't print** anything additional on the console except for the wanted date!
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1047#12](https://judge.softuni.org/Contests/Practice/Index/1047#12).
## Graphical Applications with Numerical Expressions
To exercise working with variables and calculations with operators and numerical expressions, we will make something interesting: we will develop a **desktop application** with a graphical user interface. We will use calculations with floating-point numbers in them.
### Graphical Application: Converter from BGN to EUR
We need to create **a graphical application** (GUI application), that calculates the value in **Euro** (EUR) of monetary amount given in **Bulgarian leva** (BGN). We use a fixed rate BGN / EUR: **1.95583**.
![](/assets/chapter-2-1-images/13.Currency-converter-01.png)
**Note:** This exercise goes beyond the material learned in this book and aims not to teach you how to program GUI applications, but to strengthen your interest in software development. Let's get to work.
We add to the existing PyCharm project one more Python file. We name it "BGN_to_EUR_converter". To create a Graphical Application using Python we will use the standard library [**tkinter**](https://docs.python.org/3/library/tkinter.html#module-tkinter).
![](/assets/chapter-2-1-images/13.Currency-converter-02.png)
First, we create a Graphical **Application**, which represents a rectangle **Frame** for components. At this stage, everything will be done without explanations, as if it is **magic**:
![](/assets/chapter-2-1-images/13.Currency-converter-03.png)
Now we can add the components of our application to the so-called **function** which we will call with the function \***\*init\*\***, or the so-called **constructor**:
![](/assets/chapter-2-1-images/13.Currency-converter-04.png)
We order the following UI components:
- **Label** - will serve for a static display of text
- **Entry** - will input the value for conversion
- **Button** - will convert the given value
- One more **Label** will show the result of the conversion.
Our components are found in the function **`create_widgets()`**. We add text for visualization on the first **Label**, named **`label`**. **`numberEntry`** is **Entry** where the conversion value will be input. **`convertButton`** will **catch** an event and execute **command** (in our task it will call the function **`convert()`** which we will write shortly). **`output`** is our **Label** for displaying a result after we have input a value and we have clicked a button:
![](/assets/chapter-2-1-images/13.Currency-converter-05.png)
After we have initialized our components, we have to visualize them. This is easly done using the built-in method from **tkinter** - **`pack()`**:
![](/assets/chapter-2-1-images/13.Currency-converter-06.png)
It is left to write the **code** (program logic) for conversion from leva to euro. We will do this by using the function **`convert()`**:
```python
def convert(self):
entry = self.numberEntry.get()
value = float(entry)
result = round(value * 1.95583, 2)
self.output.config(
text=str(value) + ' BGN = ' + str(result) + ' EUR',
bg="green", fg="white")
```
On the last line, we input the result of our **Label `output`** and we set the color of the background (**`bg`**) and the color of the text (**`fg`**).
We run the application with [Ctrl + Shift + F10] or with right-click + [Run], and we test if it works correctly.
We will have a problem with this code. What will happen if we input something different than a number?
![](/assets/chapter-2-1-images/13.Currency-converter-07.png)
We can **catch** this error and prompt a user-friendly message in our application. To do this, let's change the code of our program logic:
```python
def convert(self):
entry = self.numberEntry.get()
try:
value = float(entry)
result = round(value * 1.95583, 2)
self.output.config(
text=str(value) + ' BGN = ' + str(result) + ' EUR',
bg="green", fg="white")
except ValueError:
self.output.config(
text="That's not a number!",
bg="red", fg="black")
```
This way we catch the error in a **try block** and when we input something different than a number we will receive a message **That's not a number!**.
![](/assets/chapter-2-1-images/13.Currency-converter-08.png)
Finally, we **run the application** with [**Ctrl + Shift + F10**] or with right-click + [**Run**] and we test if it works correctly.
### Graphical Application: \*\*\* Catch The Button!
Create a fun graphical application **“catch the button”**. Upon moving the mouse cursor onto the button, it moves to a random position. This way it creates the impression that **"the button runs from the mouse and it is hard to catch"**. When the button gets “caught”, a congratulations message is shown.
![](/assets/chapter-2-1-images/14.Catch-the-button-01.png)
We will begin with the same code from our last exercise. Let's change the name of our application to **Catch the Button!** and this time we will set the window size:
![](/assets/chapter-2-1-images/14.Catch-the-button-02.png)
We will have the following components:
- **Button** - the button which we have to **catch**.
- **Label** - the congratulations message.
We create a button containing the **text "Catch me!"** and **command - the function `on_click()`**, which we will define later. We visualize the components by using the method **`pack()`**. Let both components be **on the top (top)**:
![](/assets/chapter-2-1-images/14.Catch-the-button-03.png)
In our examples, we will use the so-called **binding** operation. This represents **catching** of a change and executing a specified function. Using this code we instruct our program to execute the function **`on_enter()`** when the mouse cursor is over the button and to execute the function **`on_leave()`** when the mouse cursor leaves the button:
![](/assets/chapter-2-1-images/14.Catch-the-button-04.png)
To move the button to a random position we use **`random`**:
![](/assets/chapter-2-1-images/14.Catch-the-button-05.png)
Let's implement the three functions which represent the program logic in our application:
- **`on_enter(self, event)`** - we select random **`x`** and **`y`** coordinates which will change every time we move our cursor over the button; we also change the location of the button - in our example it will be **static to the right**, but you can create your logic and change the direction of the button together with the random numbers selected for coordinates.
- **`on_leave(self, event)`** - when the cursor of the mouse is not over the button, our congratulation should not appear; we configure our **label** to **not have text**.
- **`on_click()`** - when we click the button, our **label** will now display text - **You win!**.
![](/assets/chapter-2-1-images/14.Catch-the-button-06.png)
Not everything may run smoothly from the first try. These exercises above go **beyond the material learned** and their purpose is to strengthen your interest and make you search the web and **look for solutions** to the emerging problems.
If you are having problems with the tasks above, feel free to ask questions in the **SoftUni's Reddit Community**: [https://www.reddit.com/r/softuni/](https://www.reddit.com/r/softuni/).