automated terminal push
This commit is contained in:
355
docs/chapter-03/chapter-03-simple-conditions-exam-problems.md
Executable file
355
docs/chapter-03/chapter-03-simple-conditions-exam-problems.md
Executable file
@@ -0,0 +1,355 @@
|
||||
# Chapter 3.2. Simple Conditions – Exam Problems
|
||||
|
||||
In the previous chapter, we went through **the simple conditional statements** in Python, which we can use to execute different actions depending on a given condition. We mentioned what is the **`scope`** of a variable and how to track the execution of our program step by step (the so-called **debugging**). In this chapter, we'll be working with **simple conditions** by going through some Exam Problems. To do this, let's first revise their construction:
|
||||
|
||||
```python
|
||||
if bool expression:
|
||||
# condition body
|
||||
else:
|
||||
# else-construction body
|
||||
```
|
||||
|
||||
**`if` conditions** consist of:
|
||||
* **`if` clause**
|
||||
* bool expression - a variable of bool type (**`bool`**) or bool logical expression (an expression that results in **`true/false`**)
|
||||
* condition body - contains a random block of source code
|
||||
* **`else` clause** and its block of source code (**optional**)
|
||||
|
||||
|
||||
## Exam Problems
|
||||
|
||||
After having revised how to write simple conditions, let's solve a few Exam Problems to practice the **`if-else`** construction.
|
||||
|
||||
|
||||
## Problem: Transport Price
|
||||
|
||||
A student has to travel **n kilometers**. He can choose between **three types of transportation**:
|
||||
* **Taxi**. Starting fee: **0.70** BGN. Day rate: **0.79** BGN/km. Night rate: **0.90** BGN/km.
|
||||
* **Bus**. Day / Night rate: **0.09** BGN/km. Can be used for distances of a minimum of **20** km.
|
||||
* **Train**. Day / Night rate: **0.06** BGN/km. Can be used for distances of a minimum of **100** km.
|
||||
|
||||
Write a program that reads the number of **kilometers n** and **period of the day** (day or night) and calculates **the price for the cheapest transport**.
|
||||
|
||||
### Input Data
|
||||
|
||||
**Two lines** are read from the console:
|
||||
* The first line (arguments) contains a number **n** – number of kilometers – an integer in the range of [**1 … 5000**].
|
||||
* The second line contains the word "**day**" or "**night**" – traveling during the day or the night.
|
||||
|
||||
### Output Data
|
||||
|
||||
Print to the console **the lowest price** for the given number of kilometers.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
| Input | Output | Input | Output |
|
||||
|----------|----------|----------|----------|
|
||||
|5<br>day |4.65 |7<br>night|7 |
|
||||
|
||||
| Input | Output | Input | Output |
|
||||
|----------|----------|----------|----------|
|
||||
|25<br>day |2.25 |180<br>night|10.8 |
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
We will read the input data and, depending on the distance, we will choose the cheapest transport. To do that, we will write a few conditional statements.
|
||||
|
||||
#### Processing The Input Data
|
||||
|
||||
In the task, we are given **information about the input and output data**. Therefore, in the first **two lines** of the solution, we will declare and initialize the two **variables** that are going to store **the values of the input data**. **The first line** contains **an integer** and that is why the declared variable will be converted with the function **`int(…)`**. **The second line** contains **a word**, therefore, the variable will be of **`string`** type:
|
||||
|
||||

|
||||
|
||||
Before starting with the conditional statements, we need to **declare** one more **variable** that stores the value of **the transport price**:
|
||||
|
||||

|
||||
|
||||
#### Checking The Conditions and Calculating
|
||||
|
||||
After having **declared and initialized** the input data and the variable that stores the value of the price, we have to decide which **conditions** of the task have to be **checked first**.
|
||||
|
||||
The task specifies that the rates of two of the vehicles **do not depend** on whether it is **day** or **night**, but the rate of one of the transports (taxi) **depends**. This is why the **first condition** will be whether it is **day or night** so that it is clear which rate the taxi will be **using**. To do that, we **declare one more variable** that stores **the value of the taxi rate**:
|
||||
|
||||

|
||||
|
||||
To calculate **the taxi rate**, we will use a conditional statement of type **`if-else`**:
|
||||
|
||||

|
||||
|
||||
After having done that, now we can start calculating **the transport price** itself. The constraints in the task refer to **the distance** that the student wants to travel. This is why we will use an **`if-elif-else`** statement that will help us find **the price** of the transport, depending on the given kilometers:
|
||||
|
||||

|
||||
|
||||
First, we check whether the kilometers are **less than 20**, as the task specifies that the student can only use **a taxi** for **less than 20 kilometers**. If the condition is **true** (returns **`true`**), the variable that is created to store the value of the transport (**`price`**), will store the corresponding value. This value equals **the starting fee** that we will **sum** with its **rate**, **multiplied** by **the distance** that the student has to travel.
|
||||
|
||||
If the condition of the variable **is not true** (returns **`false`**), the next step of our program is to check whether the kilometers are **less than 100**. We do that because the task specifies that in this range, **a bus** can be used as well. **The price** per kilometer of a bus **is cheaper** than a taxi one. Therefore, if the result of the condition is **true**, we store **a value**, equal to the result of the **multiplication** of **the rate** of the bus by **the distance** to the variable for the transportation **`price`** in the **`elif`** statement body.
|
||||
|
||||
If this condition **does not return `true`** as a result, we have to store **a value**, equal to **the result** of **the multiplication** of **the distance** by the train **rate** to the price variable in the **`else`** body. This is done because the train is **the cheapest** transport for the given distance.
|
||||
|
||||
#### Printing The Output Data
|
||||
|
||||
After we have checked the distance **conditions** and we have **calculated the price of the cheapest transport**, we have to **print it**. The task **does not** specify how to format the result, therefore, we just print **the variable**:
|
||||
|
||||

