Prévia do material em texto
Sumário
1 Theory: Integer arithmetic 3
1.1 Basic operations 4
1.2 Writing complex expressions 4
1.3 Other operations 4
1.4 Operation priority 5
1.5 PEP time! 5
1.6 Practice 6
1.6.1 Factorial of 3 6
1.6.2 Adding together 6
1.6.3 Division by zero 6
1.6.4 Raise to power 6
1.6.5 Calculate it 7
1.6.6 A simple expression 7
1.6.7 All operations 7
1.6.8 Calculate a remainder 7
1.6.9 An odd operation 7
1.6.10 Let's do some math 7
1.6.11 A complex expression 8
1.6.12 Square root 8
1.6.13 The power 9
1.6.14 Priority order 9
2 Theory : Naming variables 9
2.1 Code style convention 9
2.2 Other variable names best practices 10
2.3 Conclusion 10
2.4 Practice 10
2.4.1 The best name 10
2.4.2 Number of people in the class 10
2.4.3 Good names 11
2.4.4 Zeros and ones 11
2.4.5 Character set 11
2.4.6 The first char 11
2.4.7 Why to name variables? 11
2.4.8 A good style guide 11
2.4.9 This is Python 11
2.4.10 How to name a variable? 12
2.4.11 Everest 12
2.4.12 Fix str 12
3 Theory: Program with numbers 12
3.1 Reading numbers from user input 12
3.2 Free air miles 13
3.3 Advanced forms of assignment 13
3.4 Counter variable 14
3.5 Conclusion 14
3.6 Practice 14
3.6.1 Bad omen 14
3.6.2 Undercover 15
3.6.3 When you'll have a free trip? 15
3.6.4 Calculating an expression 15
3.6.5 The last digit of a number 15
3.6.6 Divide nuts equally between squirrels 16
3.6.7 The first digit of a two-digit number 17
3.6.8 Savings account 17
3.6.9 Good rest on vacation 17
3.6.10 The sum of digits 18
3.6.11 Desks 19
4 Theory: Boolean logic 19
4.1 Boolean type 19
4.2 Boolean operations 20
4.3 The precedence of boolean operations 20
4.4 Truthy and falsy values 20
4.5 Short-circuit evaluation 21
4.6 Practice: 21
4.6.1 Exclusive or 22
5 Theory: Comparisons 23
5.1 Comparison operators 23
5.2 Comparing integers 24
5.3 Comparison chaining 24
5.4 Practice 24
5.4.1 Carry on! 24
5.4.2 Matchmaker 25
5.4.3 Discount 25
5.4.4 Focus on the positive 25
5.4.5 Enrolling 26
5.4.6 True test 27
5.4.7 In the middle 27
5.4.8 Very odd 27
5.4.9 Guessing game 28
5.4.10 Movie theater 29
5.4.11 Order! 30
5.4.12 Operator 31
5.4.13 Program with numbers: The last digit of a number 31
6 Theory: If statement 31
6.1 Simple if statement 32
6.2 Nested if statement 32
STAGE 4
What you'll do in this stage 4/4: Sustainable care <3
Project: Zookeeper
Topics you need to learn in order to complete the current stage:
1. Integer arithmetic
2. Naming variables
3. Program with numbers
4. Boolean logic
5. Comparisons
6. If statement
7. While loop
Use the material from these topics and the skills you’ve learned to successfully complete this stage of
the project.
You will be working on the following in this project stage
Finally, your program is able to work for as long as needed!
Description
Now it's time to make our project user-friendly. In this final stage, you'll make your software ready for the
zoo staff to use. Your program should understand the habitat numbers, show the animals, and be able to
work continuously without having to be restarted.
Objectives
Your tasks at this point:
Your program should repeat the behavior from the previous stage, but now in a loop.
Do not forget to include an exit opportunity: inputting exit should end the program.
When the program is done running, it should print: See you later!
1 Theory: Integer arithmetic
In real life, we often perform arithmetic operations. They help us to calculate the change from a
purchase, determine the area of a room, count the number of people in a line, and so on. The same
operations are used in programs.
https://hyperskill.org/projects/98
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
https://hyperskill.org/projects/98/stages/542/preview
1.1 Basic operations
Python supports basic arithmetic operations:
addition +
subtraction -
multiplication *
division /
integer division //
The examples below show how it works for numbers.
print (10 + 10) # 20
print (100 - 10) # 90
print (10 * 10) # 100
print (77 / 10) # 7.7
print (77 // 10) # 7
There is a difference between division / and integer division //. The first produces a floating-point
number (like 7.7), while the second one produces an integer value (like 7) ignoring the decimal part.
Python raises an error if you try to divide by zero.
ZeroDivisionError: division by zero
1.2 Writing complex expressions
Arithmetic operations can be combined to write more complex expressions:
print (2 + 2 * 2) # 6
The calculation order coincides with the rules of arithmetic operations. Multiplication has a higher
priority level than addition and subtraction, so the operation 2 * 2 is calculated first.
To specify an order of execution, you can use parentheses, as in the following:
print ((2 + 2) * 2) # 8
Like in arithmetic, parentheses can be nested inside each other. You can also use them for clarity.
The minus operator has a unary form that negates the value or expression. A positive number becomes
negative, and a negative number becomes positive.
print (-10) # -10
print (-(100 + 200)) # -300
print (-(-20)) # 20
1.3 Other operations
The remainder of a division. Python modulo operator % is used to get the remainder of a division. It may
come in handy when you want to check if a number is even. Applied to 2, it returns 1 for odd numbers
and 0 for the even ones.
print (7 % 2) # 1, because 7 is an odd number
print (8 % 2) # 0, because 8 is an even number
Here are some more examples:
# Divide the number by itself
print (4 % 4)# 0
# At least one number is a float
print (11 % 6.0) # 5.0
# The first number is less than the divisor
print (55 % 77) # 55
# With negative numbers, it preserves the divisor sign
print (-11 % 5) # 4
print (11 % -5) # -4
Taking the remainder of the division by 0 also leads to ZeroDivisionError.
The behavior of the mod function in Python might seem unexpected at first glance. While 11 % 5 = 1
and -11 % -5 = -1 when both numbers on the left are of the same sign, 11 % -5 = -4 and -11 %
5 = 4 if we have one negative number.
The thing is, in Python, the remainder always has the same sign as the divisor.
In the first case, 11 % -5 = -4, as the remainder should be negative, we need to compare 15 and 11, not
10 and 11: 11 = (-5) * (-3) + (-4).
In the second case, -11 % 5 = 4, the remainder is supposed to be positive: -11 = 5 * (-3) + 4.
Exponentiation . Here is a way to raise a number to a power:
print(10 ** 2) # 100
This operation has a higher priority over multiplication.
1.4 Operation priority
To sum up, there is a list of priorities for all considered operations:
1. parentheses
2. power
3. unary minus
4. multiplication, division, and remainder
5. addition and subtraction
As mentioned above, the unary minus changes the sign of its argument.
Sometimes operations have the same priority:
print(10 / 5 / 2) # 1.0
print(8 / 2 * 5) # 20.0
The expressions above may seem ambiguous to you, since they have alternative solutions depending on
the operation order: either 1.0 or 4.0 in the first example, and either 20.0 or 0.8 in the second one. In
such cases, Python follows a left-to-right operation convention from mathematics. It's a good thing to
know, so try to keep that in mind, too!
1.5 PEP time!
There are a few things to mention about the use of binary operators, that is, operators that influence
both operands. As you know, readability matters in Python. So, first, remember to surround a binary
operator with a single space on both sides:
number=30+12 # No!
number = 30 + 12 # It's better this way
Also, sometimes people use the break after binary operators. But this can hurt readability in two ways:
● the operators are not in one column,
● each operator has moved away from its operand and onto the previous line:
# No: operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
Mathematicians and their publishers follow the opposite convention in order to solve the readability
problem. Donald Knuth explains this in his Computers and Typesetting series: "Although formulas within
a paragraph always break after binary operations and relations, displayed formulas always break before
binary operations". Following this tradition makes the code more readable:
# Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
In Python code, it is permissible to break before or after a binary operator, as long as the convention is
consistent locally. For new code, Knuth's style is suggested, according to PEP 8.
1.6 Practice
1.6.1 Factorial of 3
Write a program that prints the product of these three numbers 1 * 2 * 3.
Solution:
print ( 1 * 2 * 3 )
1.6.2 Adding together
Write a program that takes two integer numbers a and b and prints their sum.
The variables have already been defined.
Sample Input 1: 8 11
Sample Output 1: 19
Solution:
a = int ( input ())
b = int ( input ())
print ( a + b )
1.6.3 Division by zero
What will happen if you divide any number by zero in Python? Select one option from the list:
0
undefined
ZeroDivisionError exception (X)
InvalidOperation exception
1.6.4 Raise to power
It's time for really big numbers! Calculate this 2 179 and print what you got.
Solution:
print ( 2 ** 179 )
1.6.5 Calculate it
Print the result of executing the following expression: multiply 1234567890 by 987654321, then add
67890.
Solution:
print ( 1234567890 * 987654321 + 67890 )
1.6.6 A simple expression
Write a program that takes 3 integer numbers a, b and c, calculates a times b and then subtracts c from
the product. The program should print the result.
There's no need to create the variables, just use them in the code below.
Sample Input 1: 8 11 63
Sample Output 1: 25
Solution:
a = int ( input ())
b = int ( input ())
c = int ( input ())
print ( a * b - c )
1.6.7 All operations
Match each name of a mathematical operation with its corresponding symbol.
remainder of the division %
raising to power **
addition +
subtraction -
multiplication *
division /
integer division //
1.6.8 Calculate a remainder
Write a program that calculates the remainder of 10 divided by 3 and prints the result.
Solution: print ( 10 % 3 )
1.6.9 An odd operation
Which arithmetic operation doesn't have its own operator in Python? Select one option from the list:
Division
Raising to power
Square root (X)
Unary minus
Integer division
The remainder of division
1.6.10 Let's do some math
What is the result of the following Python expression?
print(((3 + 5) // 2 * 2 ** 3) % 7)
Enter a number: (Solution:) 4
1.6.11 A complex expression
Write a program that takes a single integer number n and then performs the following operations in the
following order:
● adds n to itself
● multiplies the result by n
● subtracts n from the result
● exactly divides the result by n (that means, you need to carry out integer division).
Then print the result of the division. The example is given below:8 + 8 = 16
16 * 8 = 128
128 - 8 = 120
120 // 8 = 15
Sample Input: 8
Sample Output: 15
Solution:
n = int(input())
soma = n + n
mult = soma * n
subt = mult - n
divi = subt // n
print(divi)
Outras resoluções:
n = int(input())
result = n + n
result = result * n
result = result - n
result = result // n
print(result)
____
n = int(input())
print(((n + n) * n - n) // n)
n = int(input())
print((((n + n) * n) - n) // n)
n = int(input())
____
def complex_expression(x):
sum_tot = x + x
mult = sum_tot * x
subst = mult - x
return subst // x
result = complex_expression(n)
print(result)
____
1.6.12 Square root
Extracting the square root of a number is equivalent to raising this number to a certain power. What
power are we talking about?
Solution: 0,5
1.6.13 The power
Please, print() the result of the following expression: raise 31 to the power of 331 and then get the
remainder of the result's division by 20.
n = ( 31 ** 331 ) % 20
print ( n )
1.6.14 Priority order
Sort a list from mathematical operations with the highest priority to operations with the lowest priority.
Thus, operations executed in the first turn will be at the top of your list.
01. parentheses ()
02. power **
03. unary minus -
04. multiplication, division, integer division, and remainder * / // %
05. addition and subtraction + -
2 Theory : Naming variables
As you know, every variable has a name that uniquely identifies it among other variables. Giving a good
name to a variable may not be as simple as it seems.
Experienced programmers are careful when naming their variables to ensure that their programs are
easy to understand. It is important because programmers spend a lot of time reading and understanding
code written by other programmers. If variables have bad names, even your own code will seem unclear
to you in a few months. In this topic, we will consider how to choose good names for your variables in
accordance with conventions and best practices established in the Python community.
2.1 Code style convention
PEP 8 provides some rules for variable names to increase code readability.
Use lowercase and underscores to split words. Even if it's an abbreviation.
http_response # yes!
httpresponse # no
myVariable # no, that's from Java
However, if you want to define a constant, it's common to write its name in all capital letters and, again,
separate words with underscores. Normally, constants are stored in special files called modules.
Although we'll cover this later, here is a small example:
SPEED_OF_LIGHT = 299792458
Avoid names of one letter that could be easily mixed up with numbers like 'l' (lowercase letter el), 'O'
(uppercase letter oh), or 'I' (uppercase letter eye).
l = 1 # no
O = 100 # no, if you use this variable name further in your code, it
may look like a zero
Although you can use any Unicode symbols, the code style convention recommends limiting variable
names with ASCII characters.
# Using Cyrillic instead of Latin can cause an evening of useless
headache
# These are different variables!
copy = "I'm written in Latin alphabet" # yes!
сору = "And I'm written in Cyrillic!" # no
If the most suitable variable name is some Python keyword, add an underscore to the end of it.
class_ = type(var) # yes!
https://en.wikipedia.org/wiki/List_of_Unicode_characters
http://www.asciitable.com/
klass = type(var) # no
All the code style rules regarding names are described in PEP 8 .
2.2 Other variable names best practices
There are also some best practices that are common for many programming languages.
Choose a name that makes sense. The variable name must be readable and descriptive and should
explain to the reader what sort of values will be stored in it.
score # yes!
s # no
count # yes!
n # no
Don't use too generic names. Try to choose a name that will explain the meaning of the variable. But
don't make it too wordy. 1-3 words are usually enough.
http_response # yes!
var1 # no
http_response_from_the_server # no, some words can be dropped
If a word is long, try to find the most common and expected short form to make it easier to guess later.
output_file_path # yes!
fpath # no
output_flpth # no
Avoid names from the built-in types list.
str = 'Hello!' # no, because in the further code you can't use str
type as it's overridden
Note, the last best practice is pretty Python-specific.
2.3 Conclusion
All the naming conventions and best practices are optional, but it is strongly recommended to follow
them. As we mentioned at the beginning of this lesson, they make your code more readable and
self-descriptive for you and other programmers.
2.4 Practice
2.4.1 The best name
Which of the following variable names is the best according to naming conventions?
_uha
userHomeAddress
userhomeaddress
the_home_address_of_the_user
user_home_address (X)
2.4.2 Number of people in the class
The name number_of_people_in_the_class is a very long name for a variable. What is the best way to
shorten it?
n_o_p
nopitc
https://www.python.org/dev/peps/pep-0008/#naming-conventions
n_of_people_inc
number_of_people
2.4.3 Good names
Here's a list of variables:
number_of_people_in_the_room = 10
model_score = 0.9875
client_name = "Bob"
colorOfTheShirt = "red"
Some of them are named according to naming conventions and best practices, others are not.
Copy only the lines with those variables that have good names in your code. You don't need to use the
print() function.
Solution:
model_score = 0.9875
client_name = "Bob"
2.4.4 Zeros and ones
Apart from texting, the abbreviation lol can be easily mistaken for anumerical sequence. What number
is it? Solution: 101
2.4.5 Character set
Letters from which standard are recommended for naming variables? Select one option from the list:
Unicode
Runic
ANSEL
ASCII (X)
2.4.6 The first char
The Python naming conventions specify groups of characters that are allowed at the beginning of a
variable name. What characters cannot start a name? Select one option from the list:
digits (X)
lowercase letters
uppercase letters
underscores
2.4.7 Why to name variables?
Why should a developer care about variable names? Select all that apply.
Select one or more options from the list
To increase the code readability. (X)
To make the code easier to understand. (X)
To increase the code artistry.
To make the code compilable.
2.4.8 A good style guide
What is the name of the document in which you can find official Python recommendations for variable
naming? Solution: PEP8
2.4.9 This is Python
Rename the variables in the code below according to the Python code style convention.
http_response = 'mocked response'
http_error = 404
2.4.10 How to name a variable?
Select all the correct variable names according to PEP 8 code style convention. Select one or more
options from the list:
error_message (X)
int
correctAnswer
class_ (X)
O
2.4.11 Everest
In your program, you need a variable to store the height of mount Everest (8, 848 m). There are other
heights and other mountains in the program, so you cannot simply call it height . The name of the
variable should reflect the fact that the value is constant and refer to the measure and the object .
What would be an optimal name for that variable?
the_height_of_everest_in_meters
height_of_everest
everest_height
MOUNTAIN_HEIGHT
mount_everest
EVEREST_HEIGHT (X)
2.4.12 Fix str
The previous developer accidentally named a variable str. Since this name is reserved for a built-in type,
now the code fails.
Please fix the variable name by adding an underscore, as suggested in the topic. The value of your new
variable shouldn't change, i.e. it should look like Hello10 . You don't have to print anything.
Remember that the str() function returns the string version of the given object.
str = "Hello"
str = str + str(10)
Failed. Runtime error
Error: Traceback (most recent call last):
File "jailed_code", line 2, in <module>
str_ = str_ + str_(10) TypeError: 'str' object is not callable
Solution:
str_ = "Hello"
str_ = str_ + str ( 10 )
3 Theory: Program with numbers
Programs in which there's nothing to calculate are quite rare. Therefore, learning to program with
numbers is never a bad idea. An even more valuable skill we are about to learn is the processing of user
data. With its help, you can create interactive and by far more flexible applications. So let's get started!
3.1 Reading numbers from user input
Since you have become familiar with the input() function in Python, it's hardly new to you that any data
passed to this function is treated as a string. But how should we deal with numerical values? As a
general rule, they are explicitly converted to corresponding numerical types:
integer = int(input())
floating_point = float(input())
Pay attention to current best practices: it's crucial not to name your variables as built-in types (say, float
or int). Also, we should take into account user mistakes: if a user types an inaccurate input, say, a string
'two' instead of a number 2, a ValueError will occur. At the moment, we won't focus on it; but don't worry,
more information about errors is available in a dedicated topic. Now, consider a more detailed and
pragmatic example of handling numerical inputs.
3.2 Free air miles
Imagine you have a credit card with a free air miles bonus program (or maybe you already have one). As
a user, you are expected to input the amount of money you spend on average from this card per month.
Let's assume that the bonus program gives you 2 free air miles for every dollar you spend. Here's a
simple program to figure out when you can travel somewhere for free:
# the average amount of money per month
money = int(input("How much money do you spend per month: "))
# the number of miles per unit of money
n_miles = 2
# earned miles
miles_per_month = money * n_miles
# the distance between London and Paris
distance = 215
# how many months do you need to get
# a free trip from London to Paris and back
print(distance * 2 / miles_per_month)
This program will calculate how many months it takes to travel the selected distance and back.
Although it is recommended to write messages for users in the input() function, avoid them in our
educational programming challenges, otherwise your code may not pass our tests.
3.3 Advanced forms of assignment
Whenever you use an equal sign =, you actually assign some value to a name. For that reason, = is
typically referred to as an assignment operator. Meanwhile, there are other assignment operators you
can use in Python. They are also called compound assignment operators, for they carry out an
arithmetic operation and assignment in one step. Have a look at the code snippet below:
# simple assignment
number = 10
number = number + 1 # 11
This code is equivalent to the following one:
# compound assignment
number = 10
number += 1 # 11
One can clearly see from the example that the second piece of code is more concise (for it doesn't
repeat the variable's name).
Naturally, similar assignment forms exist for the rest of arithmetic operations: -=, *=, /=, //=,
%=, **=. Given the opportunity, use them to save time and effort.
One possible applicationof compound assignment comes next.
3.4 Counter variable
In programming, loops are used alongside special variables called counters. A counter counts how many
times a particular code is run. It also follows that counters should be integers. Now we are getting to the
point: you can use the operators += and -= to increase or decrease the counter respectively.
Consider this example where a user determines the value by which the counter is increased:
counter = 1
step = int(input()) # let it be 3
counter += step
print(counter) # it should be 4, then
In case you need only non-negative integers from the user (we are increasing the counter after all!), you
can prevent incorrect inputs by using the abs() function. It is a Python built-in function that returns the
absolute value of a number (that is, value regardless of its sign). Let's readjust our last program a bit:
counter = 1
step = abs(int(input())) # user types -3
counter += step
print(counter) # it's still 4
As you can see, thanks to the abs() function we got a positive number.
For now, it's all right that you do not know much about the mentioned details of errors, loops and built-in
functions in Python. We will catch up and make sure that you know these topics comprehensively. Keep
learning!
3.5 Conclusion
Thus, we have shed some light on new details about integer arithmetic and the processing of numerical
inputs in Python. Feel free to use them in your future projects.
An airline company "Happy travel" has a loyalty system for its customers: for each spent dollar they get
0.01 free miles on their account and then can use them to travel for free. Below is the code for free air
miles calculation for one customer who plans to travel from London to Paris and back:
# the number of free miles per dollar
n_miles = 0.01
# money spent per month (in dollars)
money = 2000
# number of miles earned each month
miles_per_month = money * n_miles
# distance from London to Paris and back (in miles)
total_distance = 215 * 2
3.6 Practice
3.6.1 Bad omen
Take a look at the code below:
step = 666
counter += step
print (counter)
It's not working for some reason. What's wrong with it? Select one option from the list:
The step value should be a floating-point number.
The step value is extremely large.
One of the variables hasn't been defined. (X)
The compound assignment operator should be =+.
3.6.2 Undercover
Which of the following operators has nothing to do with compound assignment?
Select one option from the list:
+=
-=
**=
//=
%=
== (X)
Well done! The equality operator ̀==` is used to compare values, not to assign them.
3.6.3 When you'll have a free trip?
An airline company "Happy travel" has a loyalty system for its customers: for each spent dollar they get
0.01 free miles on their account and then can use them to travel for free. Below is the code for free air
miles calculation for one customer who plans to travel from London to Paris and back:
# the number of free miles per dollar
n_miles = 0.01
# money spent per month (in dollars)
money = 2000
# number of miles earned each month
miles_per_month = money * n_miles
# distance from London to Paris and back (in miles)
total_distance = 215 * 2
What would be the correct final line to calculate how many months it will take for this client to make the
desired trip free of charge? Select one option from the list:
total_distance * 2 / miles_per_month
total_distance / miles_per_month
total_distance * 2
total_distance * miles_per_month
3.6.4 Calculating an expression
Write a program that reads an integer value n from the standard input and prints the result of the
expression:
((n + 1) * n + 2) * n + 3
Sample Input 1: 3
Sample Output 1: 45
Solution:
n = int ( input ())
print ((( n + 1 ) * n + 2 ) * n + 3 )
3.6.5 The last digit of a number
Write a program that reads an integer and outputs its last digit.
Sample Input 1: 425
Sample Output 1: 5
Hints:
I had to do a bit of googling and found that % 10 will always give the last digit of a number.
you'll want the user to input a number, but make sure its an integer.
last_digit = number % 10 # having % 10 will ALWAYS give only the last digit.
lastly, print the last_digit
number = ....
last_digit = number % 10
print(.....)
Solution:
number01 = int ( input ())
last_digit = number01 % 10
print ( last_digit )
Outras resoluções:
a = int ( input ())
print (a % 10 )
number = list ( str ( input ()))
print (number[ -1 ])
num = list ( input ( '' ))
last_index = num[ -1 ]
print (last_index)
input_number = int ( input ()) # put your python code here
print ( str (input_number)[ -1 ])
n = input ()
print (n[ -1 ])
n = input () # take a number as string
print (n[ -1 ]) # print the the last char in the string index > -1
print ( input ()[ -1 ])
3.6.6 Calculating S V P
Ask the user about parameters of a rectangular parallelepiped (3 integers representing the length, width
and height) and print the sum of edge lengths, its total surface area and volume.
Sum of lengths of all edges: s = 4(a + b + c)s=4(a+b+c)
Surface area: S = 2(ab + bc + ac)S=2(ab+bc+ac)
Volume: V = abc
Solution:
a = int ( input ())
b = int ( input ())
c = int ( input ())
len_edges = 4 * ( a + b + c )
area_surf = 2 * (( a * b ) + ( b * c ) + ( a * c ))
vol_par = a * b * c
print ( len_edges )
print ( area_surf )
print ( vol_par )
Outras resoluções:
print (( lambda a, b, c: (f "{4 * (a + b + c)}\n{2 * (a * b + b * c + c * a)}\n{a * b *
c}" ))( int ( input ()), int ( input ()), int ( input ())))
____
a, b, c = int ( input ()), int (input ()), int ( input ())
print ( "{}\n{}\n{}" . format ( 4 * (a + b + c), 2 * (a * b + b * c + a * c), a * b * c))
____
a, b, c = int ( input ()), int ( input ()), int ( input ())
s = 4 * (a + b + c)
S = 2 * ((a * b) + (b * c) + (a * c))
V = a * b * c
print (s, S, V, sep= "\n" )
3.6.7 Divide nuts equally between squirrels
N squirrels found K nuts and decided to divide them equally. Determine how many nuts each squirrel will
get.
Input data format: There are two positive numbers N and K, each of them is not greater than 10000.
Sample Input 1: 3 14
Sample Output 1: 4
Solution:
N = int ( input ())
K = int ( input ())
print ( K // N )
Outras resoluções:
n = int ( input ())
print ( int ( input ()) // n)
____
N = abs ( int ( input ()))
K = abs ( int ( input ()))
print (K // N)
3.6.8 The first digit of a two-digit number
Write a program that will take an input of a two-digit integer and print its first digit (i.e. the number of
tens).
Sample Input 1: 42
Sample Output 1: 4
Solution:
que = int ( input ())
print ( que // 10 )
Outras resoluções:
number = input ()
print (number[ 0 ])
____
print ( input ()[ 0 ])
3.6.9 Difference of times
You will get the values for two moments in time of the same day: when Megan went for a walk, and
when it started to rain. It is known that the first event happened earlier than the second one. Find out
how many seconds passed between them.
The program gets the input of six integers, each on a separate line. The first three integers represent
hours, minutes, and seconds of the first event, and the rest three integers define similarly the second
event. Print the number of seconds between these two moments of time.
Sample Input 1: 1 1 1 2 2 2
Sample Output 1: 3661
Sample Input 2: 1 2 30 1 3 20
Sample Output 2: 50
Solution:
hour1 = int ( input ())
min1 = int ( input ())
sec1 = int ( input ())
hour2 = int ( input ())
min2 = int ( input ())
sec2 = int ( input ())
first_event = ( hour1 * 3600 ) + ( min1 * 60 ) + sec1
second_event = ( hour2 * 3600 ) + ( min2 * 60 ) + sec2
print ( second_event - first_event )
Outras resoluções:
hour1 = int ( input ())
minute1 = int ( input ())
second1 = int ( input ())
time_1 = hour1 * 3600 + minute1 * 60 + second1
hour2 = int ( input ())
minute2 = int ( input ())
second2 = int ( input ())
time_2 = hour2 * 3600 + minute2 * 60 + second2
print ( abs (time_1 - time_2))
____
print ( abs (hours_2 * 3600 + minutes_2 * 60 + seconds_2 - hours_1 * 3600 - minutes_1 * 60
- seconds_1))
3.6.10 The sum of digits
Given a three-digit integer (i.e., an integer from 100 to 999). Find the sum of its digits and print the result.
To get the separate digits of the input integer, make use of % and // (for example, you can get 8 from the
number 508 by taking the remainder of the division by 10).
Sample Input 1: 476
Sample Output 1: 17
Solution:
number = list ( str ( input ()))
sum_dig = ( int ( number [ 0 ]) + int ( number [ 1 ]) + int ( number [ 2 ]))
print ( sum_dig )
Outras resoluções:
n = abs ( int ( input ()))
hundreds = n // 100
tens = (n % 100 ) // 10
units = n % 10
print (hundreds + tens + units)
____
n = int ( input ())
print (n // 100 + n % 100 // 10 + n % 10 )
____
n = int ( input ())
print (( int (n / 100 )) + ((n // 10 ) % 10 ) + (n % 10 ))
____
number = int ( input ())
a = number // 100
b = number // 10 - a * 10
c = number % 10
print (a + b + c)
____
print ( sum ([ int (x) for x in str ( input ())]))
* Correct, but can be improved. 1 code style error
____
number = str ( input ())
count = 0
for i in number:
count += int (i)
print (count)
____
num = str ( input ())
f = num[ 0 ]
s = num[ 1 ]
t = num[ 2 ]
f = int (f)
s = int (s)
t = int (t)
res = f + s + t
print (res)
3.6.11 Pumpkin pie
Paul has baked a pumpkin pie and asked his guests how many pieces they wanted to take home:
n_pieces = int(input("How many pieces of the pumpkin pie can I offer you?"))
It's so nice of him! However, this program crashed as one guest entered the value 2.5. What are possible
actions to prevent the error in the code? There is more than just one correct answer.
Let's assume that no guest should leave without a treat! You also don't have to think about cases when a
guest enters something different than a number in this task. Select one or more options from the list:
Leave the whole pie for you.
Convert the input value to float rather than int . (X)
Read the numbers as floats and then round them up to the closest integer. (X)
Print a message for the guests that pieces should be whole.
3.6.12 Savings account
For the given amount of money, calculate the income from this savings account with a 5% interest rate
after one year.
Save the result into the variable income. You DO NOT need to print it.
Solution:
amount = 1000
interest_rate = 5
years = 1
income = ( amount * ( interest_rate / 100 ))
3.6.13 Good rest on vacation
Write a program that will help people who are going on vacation. The program should calculate the total
required sum (e.g. $) of money to have a good rest for a given duration.
There are four parameters that have to be considered:
● duration in days
● total food cost per day
● one-way flight cost
● cost of one night in a hotel (the number of nights is equal to the duration of days minus one)
Read integer values of these parameters from the standard input and then print the result.
Sample Input 1: 7 30 100 40
Sample Output 1: 650
Solution:
n_days = abs ( int ( input ()))
food_day = abs ( int ( input ()))
flight = abs ( int ( input ()))
h_per_night= abs ( int ( input ()))
hotel_total = abs ( int ( n_days - 1 ) * h_per_night )
print (( n_days * food_day ) + ( flight * 2 ) + hotel_total )
3.6.14 Desks
A school has decided to create three new math groups and equip three classrooms for them with new
desks. Your task is to calculate the minimum number of desks to be purchased. To do so, you'll need the
following information:
● The number of students in each of the three groups is known: your program will receive three
non-negative integers as the input. It is possible that one or more of them will be zero, so you
should take it into account.
● Each group will sit in its own classroom. It means that you should calculate the number of desks
for each classroom separately, and only then add them up!
● At most two students may sit at any desk. You are expected to output the minimum number of
desks to buy, so there should be as many as possible desks taken by two students rather than
one.
Most probably, you'll need operations // and % in your program!
Sample Input 1: 20 21 22
Sample Output 1: 32
Sample Input 2: 16 18 20
Sample Output 2: 27
Solution:
stud_01 = abs ( int ( input ()))
stud_02 = abs ( int ( input ()))
stud_03 = abs ( int ( input ()))
print (( stud_01 // 2 + stud_02 // 2 + stud_03 // 2 )
+ ( stud_01 % 2 + stud_02 % 2 + stud_03 % 2 ))
4 Theory: Boolean logic
4.1 Boolean type
The Boolean type, or simply bool , is a special data type that has only two possible values: True and
False . In Python the names of boolean values start with a capital letter.
In programming languages the boolean, or logical, type is a common way to represent something that
has only two opposite states like on or off, yes or no, etc.
If you are writing an application that keeps track of door openings, you'll find it natural to use bool to
store the current door state.
is_open = True
is_closed = False
print(is_open) # True
print(is_closed) # False
4.2 Boolean operations
There are three built-in boolean operators in Python: and, or and not . The first two are binary
operators which means that they expect two arguments. not is a unary operator, it is always applied to a
single operand. First, let's look at these operators applied to the boolean values.
● and is a binary operator, it takes two arguments and returns True if both arguments are true,
otherwise, it returns False .
a = True and True # True
b = True and False # False
c = False and False # False
d = False and True # False
● or is a binary operator, it returns True if at least one argument is true, otherwise, it returns
False .
a = True or True # True
b = True or False # True
c = False or False # False
d = False or True # True
● not is a unary operator, it reverses the boolean value of its argument.
to_be = True # to_be is True
not_to_be = not to_be # not_to_be is False
4.3 The precedence of boolean operations
Logical operators have a different priority and it affects the order of evaluation. Here are the operators in
order of their priorities: not, and, or. So, not is considered first, then and, finally or. Having this in mind,
consider the following expression:
print(False or not False) # True
First, the part not False gets evaluated, and after evaluation, we are left with False or True. This results in
True, if you recall the previous section.
While dealing solely with the boolean values may seem obvious, the precedence of logical operations
will be quite important to remember when you start working with so-called truthy and falsy values.
4.4 Truthy and falsy values
Though Python has the boolean data type, we often want to use non-boolean values in a logical context.
And Python lets you test almost any object for truthfulness. When used with logical operators, values of
non-boolean types, such as integers or strings, are called truthy or falsy . It depends on whether they are
interpreted as True or False .
The following values are evaluated to False in Python:
● constants defined to be false: None and False ,
● zero of any numeric type: 0, 0.0,
● empty sequences and containers: "", [], {}.
Anything else generally evaluates to True . Here is a couple of examples:
print(0.0 or False) # False
print("True" and True) # True
print("" or False) # False
Generally speaking, and and or could take any arguments that can be tested for a boolean value.
Now we can demonstrate more clearly the difference in operator precedence:
# “and” has a higher priority than “or”
truthy_integer = False or 5 and 100 # 100
Again, let's break the above expression into parts.
Since the operator and has a higher priority than or , we should look at the 5 and 100 part. Both 100
and 5 happen to be truthy values, so this operation will return 100. You have never seen this before, so
it's natural to wonder why we have a number instead of the True value here. The explanation is as
follows:
Coming back to the original expression, you can see that the last part False or 100 does exactly the
same thing, returns 100 instead of True .
Another tricky example is below:
tricky = not (False or '') # True
A pair of parentheses is a way to specify the order in which the operations are performed.
Thus, we evaluate this part of the expression first: False or '' .
This operand '' evaluates to False and or returns this empty string. Since the result of the enclosed
expression is negated, we get True in the end: not '' is thesame as True .
Why didn't we get, say, a non-empty string? The not operator creates a new value, which by default has
the boolean type. So, as stated earlier, the unary operator always returns a logical value.
4.5 Short-circuit evaluation
The last thing to mention is that logical operators in Python are short-circuited . That's why they are also
called lazy . That means that the second operand in such an expression is evaluated only if the first one
is not sufficient to evaluate the whole expression.
● x and y returns x if x is falsy; otherwise, it evaluates and returns y.
● x or y returns x if x is truthy; otherwise, it evaluates and returns y.
For instance:
# division is never evaluated, because the first argument is True
lazy_or = True or (1 / 0) # True
# division is never evaluated, because the first argument is False
lazy_and = False and (1 / 0) # False
Those were the very basics of boolean values and logical operations in Python. It's definitely good to
know them right from the beginning!
4.6 Practice:
4.6.1 Boolean type
Which values are considered boolean in Python? Select one or more options from the list
True (X) "True" None
1 0 False (X)
4.6.2 Priority
Sort boolean operations from the highest priority to the lowest: not, (1) and, (2) or (3)
4.6.3 Boolean values
Assuming that variables have the following boolean values:
a = True
b = not a
Enter the result by evaluating the expression:
not (a and b)
The operators or and and return one of their operands, not necessarily of the boolean type.
Nonetheless, not always returns a boolean value.
4.6.4 False in Python
Choose all the values that are considered False in Python. Select one or more options from the list
False (X)
"" (X)
"False"
0 (X)
1
"0"
4.6.5 Exclusive or
Exclusive OR , or simply XOR , is a binary logical operation. It returns True only if both arguments are
different (one is True , the other is False ).
Here is a table with XOR outputs for different values of variables a and b :
Select all the expressions that give the same result as applying XOR to the boolean variables a and b
(that is, the expressions acting as a XOR b ).
Select one or more options from the list:
not a or b
(a or b) and not (a and b)
(a and b) or not (a or b)
(a and not b) or (not a and b)
a and not b
4.6.6 Logical operations
In Python, logical operators and and or follow short-circuit evaluation rule.
There are two boolean variables:
a = True
b = False
Choose the expressions that should be evaluated fully to determine their value. This means that the
whole expression will be evaluated, not just part of it.
Here is the main rule:
● a and b returns a if a is False; otherwise, it evaluates and returns b ;
● a or b returns a if a is True ; otherwise, it evaluates and returns b .
Select one or more options from the list
not a and b
b and a
a b XOR
True True False
True False True
False True True
False False False
You might be familiar with ̂ , the bitwise XOR operator in Python. Although it can be used to solve this
task, keep in mind that it works with binary representations of data, whereas boolean operations have
no such limitation.
a or b
a and b (X)
not a or b (X)
b or a (X)
Note the following in your thought process.
"or" expressions only evaluates the second argument if the first one is false
"and" expressions only evaluates the second argument if the first one is true
4.6.7 Boolean expression
What will be the boolean value of the following expression? Write the result.
not None or 1
Answer: True
5 Theory: Comparisons
Writing code without comparing any values in it will get you only so far. Now, it's time to master this skill.
5.1 Comparison operators
Comparison or relation operations let you compare two values and determine the relation between
them. There are ten comparison operators in Python:
● < strictly less than
● <= less than or equal
● > strictly greater than
● >= greater than or equal
● == equal
● != not equal
● is object identity
● is not negated object identity
● in membership
● not in negated membership.
The result of applying these operators is always bool . The following sections focus on the first six
operators ( <, <=, >, >=, ==, != ), but you can find more details about identity and membership
testing in the next topics.
5.2 Comparing integers
In this topic, we will cover only integer comparison.
a = 5
b = -10
c = 15
result_1 = a < b # False
result_2 = a == a # True
result_3 = a != b # True
result_4 = b >= c # False
Any expression that returns integer is a valid comparison operand too:
calculated_result = a == b + c # True
Given the defined variables a, b and c , we basically check if 5 is equal to -10 + 15 , which is true.
5.3 Comparison chaining
Since comparison operations return boolean values, you can join them using logical operators.
x = -5
y = 10
z = 12
result = x < y and y <= z # True
In Python, there is a fancier way to write complex comparisons. It is called chaining . For example, x <
y <= z is almost equivalent to the expression you saw in the last example. The difference is that y is
evaluated only once.
result = 10 < (100 * 100) <= 10000 # True, the multiplication is evaluated once
5.4 Practice
5.4.1 Carry on!
If you've ever traveled by plane, you know that there are strict rules when it comes to carry-on luggage. A
handbag has three dimensions: width, length and height. Some company set the following rule for the
carry-on:
allowed = (height <= 10 <width <= 35 < length <= 40) or (height + width + length <= 80)
Which carry-ons are going to be allowed on a plane? Select one or more options from the list
height = 4, width = 30, length = 50
height = 15, width = 25, length = 37 (X)
height = 25, width = 30, length = 23 (X)
height = 10, width = 35, length = 35 (X)
5.4.2 Matchmaker
Here are the values of some variables:
x = 1
y = 1
z = 1000
q = 1000
m = 37
What operator should be used instead of the underscore in the code below so that the expressions
would have intended value? Match the options.
z _ y : False < x _ y : True == m _ q : False >
Please pay attention to the fact that tools for code quality often recommend chaining comparisons
instead of joining them.
5.4.3 Discount
The museum gives discounts to people according to the following rule:
age = ...
discount = (age < 21 ) or (age >= 65 )
A family of five wants to visit this museum. Which family members will get a discount, if these are their
ages:
Mary - 49 Andrew - 50 Dora - 21 John - 15 Ann - 75
Select one or more options from the list:
Andrew
Ann (X)
Dora
John (X)
Mary
5.4.4 Focus on the positive
Write a program that reads an integer value from the input and checks if it is positive.
Hint: 0 is not a positive number.
A comparison already returns a boolean, so if you need the result of the comparison, you can print
it, like this print(5 > 9) # False
Sample Input 1: 8 Sample Output 1: True
Solution:
a = int ( input (). strip ())
print ( a > 0 )
5.4.5 Enrolling
Imagine, you are developing a rule in terms of logical and comparison operations to determine whether
you should enroll a student in your course or not. The rule itself looks like this:
enroll_student = ((average_grade >= 40 and recommended_by_tutor)
or (finished_introductory_course and introductory_course_grade > 85 ))
Parameters meaning:
● average_grade is an integer variable that shows the student's average grade.
● recommended_by_tutor is a bool variable that shows whether the student has a recommendation
from the tutor.
● finished_introductory_course is a bool variable that shows whether the student finished the
introductory course.
● introductory_course_grade is an integer variable that shows the student's introductory course
grade.
The table of students who wish to enroll:
Using this rule select all the students to enroll. Select one or more options from the list:
Anne (X)
John
Frank (X)
Victoria (X)
Mary
Sam
5.4.6 True test
Select all the values of variable a such that is True.
a = ...
test_result = a <= 0 or a > 200
Select one or more options from the list
-100 (X)
0 (X)
100
200
500 (X)
5.4.7 In the middle
Write a program that reads an integer value from input and checks if it is less than 10 or greater than
250.
Sample Input 1: 0
Sample Output 1: True
Solution:
print ( a > 250 or a < 10 )
5.4.8 Very odd
Find out if the result of dividing A by B is an odd number.
The input format:
The first line is the dividend (A) and the second line is the divisor (B). It is guaranteed that the numbers
are divided without remainder.
The output format:
True or False
Sample Input 1: 99 3
Sample Output 1: True
average_grade recommended_by_tutor finished_introductory_course introductory_course_grade
Anne 49 True False 0
John 41 False True 76
Frank 37 True True 97
Victoria 40 True True 86
Mary 49 False True 85
Sam 33 False True 51
Remember the thing that if the result % 2 equals 1 then the result is odd, else if the result % 2 equals
0 then the result is even.
Solution:
A = int ( input ())
B = int ( input ())
result = A / B
print ( not result % 2 == 0 )
outras resoluções:
print (( int ( input ()) / int ( input ())) % 2 != 0 )
a = int ( input ())
b = int ( input ())
c = a // b
if c % 2 == 0 :
print ( 'False' )
else :
print ( 'True' )
____
a = int ( input ())
b = int ( input ())
print ((a / b) % 2 != 0 )
5.4.9 Guessing game
You are playing a guessing game with a user. Imagine that you came up with an integer stored in a
variable set_number . Check if set_number is equal to the product of two integers entered by the
user.
The input format:
Two lines containing integer numbers for you to multiply.
The output format:
True if the user guessed correctly and False otherwise.
Sample Input: 3 11 Sample Output: False
Solution:
set_number = 847
mu1 = int ( input ())
mu2 = int ( input ())
print ( mu1 * mu2 == set_number )
Outras Resoluções:
set_number = 6557
print (( lambda x, y: x * y == set_number)( int ( input ()), int ( input ())))
____
“Best”
set_number = 6557
print (set_number == int ( input ()) * int ( input ()))
____
set_number = 6557
a = ( lambda x, y: x * y == set_number)( int ( input ()), int ( input ()))
print (a)
____
set_number = 6557
a = abs ( int ( input ()))
b = abs ( int ( input ()))
prod = a * b
print (set_number == prod)
5.4.10 Movie theater
The movie theater has cinema halls that can accommodate a certain number of viewers each.
Figure out if a movie theater can hold a given number of viewers that plan to visit it on a particular day.
The input format:
The first line is number of halls , the second line is their capacity , and the third line is the
planned number of viewers. The output format: True or False.
Sample Input 1: 9 68 589
Sample Output 1: True
Primeira tentativa (Errada):
n_halls_max = int(9)
capacity_max = int(68)
n_viewers_max = int(589)
n_halls = int(input())
capacity = int(input())
n_viewers = int(input())
print(n_halls <= n_halls_max and capacity <= capacity_max andn_viewers <= n_viewers_max)
Hint: Use int in input 3 inputs use print ( xxxxx * xxxx >= xxxxx)
Solution:
n_halls = int ( input ())
capacity = int ( input ())
n_viewers = int ( input ())
print ( n_halls * capacity >= n_viewers )
Outras resoluções:
print ( int ( input ()) * int ( input ()) >= int ( input ()))
____
halls, capacity, viewers = ( int ( input ()) for _ in range ( 3 ))
print (halls * capacity >= viewers)
____
x = [ int ( input ()) for i in range ( 3 )]
print (x[ 2 ] <= x[ 1 ] * x[ 0 ])
____
capacity = int ( input ()) * int ( input ())
viewers = int ( input ())
____
if viewers <= capacity:
print ( True )
else :
print ( False )
5.4.11 Order!
Get three large numbers from input and check that they are given in ascending order. The subsequent
number must be greater than the previous one.
The input format:
Three lines with three numbers.
The output format:
True or False
Sample Input 1: 7.790.765.547.678.990 7.790.765.557.679.990 7.790.765.557.778.900
Sample Output 1: True
Solution:
a = int(input())
b = int(input())
c = int(input())
print(a < b < c)
5.4.12 Operator
Which of the following are NOT comparison operators in Python?
Select one or more options from the list
is
=== (X)
==
>=
<=
!=
not in
=> (X)
5.4.13 Don't want to delete? Comment!
Sometimes, it is useful to comment out some parts of a program if you don't need them now and
want to save them for later. Look at the following code and decide what line(s) of code to convert to
comment so that when you run this block of code, the program will print only an integer 7.
Solution:
# print(1 + 2 + 3 + 6)
print ( 1 + 3 + 3 ) # print(1 + 2 + 3)
6 Theory: If statement
6.1 Simple if statement
There are situations when your program needs to execute some piece of the code only if a particular
condition is true. Such a piece of the code should be placed within the body of an if statement. The
pattern is the same as in the English language: first comes the keyword if , then a condition, and then a
list of expressions to execute. The condition is always a Boolean expression, that is, its value equals
either True or False . Here is one example of how the code with a conditional expression should look
like:
biscuits = 17
if biscuits >= 5 :
print ( "It's time for tea!" )
Note that the condition ends with a colon and a new line starts with an indentation. Usually, 4 spaces
are used to designate each level of indentation. A piece of code in which all lines are on the same level of
indentation is called a block of code . In Python, only indentation is used to separate different blocks of
code, hence, only indentation shows which lines of code are supposed to be executed when the if
statement is satisfied, and which ones should be executed independently of the if statement. Check out
the following example:
if biscuits >= 5 :
print ( "It's time for tea!" )
print ( "What tea do you prefer?" )
print ( "What about some chocolate?" )
In this example, the line "It's time for tea!" , as well as "What tea do you prefer?", will
be printed only if there are 5 or more biscuits. The line "What about some chocolate?" will be
printed regardless of the number of biscuits.
An if statement is executed only if its condition holds (the Boolean value is True ), otherwise, it's
skipped.
Boolean values basically make it clear whether a piece of code needs to be executed or not. Since
comparisons result in bool , it's always a good idea to use them as a condition.
There is one pitfall, though. You should not confuse the comparison operator for equality == with the
assignment operator =. Only the former provides for a proper condition. Try to avoid this common
mistake in your code.
6.2 Nested if statement
Sometimes a condition happens to be too complicated for a simple if statement. In this case, you can
use so-called nested if statements. The more if statements are nested, the more complex your code
gets, which is usually not a good thing. However, this doesn't mean that you need to avoid nested if
statements at all costs. Let's take a look at the code below:
rainbow = "red, orange, yellow, green, blue, indigo, violet"
warm_colors = "red, yellow, orange"
my_color = "orange"
if my_color in rainbow:
print ( "Wow, your color is in the rainbow!" )
if my_color in warm_colors:
print ( "Oh, by the way, it's a warm color." )
The example above illustrates a nested if statement. If the variable my_color is a string that contains the
name of a color from the rainbow, we enter the body of the first if statement. First, we print the message
and then check if our color belongs to the warm colors. The membership operator in simply shows
whether my_color is a substring of the respective string, rainbow or warm_colors. Just like arithmetic
comparisons, it returns a boolean value.
Here is what we will see in our case:
Wow, your color is in the rainbow!
Oh, by the way, it's a warm color.
When it comes to nested if statements, proper indentation is crucial, so do not forget to indent each
statement that starts with the if keyword.
6.3 Practice
6.3.1 Bouquet
Florist Lillian finds it easier to arrange flowers when their number is odd. So, if the number of flowers in a
bouquet happens to be even, she usually adds one more flower. How would you replicate this procedure
in code?
Make sure to indent your code properly: hitting the right arrow button once equals to adding 4 spaces for
indentation.To reorder the lines of code you can either use up and down arrows that are placed to the right of each
line of code, or drag them with the mouse.
Rearrange the lines to make the code work. Use the arrow buttons to add indentation.
1 n_flowers = int(input())
2 if n_flowers % 2 == 0:
3 n_flowers += 1
6.3.2 Bad Omen
Which of the following expressions will result in an error message when used as a condition after if ?
Select one option from the list:
x >= 666
x = 666 (X)
x < 666
x == 666
6.3.3 Boolean logic
Which logical operator is an alternative to the nested if statements?
Suppose we were about to rewrite this code snippet
if sound == "music":
if n_people > 10:
print("We are at the party!")
as follows:
if sound == "music" ... n_people > 10:
print("We are at the party!")
How would you change ... in this case? Enter a short text (answer): and
6.3.4 Indentation
What symbols are used to indent if blocks in Python?
backslashes
curly braces
colons
spaces (X)
6.3.5 University
Here's a piece of code that tells you what university the course is read in.
harvard = "linguistics, physics, programming, fine arts"
stanford = "biology, classics, geophysics, music"
arts = "linguistics, fine arts, classics, music"
sciences = "physics, programming, biology, geophysics"
major = "..."
if major in harvard:
if major in arts:
print ( "This is an arts program at Harvard" )
if major in sciences:
print ( "This is a sciences program at Harvard" )
if major in stanford:
if major in arts:
print ( "This is an arts program at Stanford" )
if major in sciences:
print ( "This is a sciences program at Stanford" )
What will be the result if major = "biology" ? Answer: This is a sciences program at Stanford
6.3.6 Underworld
Charon the Ferryman carries souls across the river Styx to the world of the dead but does so only for a
fee. It's a business after all.
Check whether the recently deceased has a coin, if any, print Welcome to Charon's boat!
The variable coin stores a Boolean value, so it qualifies as a condition. If coin has False value, alas!
There's nothing to be done about it.
In conclusion, let's warn everyone in the underworld (both those in the boat and those overboard) by
printing the message There is no turning back.
Solution:
coin = bool(int(input()))
if coin > 0:
print("Welcome to Charon's boat!")
print("There is no turning back.")
6.3.7 The minimum
Look at the program below. It's supposed to find the minimum of two numbers, a and b, and print it out.
Unfortunately, the lines got mixed up, and the indentation disappeared. Fix this to solve the task.
1 minimum = a
2 if b < minimum:
3 minimum = b
4 print(minimum)
6.3.8 Cook book
Any recipe starts with a list of ingredients. Below is an extract from a cookbook with the ingredients for
some dishes. Write a program that tells you what recipe you can make based on the ingredient you have.
The input format: A name of some ingredient.
The output format: A message that says "food time!" where " food " stands for the dish that
contains this ingredient. For example, " pizza time! ". If the ingredient is featured in several recipes,
write about all of them in the order they're featured in the cook book.
Sample Input 1: basil
Sample Output 1: pasta time!
Sample Input 2: flour
Sample Output 2: apple pie time! chocolate cake time!
Solution:
pasta = "tomato, basil, garlic, salt, pasta, olive oil"
apple_pie = "apple, sugar, salt, cinnamon, flour, egg, butter"
ratatouille = "aubergine, carrot, onion, tomato, garlic, olive oil, pepper,
salt"
chocolate_cake = "chocolate, sugar, salt, flour, coffee, butter"
omelette = "egg, milk, bacon, tomato, salt, pepper"
food = input ()
if food in pasta :
print ( "pasta time!" )
if food in apple_pie :
print ( "apple pie time!" )
if food in ratatouille :
print ( "ratatouille time!" )
if food in chocolate_cake :
print ( "chocolate cake time!" )
if food in omelette :
print ( "omelette time!" )
Outras resoluções:
recipes = dict (pasta=pasta, apple_pie=apple_pie, ratatouille=ratatouille,
chocolate_cake=chocolate_cake,
omelette=omelette)
ingredient = input ()
for key, value in recipes.items():
if ingredient in value:
print (f "{' '.join(key.split('_'))} time!" )
____
foods = { 'pasta' : pasta, 'apple pie' : apple_pie, 'ratatouille' : ratatouille, 'chocolate
cake' : chocolate_cake, 'omelette' : omelette}
ingredient = input ()
for food in foods:
if ingredient in foods[food]:
print (food, 'time!' )
____
dishes = {
pasta: "pasta" ,
apple_pie: "apple pie" ,
ratatouille: "ratatouille" ,
chocolate_cake: "chocolate cake" ,
omelette: "omelette"
}
ingredient = input ()
for dish in dishes:
if ingredient in dish:
print (dishes[dish] + " time!" )
____
food = [pasta, apple_pie, ratatouille, chocolate_cake, omelette]
dish = [ "pasta" , "apple pie" , "ratatouille" , "chocolate cake" , "omelette" ]
ingredient = input ()
for i in enumerate (food):
if ingredient in food[i[ 0 ]]:
print (f "{dish[i[0]]} time!" )
7 Theory: While loop
Sometimes one iteration (=execution) of a statement is not enough to get the result you need. That is
why Python offers a special statement that will execute a block of code several times. Meet the loop
command and one of the universal loops — the while loop.
People generally don't choose Python to write fast code. The main advantages of Python are readability
and simplicity. As the while loop requires the introduction of extra variables, iteration takes up more
time. Thus, the while loop is quite slow and not that popular. It resembles a conditional operator: usingthe while loop, we can execute a set of statements as long as the condition is true.
The condition itself (2) is written before the body of the loop (some call it the conditional code) and is
checked before the body is executed. If the condition is true (3a), the iterations continue. If the condition
is false (3b), the loop execution is terminated and the program control moves further to the next
operation.
7.1 Visualization
If we visualize the while loop, it’ll look like this:
number = 0
while number < 5 :
print (number)
number += 1
print ( 'Now, the number is equal to 5' )
The variable number plays here the role of a counter – a variable that changes its value after each
iteration. In this case, the iterations continue until the number is equal to 5 (note that the program
outputs the value of the number before increasing it). When the value of a counter reaches 5, the
program control moves to the next operation and prints the message. Here you can see the output of
this code:
0
1
2
3
4
Now, the number is equal to 5
7.2 The infinite loop
If you delete a part of the conditional code where you increase the value of a counter, you will bump into
the infinite loop . What does it mean? Since you don’t increase your variable, a condition never becomes
false and can work forever. Usually, it is a logical fallacy, and you'll have to stop the loop using special
statements or finishing the loop manually.
Sometimes the infinite loop can be useful, e.g. in querying a client when the loop works continuously to
provide the constant exchange of information with a user. You can implement it by writing True as a
condition after the while header.
while True:
...
7.3 Conclusion
Now you are familiar with the while loop and its usage. Don’t forget about the role of a counter,
otherwise, you’ll have to deal with the infinite loop. After you’ve written the code, try to "run" it as if you
were a Python program. That’ll help you understand how the loop works.
Programming is all about simplification, so the code should be readable, short, and clear. Don’t forget
about comments and syntax. In the beginning, it may seem that the while loop is not that easy to
implement, but after a couple of times, you’ll see that it’s a very useful tool.
7.4 Practice
7.4.1 Something about loops
Find the wrong suggestion:
The while loop statement is written before the body of the loop.
"While True" statement always leads to an infinite loop.
If the while loop statement is true, loop iterations are over.
An infinite loop is usually a logical mistake.