|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#0](https://judge.softuni.org/Contests/Practice/Index/1050#0).
|
||||
|
||||
|
||||
## Problem: Pipes in Pool
|
||||
|
||||
A pool with **volume V** fills up via **two pipes**. **Each pipe has a certain flow rate** (the liters of water, flowing through a pipe for an hour). A worker starts the pipes simultaneously and goes out for **N hours**. Write a program that finds the state of the pool **the moment the worker comes back**.
|
||||
|
||||
### Input Data
|
||||
|
||||
**Four lines** are read from the console:
|
||||
* The first line contains a number **V – the volume of the pool in liters** – an integer in the range of [**1 … 10000**].
|
||||
* The second line contains a number **P1 – the flow rate of the first pipe per hour** – an integer in the range of [**1 … 5000**].
|
||||
* The third line contains a number **P2 – the flow rate of the second pipe per hour** – an integer in the range of [**1 … 5000**].
|
||||
* The fourth line contains a number **H – the hours that the worker is absent** – a floating-point number in the range of [**1.0 … 24.00**].
|
||||
|
||||
### Output Data
|
||||
|
||||
Print to the console **one of the two possible states**:
|
||||
* To what extent the pool has filled up and how many percents each pipe has contributed with. All percent values must be formatted to an integer (without rounding).
|
||||
* "The pool is **[x]**% full. Pipe 1: **[y]**%. Pipe 2: **[z]**%."
|
||||
* If the pool has overflown – with how many liters it has overflown for the given time – a floating-point number.
|
||||
* "For **[x]** hours the pool overflows with **[y]** liters."
|
||||
|
||||
**Have in mind** that due to **the rounding to an integer**, there is **data loss** and it is normal for **the sum of the percents to be 99%, not 100%**.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
|Input|Output|Input|Output|
|
||||
| ---- | ----- | ---- | ---- |
|
||||
|1000<br>100<br>120<br>3 |The pool is 66% full. Pipe 1: 45%. Pipe 2: 54%. |100<br>100<br>100<br>2.5|For 2.5 hours the pool overflows with 400 liters.|
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
To solve the task, we read the input data, write a few conditional statements, do some calculations and print the result.
|
||||
|
||||
#### Processing The Input Data
|
||||
|
||||
From the task requirements, we note that our program must have **four lines** from which we read **the input data**. The first **three** consist of **integers** and that is why the **variables** that will store their values will be of **`int`** type. We know that the **fourth** line will be a **floating-point number**, therefore, the variable we use will be of **`float`** type:
|
||||
|
||||

|
||||
|
||||
Our next step is to **declare and initialize** a variable in which we are going to calculate how many **liters** the pool has **filled up** for the **time** the worker was **absent**. We do the calculations by **summing** the values of the flow rates of the **two pipes** and **multiplying** them by the **hours** that are given as input data:
|
||||
|
||||

|
||||
|
||||
#### Checking The Conditions and Processing Output Data
|
||||
|
||||
After we have **the value of the quantity** of water that has flown through the **pipes**, the next step is to **compare** that quantity with the volume of the pool itself.
|
||||
|
||||
We do that with a simple **`if-else`** statement, where the condition will be whether **the quantity of water is less than the volume of the pool**. If the statement returns **`true`**, we have to print one **line** that contains **the ratio** between the quantity of **water that has flown through the pipes** and **the volume of the pool**, as well as the **ratio of the quantity of the water** from **each pipe** to the **volume of the pool**.
|
||||
|
||||
The ratio has to be in **percentage**, that is why all the calculations so far will be **multiplied by 100**. The values will be printed using **placeholders**, and as there is a condition for **the result in percentage** to be formatted to **two digits** after **the decimal** point **without rounding**, we will use the method **`math.trunc(…)`**:
|
||||
|
||||

|
||||
|
||||
However, if **the condition** returns **`false`**, that means that **the quantity of water** is **more** than the **volume** of the pool, therefore, it has **overflown**. Again, the output data has to be on **one line**, but this time it should contain only two values – one of the **hours** when the worker was absent, and the **quantity of water**, which is the difference between the incoming water and the volume of the pool.
|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#1](https://judge.softuni.org/Contests/Practice/Index/1050#1).
|
||||
|
||||
## Problem: Sleepy Tom Cat
|
||||
|
||||
**Tom Cat** likes to sleep all day but, unfortunately, his owner is always playing with him whenever he has free time. To sleep well, **the norm of games** that Tom has is **30 000 minutes per year**. The time for games he has **depends on the holidays that his owner has**:
|
||||
* During **workdays**, his owner plays with him **63 minutes per day**.
|
||||
* During **holidays**, his owner plays with him **127 minutes per day**.
|
||||
|
||||
Write a program that reads **the number of holidays** and prints whether **Tom can sleep well** and how much **the difference from the norm** for the current year is. It is assumed that **there are 365 days in one year**.
|
||||
|
||||
**Example**: 20 holidays -> the working days are 345 (365 - 20 = 345). The time for games is 24 275 minutes (345 \* 63 + 20 \* 127). The difference from the norm is 5 725 minutes (30 000 – 24 275 = 5 725) or 95 hours and 25 minutes.
|
||||
|
||||
### Input Data
|
||||
|
||||
The input is read from the console and consists of an integer – **the number of holidays** in the range of [**0 … 365**].
|
||||
|
||||
### Output Data
|
||||
|
||||
**Two lines** have to be printed to the console:
|
||||
* If Tom's time for games **is above the norm** for the current year:
|
||||
* **On the first line** print: **"Tom will run away"**.
|
||||
* **On the second line** print the difference from the norm in the format: **"{H} hours and {M} minutes more for play"**.
|
||||
* If the time for games of Tom **is below the norm** for the current year:
|
||||
* **On the first line** print: **"Tom sleeps well"**.
|
||||
* **On the second line** print the difference from the norm in the format: **"{H} hours and {M} minutes less for play"**.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
|Input|Output|Input|Output|
|
||||
|----|-----|----|-----|
|
||||
|20|Tom sleeps well<br>95 hours and 25 minutes less for play|113|Tom will run away<br>3 hours and 47 minutes more for play|
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
To solve the problem, we will read the input data. Then, we will write a few conditional statements and do some calculations. Finally, we will print the result.
|
||||
|
||||
#### Processing The Input Data and calculating
|
||||
|
||||
From the task we see that **the input data** will be read only on **the first line** and will be **an integer** in the range of [**0 … 365**]. This is why we will use a variable of **`int`** type:
|
||||
|
||||

|
||||
|
||||
To solve the problem, **first**, we have to calculate **the total minutes** the owner of Tom is playing with him. We see that not only does the sleepy cat has to play with his owner during **the holidays**, but also during **the working days**. **The number** that we read from the console refers to **the holidays**.
|
||||
|
||||
Out next step is to **calculate**, with the help of that number, how many **the working days** of the owner are, as without them we cannot calculate **the total minutes for play**. As the total number of days per year is ***365*** and the number of holidays is **X**, that means that the number of working days is **365 - X***. We store **the difference** in a new variable that only stores this value:
|
||||
|
||||

|
||||
|
||||
Once we have **the number of days for playing**, we can calculate **the time for games** of Tom in minutes. Its **value is equal** to the **result of the multiplication of the working days by 63** minutes (the task specifies that during working days, the time for play is 63 minutes per day), **summed with the result of the multiplication of the holidays by 127** minutes (the task specifies that during holidays, the time for play is 127 minutes per day):
|
||||
|
||||

|
||||
|
||||
In the task condition, we see that we have to **print the difference** between the two values in **hours** and **minutes** as output data. That is why we **subtract** the **total** time for play from the norm of **30 000** minutes and **store** the result in a **new** variable. After that, we **divide** that variable by 60 to get the **hours**, and then, to find out how many the **minutes** are, we use **modular division with the operator `%`**, as again we divide the variable of the difference by 60.
|
||||
|
||||
Here we have to note that if the total **time for the playing** of Tom is **less** than **30,000** when **subtracting** the norm from it, we will obtain **a negative number**. To **neutralize** the number in the division, we use **the function `math.fabs(…)`** when finding the difference:
|
||||
|
||||

|
||||
|
||||
#### Checking The Conditions
|
||||
|
||||
The time for games is already calculated, which leads us to the **next** step – **comparing** the **time for play** of Tom with the **norm** on which the good sleep of the cat depends. To do so, we will use an **`if-else`** conditional statement. In the **`if` clause** we will check whether **the time for play is more than 30 000** (the norm).
|
||||
|
||||
#### Processing The Output Data
|
||||
|
||||
Whatever the result of the conditional statement is, we have to print how much **the difference in hours and minutes** is. We will do that with a **placeholder** and the variables that store the values of the hours and the minutes, as the formatting will be according to the task requirements for output:
|
||||
|
||||

|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#2](https://judge.softuni.org/Contests/Practice/Index/1050#2).
|
||||
|
||||
|
||||
|
||||
## Problem: Harvest
|
||||
|
||||
In a vineyard with an area of X square meters, **40% of the harvest goes for wine production**. **Y kilograms of grapes** are extracted from a **1 square meter vineyard**. **2,5 kg of grapes** is needed for **1 liter of wine**. The wanted quantity of wine for sale is **Z liters**.
|
||||
|
||||
Write a program that **calculates how much wine can be produced** and whether that quantity is enough. **If it is enough, the rest is divided between the vineyard workers equally**.
|
||||
|
||||
### Input Data
|
||||
|
||||
The input data is read from the console and consists of **exactly 4 lines**:
|
||||
* First line: **X $$m^2$$ – the vineyard size** – an integer in the range of [**10 … 5000**].
|
||||
* Second line: **Y grapes for one $$m^2$$** – an integer in the range of [**0.00 … 10.00**].
|
||||
* Third line: **Z needed liters of wine** – an integer in the range of [**10 … 600**].
|
||||
* Fourth line: **number of workers** – an integer in the range of [**1 … 20**].
|
||||
|
||||
### Output Data
|
||||
|
||||
The following has to be printed to the console:
|
||||
* If the **produced** wine is **less than the needed quantity**:
|
||||
* **"It will be a tough winter! More {insufficient wine}} liters wine needed."**
|
||||
</br> \* **The result** has to be **rounded down to the nearest integer**.
|
||||
* If **the produced** wine is **more than the needed quantity**:
|
||||
* **"Good harvest this year! Total wine: {total wine} liters."**
|
||||
\* **The result** has to be **rounded down to the nearest integer**.
|
||||
* **"{Wine left} liters left -> {wine for one worker} liters per person."**
|
||||
\* **Both of the results** have to be **rounded up to the higher integer**.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
|Input|Output|Input|Output|
|
||||
|----|-----|----|-----|
|
||||
|650<br>2<br>175<br>3|Good harvest this year! Total wine: 208 liters.<br>33 liters left -> 11 liters per person.|1020<br>1.5<br>425<br>4|It will be a tough winter! More 180 liters wine needed.|
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
To solve the problem, we will read the input data. Then, we will write a few conditional statements and do some calculations. Finally, we will print the result.
|
||||
|
||||
#### Processing The Input Data and performing the calculations
|
||||
|
||||
First, we have to **check** what **the input data** will be so that we can choose what **variables** we will use. The code below is blurred on purpose and it should be written by the reader:
|
||||
|
||||

|
||||
|
||||
To solve the task, based on the input data, we have to **calculate** how many **liters of wine** will be produced. From the task requirements, we see that to **calculate** the quantity of **wine in liters**, we first, have to find **the number of grapes in kilograms**, which we will get from the harvest. For that, we will declare a variable that keeps a **value**, equal to **40%** of the result from the **multiplication** of the vineyard area by the number of grapes, which is extracted from 1 $$m^2$$.
|
||||
|
||||
After having done these calculations, we are ready to **calculate the quantity of wine in liters** that will be produced from the harvest as well. For that, we declare one more variable that stores that **quantity**. To calculate, we have to **divide the number of grapes in kg by 2.5**:
|
||||
|
||||

|
||||
|
||||
#### Checking The Conditions and Processing Output Data
|
||||
|
||||
After having done the necessary calculations, the next step is to **check** whether the liters of wine that have been produced **are enough**. For that, we will use **a simple conditional statement** of the **`if-else`** type and we will check whether the liters of wine from the harvest are **more than** or **equal to** the **needed liters**.
|
||||
|
||||
If the condition returns **`true`**, from the task requirement we see that **on the first line** we have to print **the wine that has been produced from the harvest**. That value has to be **rounded down to the nearest integer**, which we will do by using both the method **`math.floor(…)`** and a **placeholder** when printing it.
|
||||
|
||||
On the second line, we have to print the results by **rounding them up to the higher integer**, which we will do by using the method **`math.ceil(…)`**. The values that we have to print are **the quantity of wine left** and **the quantity that each worker gets**. The wine left is equal to **the difference** between the produced liters of wine and the needed liters of wine.
|
||||
We calculate the value of that quantity in a new variable, which we declare and initialize in the **`if` condition body**, before printing the first line. We calculate the quantity of wine that **each worker gets** by dividing the wine left by the number of workers:
|
||||
|
||||

|
||||
|
||||
If the condition returns **`false`**, we have to **print the difference** between **the needed liters** and the **liters of wine produced from the harvest**. There is a specification that the result has to be **rounded down to the nearest integer**, which we will do by using the method **`math.floor(…)`**:
|
||||
|
||||

|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#3](https://judge.softuni.org/Contests/Practice/Index/1050#3).
|
||||
|
||||
|
||||
## Problem: Firm
|
||||
|
||||
A firm gets a request for creating a project for which a certain number of hours are needed. The firm has **a certain number of days**. During 10% of the days, the workers are **being trained** and cannot work on the project. A normal **working day is 8 hours long**. The project is important for the firm and every worker must work on it with **overtime of 2 hours per day**.
|
||||
|
||||
**The hours** must be **rounded down to the nearest integer** (for example, **6.98 hours** are rounded to **6 hours**).
|
||||
|
||||
Write a program that calculates whether **the firm can finish the project on time** and **how many hours more are needed or left**.
|
||||
|
||||
### Input Data
|
||||
|
||||
The input data is read from **the console** and contains **exactly three lines**:
|
||||
* On **the first** line are **the needed hours** – **an integer in the range of** [**0 … 200 000**].
|
||||
* On **the second** line are **the days that the firm has** – **an integer in the range of** [**0 … 20 000**].
|
||||
* On **the third** line are **the number of all workers** – **an integer in the range of** [**0 … 200**].
|
||||
|
||||
### Output Data
|
||||
|
||||
**Print one line** to the console:
|
||||
* If **the time is enough**:
|
||||
* **"Yes!{the hours left} hours left."**
|
||||
* If **the time is NOT enough**:
|
||||
* **"Not enough time!{additional hours} hours needed."**
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
|Input|Output|Input|Output|
|
||||
|----|-----|----|-----|
|
||||
|90<br>7<br>3<br>|Yes!99 hours left.|99<br>3<br>1|Not enough time!72 hours needed.|
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
To solve the problem, we will read the input data. Then, we will write a few conditional statements and do some calculations. Finally, we will print the result.
|
||||
|
||||
#### Processing The Input Data
|
||||
|
||||
**First**, we have to read the input data to solve the problem. The code below is blurred on purpose and it should be written by the reader:
|
||||
|
||||

|
||||
|
||||
#### Auxiliary Calculations
|
||||
|
||||
The next step is to calculate **the number of total working hours** by multiplying the working days by 8 (every working day is 8 hours long) with the number of workers and then sum them with the overtime. **The working days** equal **90% of the days** that the firm has. **The overtime** equals the result of the multiplication of the number of workers by 2 (the possible hours of overtime) and then it is multiplied by the number of days that the firm has. From the task requirements, we see that **the hours** should be **rounded down to the nearest integer**, which we will do with the method **`math.floor(…)`**:
|
||||
|
||||

|
||||
|
||||
#### Checking The Conditions
|
||||
|
||||
After having done the calculations that are needed to find the value of **the working hours**, now we have to check whether these hours are **enough**, **or some hours are left**.
|
||||
|
||||
If **the time is enough**, we print the result that is specified in the task requirements, which in this case is the difference between **the working hours and the hours needed** for finishing the project.
|
||||
|
||||
If **the time is not enough**, we print the additional hours that are needed for finishing the project. They equal the difference between **the hours for the project** and **the total working hours**:
|
||||
|
||||

|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#4](https://judge.softuni.org/Contests/Practice/Index/1050#4).
|
||||
508
docs/chapter-03/chapter-03-simple-conditions.md
Executable file
508
docs/chapter-03/chapter-03-simple-conditions.md
Executable file
@@ -0,0 +1,508 @@
|
||||
# Chapter 3.1. Simple Conditions
|
||||
|
||||
In the current chapter, we're going to be taking a look at the **conditional constructs in the Python programming language**. By implementing these constructs, our program can produce a different output based on a given specific input. We will explain the syntax of the conditional operators (**`if`**, **`if-elif`** and **`else`**) by implementing appropriate examples and also we are going to take a look at the range in which a variable lives (its **scope**). Finally, we will go over different **debugging** techniques, to follow the programming steps through which our program goes during its run.
|
||||
|
||||
## Number Comparison
|
||||
|
||||
In programming, we can compare values through the use of the following **operators**:
|
||||
|
||||
* Operator **`<`** (less than)
|
||||
* Operator **`>`** (greater than)
|
||||
* Operator **`<=`** (less than or equals)
|
||||
* Operator **`>=`** (greater than or equals)
|
||||
* Operator **`==`** (equals)
|
||||
* Operator **`!=`** (not equal; different than)
|
||||
|
||||
The result from a comparison is the so-called Boolean value – **`True`** or **`False`**, depending on the evaluated result being either true or false.
|
||||
|
||||
### Problems of Number Comparisons
|
||||
|
||||

|
||||
|
||||
Note that when printing **`true`** and **`false`** values in **Python**, they are capitalized, **`True`** and **`False`**, respectively.
|
||||
|
||||
### Comparison Operators
|
||||
|
||||
In Python, we can use the following operators to compare data:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Operator</th> <th>Notation</th> <th>Applicable for</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Equals</td><td align="center"> == </td><td rowspan="2"> numbers, strings, dates</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Not equal</td><td align="center"> != </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Greater than</td><td align="center"> > </td><td rowspan="4">numbers, dates, other comparable data types</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Greater than or equal</td><td align="center"> >= </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Less than</td><td align="center"> < </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Less than or equal</td><td align="center"> <= </td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
Here is an example:
|
||||
|
||||

|
||||
|
||||
## Simple If Comparisons
|
||||
|
||||
In programming, we often **check particular conditions** and perform various actions depending on the result of the comparison. This is done through **`if`** clauses, which have the following structure:
|
||||
|
||||
```python
|
||||
if condition:
|
||||
# body of the conditional construct
|
||||
```
|
||||
|
||||
### Problem: Excellent Result
|
||||
|
||||
We take the grade as an input in the console and check if it is excellent (**`≥ 5.50`**).
|
||||
|
||||

|
||||
|
||||
Test the example code locally. Try entering different grades, for example, **4.75**, **5.49**, **5.50** and **6.00**. For grades **less than 5.50** the program will not give any output, however for grades of **5.50 or greater**, the output will be "**Excellent!**".
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
You can test the solution example here:
|
||||
[https://judge.softuni.org/Contests/Practice/Index/1049#0](https://judge.softuni.org/Contests/Practice/Index/1049#0).
|
||||
|
||||
|
||||
## If-Else Conditional Constructs
|
||||
|
||||
The **`if`** conditional can also have an **`else`** option to provide a specific action to be performed in case the Boolean expression (which is specified at the beginning **`if Boolean expression`**) returns a negative result (**`False`**). Written in this way, the **conditional statement** is called **`if-else`** and its behavior is as follows: if the result of the condition is **positive** (**`True`**) - a set of instructions is executed. By contrast, when the result is **negative** (**`False`**) - a different set is executed. The format of this structure is as shown:
|
||||
|
||||
```python
|
||||
if condition:
|
||||
# Condition body to be executed if a condition is true
|
||||
else:
|
||||
# else structure body to be executed if a condition is false
|
||||
```
|
||||
|
||||
### Problem: Excellent or Not
|
||||
|
||||
Similarly to the example above, we input a grade and check if it is excellent, but this time we should **output a result in both cases**:
|
||||
|
||||

|
||||
|
||||
#### Testing in Judge System
|
||||
|
||||
You can test your solution at the following link: [https://judge.softuni.org/Contests/Practice/Index/1049#1](https://judge.softuni.org/Contests/Practice/Index/1049#1).
|
||||
|
||||
|
||||
## About Blocks of Code
|
||||
|
||||
By pressing the **tab key** we create a block of code through which a group of commands can be executed. When we have code in **if, elif, else** (and other structures) and we want to perform a series of operations, we put them in a block after the condition.
|
||||
|
||||
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
|
||||
<td>It is a good practice <strong>to use a tab (or four spaces)</strong> since this makes the code more readable, neater and cleaner. In this way, we avoid errors during code execution.</td>
|
||||
</tr></table>
|
||||
|
||||
Here is an example of bad indentation:
|
||||
|
||||

|
||||
|
||||
The above code will either give an error because it is incorrectly formatted, or its execution will display the wrong result on the console:
|
||||
|
||||

|
||||
|
||||
With correct indentation:
|
||||
|
||||

|
||||
|
||||
The following output will be printed on the console:
|
||||
|
||||

|
||||
|
||||
### Problem: Even or Odd
|
||||
|
||||
Write a program that checks whether a given integer number is **even** or **odd**.
|
||||
|
||||
The problem can be solved with a single **`if-else`** structure and the operator **`%`**, which returns the **division remainder** of two numbers:
|
||||
|
||||

|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#2](https://judge.softuni.org/Contests/Practice/Index/1049#2).
|
||||
|
||||
|
||||
### Problem: Greater Number
|
||||
|
||||
Write a program that reads two integers and outputs the number of higher value between the two.
|
||||
|
||||
Our first task is to **read** the two numbers. After which through the use of a simple **`if-else`** structure, in combination with the **greater than operator** (**`>`**), to perform the comparison. We have deliberately blurred parts of the code so that the reader can implement the learned so far.
|
||||
|
||||

|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#3](https://judge.softuni.org/Contests/Practice/Index/1049#3).
|
||||
|
||||
|
||||
## The Lifetime of a Variable
|
||||
|
||||
Every variable has a scope in which it exists, called **variable scope**. This scope specifies where the variable can be used and accessed. In Python, **variables could be used anywhere if they are initialized at least once.**
|
||||
|
||||
In the example below, on the last line, we try to print the variable **`my_name`**, which is defined in the **`else` structure**. We will get an **error**, because in this case the body of the **`else`** clause, in which we initialize the variable, is not executed. However, there is no problem printing the variable **`can_drive`** because the program entered the body of the **`if`** clause and initialized the variable. As you can see the variables **`can_drive`** and **`my_name`** are colored yellow. This is a warning from **PyCharm**, that we may get an error. Therefore, we should be careful where we initialize the variables.
|
||||
|
||||

|
||||
|
||||
## Conditional Chaining
|
||||
|
||||
Sometimes we have to do a series of checks, before deciding what actions our program will execute. In such cases we can apply the structure **`if-elif ... else` in series**. For this purpose, we employ the following structure:
|
||||
|
||||
```python
|
||||
if condition:
|
||||
# condition body;
|
||||
elif condition2:
|
||||
# condition body;
|
||||
elif condition3:
|
||||
# condition body;
|
||||
…
|
||||
else:
|
||||
# else structure body
|
||||
```
|
||||
|
||||
### Problem: Number 0...9 to Text
|
||||
|
||||
Print the digits one through nine in English on the console (the numbers are read from the console). We can take the digit and through a **series of conditions** print the corresponding English word on the console:
|
||||
|
||||
```python
|
||||
number = int(input())
|
||||
|
||||
if number == 1:
|
||||
print("one")
|
||||
elif num == 2:
|
||||
print("two")
|
||||
elif …:
|
||||
…
|
||||
elif num == 9:
|
||||
print("nine")
|
||||
else:
|
||||
print("number too big")
|
||||
```
|
||||
|
||||
The program logic of the above example **sequentially compares** the input number with the digits from 1 to 9 **with each consecutive comparison being performed only in case the previous result is not true**. Eventually, if none of the **`if`** conditionals are satisfied, the last **`else` clause** is executed.
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#4](https://judge.softuni.org/Contests/Practice/Index/1049#4).
|
||||
|
||||
|
||||
## Problems: Simple Conditions
|
||||
|
||||
To practice the implementation of the conditional constructs **`if`** and **`if-elif`** we will take a look at a few practical problems.
|
||||
|
||||
### Problem: Bonus Score
|
||||
|
||||
We are given an **integer** – several points. Additional **bonus points** are awarded as per the rules described below. Write a program that calculates the **bonus points** for the given number and outputs the **total points** including the bonus.
|
||||
|
||||
- If the number is **up to 100** inclusive, the bonus points are 5.
|
||||
- If the number is **larger than 100**, the bonus points are **20%** of the number.
|
||||
- If the number is **larger than 1000**, the bonus points are **10%** of the number.
|
||||
- Additional points are awarded as below (added separately from the described above):
|
||||
- For **even** numbers -> + 1 p.
|
||||
- For numbers, **ending with 5** -> + 2 p.
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 20 | 6<br>26 |
|
||||
| 175 | 37<br>212 |
|
||||
| 2703 | 270.3<br>2973.3 |
|
||||
| 15875 | 1589.5<br>17464.5 |
|
||||
|
||||
#### Hints and Guidelines
|
||||
|
||||
We can calculate the base and additional bonus score with a series of **`if-elif-else`** statements. For the **main bonus points we have 3 cases** (the input is less than or equal to 100, it is between 100 and 1000, and finally it is greater than 1000), for the **additional bonus score - further 2 cases** (whether the number is even or odd):
|
||||
|
||||

|
||||
|
||||
Here’s what the solution to the problem might look like:
|
||||
|
||||

|
||||
|
||||
Please note that for this problem the Judge system is set up to ignore any non-number outputs, so we may print explanations along with the number output.
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#5](https://judge.softuni.org/Contests/Practice/Index/1049#5).
|
||||
|
||||
|
||||
### Problem: Sum Seconds
|
||||
|
||||
Three athletes finish with some **number of seconds** (between **1** and **50**). Write a program that reads the times of the contestants and calculates their **combined time** in "minutes:seconds" format. Seconds are to be printed with a **leading zero** (2 -> "02", 7 -> "07", 35 -> "35").
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 35<br>45<br>44 | 2:04 |
|
||||
| 22<br>7<br>34 | 1:03 |
|
||||
| 50<br>50<br>49 | 2:29 |
|
||||
| 14<br>12<br>10 | 0:36 |
|
||||
|
||||
#### Hints and Guidelines
|
||||
|
||||
Firstly, we sum the three numbers, to obtain the total seconds. As we know that **1 minute = 60 seconds**, we should calculate the minutes and seconds in the range 0 to 59:
|
||||
- If the result is between 0 and 59, we print 0 minutes + calculated seconds.
|
||||
- If the result is between 60 and 119, we print 1 minute + calculated seconds minus 60.
|
||||
- If the result is between 120 and 179, we print 2 minutes + calculated seconds minus 120.
|
||||
- If the seconds are less than 10, we print the number with a leading zero.
|
||||
|
||||

|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#6](https://judge.softuni.org/Contests/Practice/Index/1049#6).
|
||||
|
||||
|
||||
### Problem: Metric Converter
|
||||
|
||||
Write a program, that **converts distance** between the following **8 units of measure**: **`m`, `mm`, `cm`, `mi`, `in`, `km`, `ft`, `yd`**. You may use the conversion table below:
|
||||
|
||||
| Input measure | Output measure |
|
||||
| :-------------: | :--------------: |
|
||||
| 1 meter (m) | 1000 millimeters (mm) |
|
||||
| 1 meter (m) | 100 centimeters (cm) |
|
||||
| 1 meter (m) | 0.000621371192 miles (mi) |
|
||||
| 1 meter (m) | 39.3700787 inches (in) |
|
||||
| 1 meter (m) | 0.001 kilometers (km) |
|
||||
| 1 meter (m) | 3.2808399 feet (ft) |
|
||||
| 1 meter (m) | 1.0936133 yards (yd) |
|
||||
|
||||
The input will consist of three parameters:
|
||||
|
||||
- First line: A number.
|
||||
- Second: Input unit of measure.
|
||||
- Third: Output unit of measure (for the result).
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 12 <br>km <br>ft | 39370.0788 |
|
||||
| 150 <br>mi <br>in | 9503999.99393599 |
|
||||
| 450 <br>yd <br>km | 0.41147999937455 |
|
||||
|
||||
#### Hints and Guidelines
|
||||
|
||||
We take the input data and to the units of measure, we can add the function **`lower()`**, which will convert all letters to lower case. As we can see from the conversion table above, we have data for **converting only between meters and any other measuring unit**. To make the conversion, firstly we must calculate the input measurement in meters. To this effect, we need to create a set of conditionals to determine the input measuring unit and then the output.
|
||||
|
||||

|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#7](https://judge.softuni.org/Contests/Practice/Index/1049#7).
|
||||
|
||||
|
||||
## Debugging - Simple Operations With a Debugger
|
||||
|
||||
So far, we have written quite a lot of code and oftentimes there have been mistakes, haven't there? Now we can show you a tool to make finding mistakes easier.
|
||||
|
||||
### What is "Debugging"?
|
||||
|
||||
**Debugging** is the process of "**attaching**" to a program's execution, which allows us to follow closely the execution of our program. We can follow **line by line** the events in our program, what its evaluation route is, what the intermediate values of the declared variables at each step of the execution are, among other useful information and thus allowing us to locate errors - the so-called **bugs**:
|
||||
|
||||

|
||||

|
||||
|
||||
### Debugging in PyCharm
|
||||
|
||||
By pressing [**Shift + F9**], we start the program in **Debug mode**. We move on to the **next line** of execution with [**F7**]:
|
||||
|
||||

|
||||
|
||||
With [**Ctrl + F8**] we create **breakpoints**, which we can reach directly using [**Shift + F9**] (when starting the program in **Debug mode**).
|
||||
|
||||
## Problems: Simple Conditions
|
||||
|
||||
Now let's practice the lessons learned in this chapter with a few practical exercises.
|
||||
|
||||
### Empty PyCharm Solution (Project)
|
||||
|
||||
We create empty solution in PyCharm so we can organize the solutions to the tasks from the exercises – each task will be in a separate file and all tasks will be in the same Project.
|
||||
|
||||
We start PyCharm and create a new **Project:** [**File**] -> [**New Project**].
|
||||
|
||||

|
||||
|
||||
Select **Pure Python** from the field on the left and set the project directory, putting the name of your project in place of the **untitled** one:
|
||||
|
||||

|
||||
|
||||
Now we have an empty project (no files in it).
|
||||
|
||||
### Problem: Password Guess
|
||||
|
||||
Write a program that **reads input data from the console - a password** (one line of random text) and checks if the input **matches** the phrase "**s3cr3t!P@ssw0rd**". If it matches, print "**Welcome**", otherwise print "**Wrong password!**".
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| qwerty | Wrong password! |
|
||||
| s3cr3t!P@ssw0rd | Welcome |
|
||||
| s3cr3t!p@ss | Wrong password! |
|
||||
|
||||
#### Hints and Guidelines
|
||||
|
||||
Use an **`if-else`** statement.
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#8](https://judge.softuni.org/Contests/Practice/Index/1049#8).
|
||||
|
||||
|
||||
### Problem: Number 100...200
|
||||
|
||||
Write a program that **reads input data from the console - an integer** and checks if it is **below 100**, **between 100 and 200** or **over 200**. Print the appropriate messages as per the examples below.
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 95 | Less than 100 |
|
||||
| 120 | Between 100 and 200 |
|
||||
| 210 | Greater than 200 |
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#9](https://judge.softuni.org/Contests/Practice/Index/1049#9).
|
||||
|
||||
|
||||
### Problem: Equal Words
|
||||
|
||||
Write a program that **reads input data from the console - two words** and checks if they are the same. A comparison should be case-insensitive and the output should be either "**yes**" or "**no**".
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| Hello<br>Hello | yes |
|
||||
| SoftUni<br>softuni | yes |
|
||||
| Soft<br>Uni | no |
|
||||
| beer<br>vodka | no |
|
||||
| HeLlO<br>hELLo | yes |
|
||||
|
||||
#### Hints and Guidelines
|
||||
|
||||
Before the comparison, both words should be in lower case, so that case (uppercase / lowercase) does not influence the result **`word = word.lower()`**.
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#10](https://judge.softuni.org/Contests/Practice/Index/1049#10).
|
||||
|
||||
|
||||
### Problem: Speed Info
|
||||
|
||||
Write a program, that **reads input data from the console - speed** (decimal number) and prints **speed information**. For speed **up to 10** (inclusive), print "**slow**". For speed **over 10 up to 50**, print "**average**". For speed **over 50 and up to 150**, print "**fast**". For speed **over 150 and up to 1000**, print "**ultra fast**". For any higher speed, print "**extremely fast**".
|
||||
|
||||
#### Sample Input and Output
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 8 | slow |
|
||||
| 49.5 | average |
|
||||
| 126 | fast |
|
||||
| 160 | ultra fast |
|
||||
| 3500 | extremely fast |
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#11](https://judge.softuni.org/Contests/Practice/Index/1049#11).
|
||||
|
||||
|
||||
### Problem: Area of Figures
|
||||
|
||||
Write a program that reads input data from the console - **the measures of a geometric shape** and **calculates its surface area**. There are four types of shapes: **square**, **rectangle**, **circle** and **triangle**.
|
||||
|
||||
The first line of input is the type of shape (**`square`**, **`rectangle`**, **`circle`**, **`triangle`**):
|
||||
* If the shape is a **square**, the next argument will be one number - the length of its side.
|
||||
* If the shape is a **rectangle**, the next argument will be two numbers - the lengths of its sides.
|
||||
* If the shape is a **circle**, the next argument will be one number - the radius of the circle.
|
||||
* If the shape is a **triangle**, the next argument will be two numbers - its base and the corresponding altitude.
|
||||
|
||||
The result should be rounded up to the **third decimal point**.
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| square<br>5 | 25 |
|
||||
| rectangle<br>7<br>2.5 | 17.5 |
|
||||
| circle<br>6 | 113.097 |
|
||||
| triangle<br>4.5<br>20 | 45 |
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#12](https://judge.softuni.org/Contests/Practice/Index/1049#12).
|
||||
|
||||
|
||||
### Problem: Time + 15 Minutes
|
||||
|
||||
Write a program that reads **two integers - hours and minutes** based on a 24-hour day and calculates what time it will be **15 minutes later**. The result should be printed in the following format **`hh:mm`**. Hours should always be between 0 and 23, while minutes should always be between 0 and 59. Hours should be written with one or two digits as needed, while the minutes should always be written with two digits - add a **leading zero**, as needed.
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 1<br>46 | 2:01 |
|
||||
| 0<br>01 | 0:16 |
|
||||
| 23<br>59 | 0:14 |
|
||||
| 11<br>08 | 11:23 |
|
||||
| 12<br>49 | 13:04 |
|
||||
|
||||
#### Hints and Guidelines
|
||||
|
||||
Add 15 minutes and check using a set of conditions. If minutes are over 59 **increase the hours** by 1 and **decrease the minutes** by 60. You may handle the case when hours are over 23 similarly. Take care when printing the minutes to add a **leading zero** where appropriate.
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#13](https://judge.softuni.org/Contests/Practice/Index/1049#13).
|
||||
|
||||
|
||||
### Problem: 3 Equal Numbers
|
||||
|
||||
Write a program that reads **3 numbers** and prints whether they are the same ("**yes**" / "**no**").
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 5<br>5<br>5 | yes |
|
||||
| 5<br>4<br>5 | no |
|
||||
| 1<br>2<br>3 | no |
|
||||
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#14](https://judge.softuni.org/Contests/Practice/Index/1049#14).
|
||||
|
||||
|
||||
### Problem: Number 0...100 to Text
|
||||
|
||||
Write a program that converts numbers in the range of [**0 … 100**] in text.
|
||||
|
||||
#### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
| --- | ---- |
|
||||
| 25 | twenty five |
|
||||
| 42 | forty two |
|
||||
| 6 | six |
|
||||
|
||||
#### Hints and Guidelines
|
||||
|
||||
Firstly, we should check for **single-digit numbers** and if this is the case, print the corresponding word. Then we can check if the number is a **double-digit number**. These can be printed in two parts: left part (**double-digit** = number / 10) and right part (**single-digit** = number % 10). If the number has three digits, then it must be 100 and this can be handled as a special case.
|
||||
#### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1049#15](https://judge.softuni.org/Contests/Practice/Index/1049#15).
|
||||
Reference in New Issue
Block a user