Introduction to Python (Python version APG4b)

About this article

The competitive programming site AtCoder has "AtCoder Programming Guide for beginners (APG4b)" as an introductory programming material. There is. It is a very complete introductory programming material and uses C ++, the main language of competitive programming. So, in this article, I wrote a Python version of APG4b based on it. Basically, please continue reading APG4b and refer to this article for Python-specific parts.

Most of it is based on APG4b, so if you find this article problematic, remove it immediately.

The heading of each section is a link to the head family. Since the section titles are tailored to the original family, there are some differences from the Python terminology.

table of contents

1.00. Introduction [1.01. Output and Comments](https://qiita.com/saba/items/b9418d7b54cce4b106e4#101%E5%87%BA%E5%8A%9B%E3%81%A8%E3%82%B3%E3% 83% A1% E3% 83% B3% E3% 83% 88) [1.02. Program writing and errors](https://qiita.com/saba/items/b9418d7b54cce4b106e4#102%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9% E3% 83% A0% E3% 81% AE% E6% 9B% B8% E3% 81% 8D% E6% 96% B9% E3% 81% A8% E3% 82% A8% E3% 83% A9% E3% 83% BC) [1.03. Four arithmetic operations and priorities](https://qiita.com/saba/items/b9418d7b54cce4b106e4#103%E5%9B%9B%E5%89%87%E6%BC%94%E7%AE%97% E3% 81% A8% E5% 84% AA% E5% 85% 88% E9% A0% 86% E4% BD% 8D) 1.04. Variables and types [1.05. Execution order and input](https://qiita.com/saba/items/b9418d7b54cce4b106e4#105%E5%AE%9F%E8%A1%8C%E9%A0%86%E5%BA%8F%E3 % 81% A8% E5% 85% A5% E5% 8A% 9B) [1.06.if statement / comparison operator / logical operator](https://qiita.com/saba/items/b9418d7b54cce4b106e4#106if%E6%96%87%E6%AF%94%E8%BC%83%E6 % BC% 94% E7% AE% 97% E5% AD% 90% E8% AB% 96% E7% 90% 86% E6% BC% 94% E7% AE% 97% E5% AD% 90) [1.07. Conditional expression result and bool type](https://qiita.com/saba/items/b9418d7b54cce4b106e4#107%E6%9D%A1%E4%BB%B6%E5%BC%8F%E3%81% AE% E7% B5% 90% E6% 9E% 9C% E3% 81% A8bool% E5% 9E% 8B) [1.08. Scope of variables](https://qiita.com/saba/items/b9418d7b54cce4b106e4#108%E5%A4%89%E6%95%B0%E3%81%AE%E3%82%B9%E3% 82% B3% E3% 83% BC% E3% 83% 97) [1.09. Composite Assignment Operator](https://qiita.com/saba/items/b9418d7b54cce4b106e4#109%E8%A4%87%E5%90%88%E4%BB%A3%E5%85%A5%E6 % BC% 94% E7% AE% 97% E5% AD% 90) 1.10.while statement 1.11.for sentence / break / continue [1.12. Character string (and characters)](https://qiita.com/saba/items/b9418d7b54cce4b106e4#112%E6%96%87%E5%AD%97%E5%88%97%E3%81%A8 % E6% 96% 87% E5% AD% 97) [1.13. List (array)](https://qiita.com/saba/items/b9418d7b54cce4b106e4#113%E3%83%AA%E3%82%B9%E3%83%88%E9%85%8D%E5 % 88% 97) [1.14. Standard Library Built-in Functions (STL Functions)](https://qiita.com/saba/items/b9418d7b54cce4b106e4#114%E6%A8%99%E6%BA%96%E3%83%A9%E3 % 82% A4% E3% 83% 96% E3% 83% A9% E3% 83% AA% E3% 81% AE% E7% B5% 84% E3% 81% BF% E8% BE% BC% E3% 81 % BF% E9% 96% A2% E6% 95% B0stl% E3% 81% AE% E9% 96% A2% E6% 95% B0) 1.15. Functions Conclusion

1.00. Introduction

About Chapter 1

Chapter 1 describes the basic grammar.

Programming language

The original APG4b deals with a programming language called C ++. This article deals with a programming language called Python.

How to run the program

It's good to build a Python environment at hand, but AtCoder's code tests are good enough to write.

problem

Submission practice

This article contains the Python version of the code, but please use the original submission section to submit your questions. The submission field is at the bottom of the home page.

First, change the "Language" in the submission field to "Python3 (3.4.3)". After making changes, try copying and pasting the following code.

print("Hello, world!")

After pasting, click the "Submit" button. If the page is switched and the result column is green "AC", the submission is successful.

1.01. Output and comments

Key Point

--Python code can write the processing contents directly --No need to write main function. You can write it, but you don't have to write it for small code like a competition pro. --You can print a string with print ("string ") --By writing #, the comment after # on that line becomes a comment.

Basic form of the program

The following program is a program that does nothing.


In other words, unlike C ++, there is no need to write the main function. The program works just by writing the processing contents directly. You can write the main function, but you don't have to write it for small scale programming such as competitive programming.

output

Let's take a look at the program we submitted first. This program is a program that outputs the character string "Hello, world!".

print("Hello, world!")

Execution result


Hello, world!

print() Use print () to print a string in Python. The part that specifies the character string to be output is the part of " Hello, world! ". You can print a string by writing it inside () of print (). When dealing with strings in Python programs, you need to enclose them in " ". In addition, a line break is automatically added at the end of the sentence.

End of line

In C ++ you need a ; at the end of the line, but in Python you don't have to write anything. (Even if you write it, it will work without problems)

Output another string

If you want to output another string, change the contents of " " as follows.

print("Hello World")

Output result


Hello World

Multiple outputs

You can also output multiple times.

print("a")
print("b")
print("c", "d")

Execution result


a
b
c d

As I mentioned earlier, Python's print () automatically breaks the line at the end of the sentence. Therefore, b is output on the line following ʻa. Next, by writing multiple items separated by ,, they will be output separated by spaces, such as c d`.

Numerical output

When outputting a numerical value, you can also output it by writing it directly without using " ".

print(2525)

Execution result


2525

comment

The comment is for leaving a memo to explain the operation of the program, and writing it does not affect the operation of the program. Let's look at an example of a comment in Python.

print("Hello, world!")  # Hello, world!Displayed as
#Also comment here

Execution result


Hello, world!

By writing #, the comment will be after # on that line.

Double-byte character

In Python, unlike C ++, even if "double-byte characters" are included in the program, it basically works without problems. However, it is difficult to read, so it is recommended to write in "half-width characters".

problem

You can find the problem statement at the link below. EX1. Code test and output practice

Sample program


print("Hello, world!")
print("Hello, AtCoder!")
print("Hello, Python!")

Execution result of sample program


Hello, world!
Hello, AtCoder!
Hello, Python!

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.02. How to write a program and errors

Key Point

--Python has meaning for spaces, line breaks, and indentation --Python has a coding standard called "PEP8" --Python is an interpreted language, so no compilation errors occur

How to write a program

Describes spaces, line breaks, and indentation in your program. It also describes PEP8, the Python coding convention.

Spaces and line breaks

In Python, spaces can be omitted, but line breaks are meaningful and cannot be omitted.

In C ++, ; means the end of a line, but in Python, a newline means the end of a line.

Indent

Indentation is done for readability in C ++, but indentation also makes sense in Python.

Let's take a look at the difference between C ++ and Python using the if statement described below as an example.

C++(With indentation)


#include <bits/stdc++.h>
using namespace std;
 
int main() {
    if (Conditional expression) {
processing
    }
}

C++(No indentation)


#include <bits/stdc++.h>
using namespace std;
 
int main() {
if (Conditional expression) {
processing
}
}

In C ++, there is no difference in behavior with or without indentation within {} as described above.

Python


if conditional expression:
processing

Indentation is required because Python uses : and indentation instead of {} to indicate that it is in an if statement.

PEP8 PEP8 is a Python coding convention. Coding conventions are rules that are defined for readability.

If you don't follow PEP8, the program will work fine, but if you follow it, you can write a program that is easy to read.

It would be long to introduce all of them, so here are some of them.

--Indentation is 4 half-width spaces --Maximum 79 characters per line ――Do not put extra space

Details can be found at https://pep8-ja.readthedocs.io/ja/latest/.

Program error

Basically, it is as written in the original APG4b, but since Python is an interpreted language, no compilation error occurs.

An interpreted language is executed sentence by sentence without compiling like C ++. Therefore, if there is a grammatical error, you will get a ** runtime error ** instead of a ** compile error **.

problem

You can find the problem statement at the link below. EX2. Error correction

Program written by Mr. A


print("Always)
print("2525"
print(AtCoder)

Standard error output


  File "./Main.py", line 1
    print("Always)
               ^
SyntaxError: EOL while scanning string literal

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.03. Four arithmetic operations and priorities

Key Point

operator Calculation contents
+ addition
- subtraction
* multiplication
/ division
// Truncation division
% Remainder
** Exponentiation

Four arithmetic operations

Let's see how to do a simple calculation with a Python program. The following programs perform "addition", "subtraction", "multiplication", "division", and "truncation division" in order from the top.

print(1 + 1)  # 2
print(3 - 4)  # -1
print(2 * 3)  # 6
print(7 / 3)  # 2.3333333333333335
print(7 // 3)  # 2

Execution result


2
-1
6
2.3333333333333335
2

These symbols +, -,*,/are called ** arithmetic operators **. Negative values can also be calculated, as 3-4 becomes -1. * ** is multiplication and ** / ** is "division". ** **

In Python, / is a normal division and the result is a decimal. Use // for division that is truncated after the decimal point. Also, // is always rounded to ** minus infinity **. C ++ / is also rounded down, but C ++ / is always rounded to 0, so ** C ++ / and Python // are different **. If you always want to round to 0 in Python, write something like ʻint (a / b) `.

print(10 // 3, -10 // 3)
print(int(10 / 3), int(-10 / 3))

Execution result


3 -4
3 -3

Modulo operation

% calculates the "remainder when divided".

print(7 % 3)  # 1
print(4 % 5)  # 4

Execution result


1
4

$ 7 ÷ 3 = 2 $ Not much $ 1 $ $ 4 ÷ 5 = 0 $ Too much $ 4 $ Therefore, the output of this program will be 1 and 4.

Exponentiation

Python also provides exponentiation operators. Exponentiation is a number expressed as $ a ^ b $.

print(3 ** 4)  # 81
print(25 ** 0.5)  # 5.0
print(1.5 ** 2)  # 2.25

Execution result


81
5.0
2.25

As mentioned above, ʻa ** bcan calculate $ a ^ b $. You can also calculate decimal numbers, such as25 ** 0.5 and 1.5 ** 2`.

Operator precedence

Since the priority of four arithmetic operations is the same as C ++, please refer to the original family.

problem

You can find the problem statement at the link below. EX3. Calculation problem

Sample program


print("""Write the formula here""")

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.04. Variables and types

Key Point

--Variables are memos --= is an assignment —— “Data type” is called a type

Mold Type of data to write
int integer
float Decimal
str String

variable

Let's take a look at a feature called ** variables **. Think of a variable as a "memo".

Let's look at an example.

name = 10

print(name)      # 10
print(name + 2)  # 10 + 2 → 12
print(name * 3)  # 10 * 3 → 30 

Execution result


10
12
30

Declaration and assignment

In Python, declaration and assignment are done at the same time. It may be more accurate to say that no declaration is needed.

name = 10

In this part, we declare a variable called "name" and assign 10 to it. Note that the = symbol means "assign (write)", not "equal".

Please refer to the head family for the explanation of "type" and "value".

In C ++, you need to write ʻintto specify that the variable type is an "integer", but in Python, the10 to be assigned is an integer, so the name` is automatically used. Makes the type int.

Read

The value noted in the variable in the last 3 lines of the program is read and output.

print(name)      # 10
print(name + 2)  # 10 + 2 → 12
print(name * 3)  # 10 * 3 → 30 

Variables are copied

If you write variable 1 = variable 2, the value of the variable itself will be copied. Subsequent changes in the value of either variable do not affect the other variable.

a = 10

b = a
a = 5

print(a)  # 5
print(b)  # 10

Execution result


5
10

Notice that the variable b remains at 10. The processing details are explained in a diagram that is easy for the head family to understand. In Python, declarations and assignments are made at the same time, so the b declaration is made at the b = a part.

Assign variables at the same time

By inserting , between variables when assigning variables, you can assign multiple variables on one line.

a, b = 10, 5

print(a)
print(b)

Execution result


10
5

The above program has the same meaning as if you wrote:

a = 10
b = 5

Variable name rules

You can basically give any variable name, but if you try to use some names as variable names, an error will occur.

Variable name not available

Names that meet the following conditions cannot be variable names.

--Names starting with a number --Names with symbols other than _ -** Keywords ** (some words used by Python)

The following is an example of a name that cannot be used as a variable name. The ʻint` used in the original example can be used as a variable name in Python (... not recommended).

100hello = 10  #Cannot be a name that starts with a number
na+me = "AtCoder"  #In the variable name+Cannot be used
not = 100  #not cannot be a variable name because it is a keyword

The following names can be variable names.

hello10 = 10  #The second and subsequent letters can be numbers
hello_world = "Hello, world"  # _Can be used for variable names
Variable 1= 1  #Chinese characters
Hensu 2= 2  #Hiragana

In the case of Python, unlike C ++, Kanji and Hiragana can also be used for variable names. A search for Python keywords will bring up a list.

Mold

There are many other types of Python besides ʻint. Only three important types are introduced here. Decimal numbers are double in C ++, but floatin Python. Similarly, the string isstr`.

Mold Type of data to write
int integer
float Decimal (real number)
str String
i = 10  #10 is an integer
f = 0.5  # 0.5 is a decimal
s = "Hello"  # "Hello"Is a string

print(i, type(i))  # type(variable) でvariableの型がわかる
print(f, type(f))
print(s, type(s))

Execution result


10 <class 'int'>
0.5 <class 'float'>
Hello <class 'str'>

Calculation between different types

** Type conversion ** is performed for calculations between different types. For example, the calculation result of int type and float type is float type.

However, ** calculations between types that cannot be converted will result in an error **.

i = 30
d = 1.5
s = "Hello"

print(i + d, type(i + d))  # 31.5
print(i * d, type(i * d))  # 45.0

"""
The following processing is an error
print(s + i)  #Addition of str type and int type
print(s + d)  #Addition of str type and float type
"""

Execution result


31.5 <class 'float'>
45.0 <class 'float'>

In case of Python, it is possible to calculate str type * int type.

i = 5
s = "Hello"

print(s * i)  # "Hello" * 5 → ???

What are the results of the above program? Let's see the execution result.

Execution result


HelloHelloHelloHelloHello

" Hello " is a string that is repeated 5 times.

Assignment between different types

In Python, the type of a variable depends on what's inside. Therefore, the following program works normally.

i = 10
s = "Hello"

i = s

print(i)
print(type(i))

Execution result


Hello
<class 'str'>

problem

You can find the problem statement at the link below. EX4. ◯ How many seconds is the year?

Sample program


#Number of seconds in a year
seconds = 365 * 24 * 60 * 60

#The following comments""" """Erase and add
print("""How many seconds a year""")
print("""2 years is a few seconds""")
print("""How many seconds is 5 years""")
print("""How many seconds is 10 years""")

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.05. Execution order and input

Key Point

--Programs are executed in order from top to bottom --You can receive input with variable = input () --Entered separated by spaces and line breaks

Program execution order

Basically ** programs are executed in order from top to bottom **.

Take a look at the following program.

name = 10

print(name)  # 10

name = 5

print(name)  # 5

Execution result


10
5

The basic structure is the same as the original one, so please refer to the original slide for the execution.

input

Let's see how to receive data input when the program runs. By using the "input function", you can perform various calculations without rewriting the program.

Use ʻinput ()` to receive input. The following program is a program that multiplies the numerical value received as input by 10 and outputs it.

a = int(input())

print(a * 10)

input


5

Execution result


50

ʻInput ()takes one line of input as a string. Therefore, in order to receive it as an int type, it must be converted to an int type by ʻint ().

a = input()

print(a, type(a))

a = int(a)  #Convert to int type

print(a, type(a))

input


5

Execution result


5 <class 'str'>
5 <class 'int'>

Input of non-integer data

If you want to receive non-integer data, you need to convert it to the required type as well.

text = input()
f = float(input())

print(text, f)

input


Hello
1.5

Execution result


Hello 1.5

Whitespace delimited input

As mentioned earlier, ʻinput ()` takes a single line of input as a string.

a = input()

print(a)
print(type(a))

input


10 20 30

Execution result


10 20 30
<class 'str'>

Therefore, if you just receive a space-separated input, it will be assigned to the variable ʻaas the string" 10 20 30 "` as shown above.

Split with whitespace

Therefore, you need to decompose the string by adding .split () after ʻinput ()`.

a, b, c = input().split()

print(a)
print(type(a))

input


10 20 30

Execution result


10
<class 'str'>

By doing this, " 10 20 30 " was separated by whitespace, and it became " 10 ", " 20 ", " 30 ".

Convert to integer

After that, if you convert it to an integer using ʻint () `as before, you can receive the input separated by spaces as an integer.

a, b, c = input().split()

a = int(a)
b = int(b)
c = int(c)

print(a)
print(type(a))

input


10 20 30

Execution result


10
<class 'int'>

In the above program, I wrote the conversion to int type every time as many as the number of variables, but you can also write this in one line.

a, b, c = map(int, input().split())

print(a)
print(type(a))

input


10 20 30

Execution result


10
<class 'int'>

By writing map (type, input (). Split ()), you can convert all the divided strings to the specified type at the same time.

Multi-line input

ʻInput ()` receives one line of input, so if there are multiple lines of input, you need to write as many lines as there are lines.

s = input()
a = int(input())

print(s, a)

input


Hello
10

Execution result


Hello 10

problem

You can find the problem statement at the link below. EX5.A Addition B problem

Sample program


#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.06. if statement / comparison operator / logical operator

Key Point

-Using ** if statement , you can write a program that "processes only when certain conditions are correct" - else clause ** can be used to write the process of "when the condition is not correct"

if conditional expression 1:
Process 1
elif conditional expression 2:
Process 2
else:
Process 3

--Comparison operator

operator meaning
x == y x and y are equal
x != y x and y are not equal
x > y x is greater than y
x < y x is less than y
x >= y x is greater than or equal to y
x <= y x is less than or equal to y

--Logical operators

operator meaning When to be true
not conditional expression Inversion of the result of the conditional expression Conditional expression is false
Conditional expression 1 and conditional expression 2 Conditional expression 1 is true and conditional expression 2 is true Both conditional expression 1 and conditional expression are true
Conditional expression or conditional expression 2 Conditional expression 1 is true or conditional expression 2 is true At least one of conditional expression 1 and conditional expression 2 is true

if statement

By using the ** if statement **, you can write a program called ** that processes only when certain conditions are correct **. The writing method is as follows.

if conditional expression:
processing

When the ** conditional expression ** is correct, the processing of the part where the indent after : is lowered by one is executed, and when the conditional expression is incorrect, the processing is skipped.

In the following example, if the input value is less than 10, "x is less than 10" is output and then "end" is output. Also, if the input value is not less than 10, only "End" is output.

x = int(input())

if x < 10:
    print("x is less than 10")

print("End")

Input 1


5

Execution result 1


x is less than 10
End

Input 2


15

Execution result 2


End

In this example, we first enter integer data in the variable x.

x = int(input())

Then it's important.

if x < 10:
    print("x is less than 10")

This part means "if x <10 (x is less than 10), x is output less than 10". Finally, run print ("end ") to print end and the program will exit.

If x is not less than 10

    print("x is less than 10")

Processing is skipped. Therefore, in the second execution example, only end is output.

Execution of processing under some condition like an if statement is called ** conditional branch **. Also, "the conditional expression is correct" is called ** the conditional expression is true **, and "the conditional expression is incorrect" is called ** the conditional expression is false **.

Comparison operator

Python's comparison operators are the same as C ++, so refer to this section for the original.

operator meaning
x == y x and y are equal
x != y x and y are not equal
x > y x is greater than y
x < y x is less than y
x >= y x is greater than or equal to y
x <= y x is less than or equal to y

The following program is a program that outputs what conditions the input integer value meets.

x = int(input())

if x < 10:
    print("x is less than 10")

if x >= 20:
    print("x is 20 or more")

if x == 5:
    print("x is 5")

if x != 100:
    print("x is not 100")

print("End")

Input 1


5

Execution result 1


x is less than 10
x is 5
x is not 100
End

Input 2


100

Execution result 2


x is 20 or more
End

Logical operator

You can also write more complex conditions in the conditional expression. To do this, use the ** logical operator **.

operator meaning When to be true
not conditional expression Inversion of the result of the conditional expression Conditional expression is false
Conditional expression 1 and conditional expression 2 Conditional expression 1 is trueAndConditional expression 2 is true Both conditional expression 1 and conditional expression are true
Conditional expression or conditional expression 2 Conditional expression 1 is trueOrConditional expression 2 is true At least one of conditional expression 1 and conditional expression 2 is true
x, y = map(int, input().split())

if not x == y:
    print("x and y are not equal")

if x == 10 and y == 10:
    print("x and y are 10")

if x == 0 or y == 0:
    print("x or y is 0")

print("End")

Input 1


2 3

Execution result 1


x and y are not equal
End

Input 2


10 10

Execution result 2


x and y are 10
End

Input 3


0 8

Execution result 3


x and y are not equal
x or y is 0
End

Processing of "when the previous condition is not true"

else clause

By writing the ** else clause ** after the if statement, processing can be performed "when the condition of the if statement is false". The writing method is as follows.

if conditional expression 1:
Process 1
else:
Process 2

The following program prints "x is less than 10" if the input value is less than 10, otherwise it prints "x is not less than 10".

x = int(input())

if x < 10:
    print("x is less than 10")
else:
    print("x is not less than 10")

Input 1


5

Execution result 1


x is less than 10

Input 2


15

Execution result 2


x is not less than 10

elif In ʻelif`, processing is performed when" the condition of the previous if statement is false "and" the condition of elif is true "". The writing method is as follows.

if conditional expression 1:
Process 1
elif conditional expression 2:
Process 2

Process 2 is executed when "conditional expression 1 is false and conditional expression 2 is true". Let's look at an example.

x = int(input())

if x < 10:
    print("x is less than 10")
elif x > 20:
    print("x is not less than 10 but greater than 20")
elif x == 15:
    print("x is not less than 10 and not greater than 20 and is 15.")
else:
    print("x is not less than 10, not greater than 20, not 15.")

Input 1


5

Execution result 1


x is less than 10

Input 2


30

Execution result 2


x is not less than 10 but greater than 20

Input 3


15

Execution result 3


x is not less than 10 and not greater than 20 and is 15.

Input 4


13

Execution result 4


x is not less than 10, not greater than 20, not 15.

You can also write elif or else after elif, as in this example.

problem

You can find the problem statement at the link below. EX6. Let's make a calculator

Sample program


a, op, b = input().split()
a = int(a)
b = int(b)

if op == "+":
    print(a + b)

#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.07. Conditional expression result and bool type

Key Point

--The result of the conditional expression is True when it is true and False when it is false. --In the int type, True is represented by 1 and False is represented by 0. -** bool type ** is a type that contains only True and False

int type representation bool type representation
true 1 True
false 0 False

The result of the conditional expression

In Python, the truth is represented by True and the false is represented by False. Note that unlike C ++, it starts with an uppercase letter. The "calculation result" of the conditional expression is also True when it is true and False when it is false.

The following program outputs the result of the conditional expression as it is, and checks what value it takes when it is true and when it is false.

print(5 < 10)
print(5 > 10)

Execution result


True
False

If you look at the output, you can see that it is True when the condition is true and False when it is false.

True and False

In Python, true and false are usually represented by True and False, so this title may not be correct, but it fits the original.

You can also write True or False directly in the conditional expression part. The following program is an example.

#True represents true, so it is output as hello
if True:
    print("hello")

#False represents false, so this if is not executed
if False:
    print("world")

Execution result


hello

In the int type, True is represented by 1 and False is represented by 0.

print(int(True))
print(int(False))

Execution result


1
0

bool type

There is a data type called ** bool type **. Variables of this type can only contain True or False.

x = int(input())

a = True
b = x < 10  #True if x is less than 10 False otherwise
c = False

if a and b:
    print("hello")

if c:
    print("world")

input


3

Execution result


hello

In this way, if you want to handle truth data as a variable, such as the result of a conditional expression, use the bool type. Until now, it was written as ʻif conditional expression, but basically it is ʻif bool type value.

The following table summarizes the story so far.

int type representation bool type representation
true 1 True
false 0 False

Scenes using bool type

Please refer to the head family.

problem

You can find the problem statement at the link below. EX7.bool value puzzle

Sample program


#Variable a, b,Substitute True or False for c so that it is output as AtCoder
a = #True or False
b = #True or False
c = #True or False

#Do not change from here onwards

if a:
    print("At", end="")  # end=""If you write, the trailing line break will not occur
else:
    print("Yo", end="")

if (not a) and b:
    print("Bo", end="")
elif (not b) and c:
    print("Co", end="")

if a and b and c:
    print("foo!")
elif True and False:
    print("yeah!")
elif (not a) or c:
    print("der")

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.08. Scope of variables

Key Point

--The part with common indentation is called ** block ** --The range in which variables can be used is called ** scope **. --Usually, the scope of a variable is "from the time the variable is declared until the end of the block" --In the case of Python, the scope is not created by the if statement etc., and it can be used even outside the block.

Variable scope

Until now, I wrote : after the if statement and indented it on the following line. The part with this indentation is called ** block **.

The head family says "

Let's look at a concrete example.

x = 5

if x == 5:
    y = 10
    print(x + y)

print(x)
print(y)

Execution result


15
5
10

This is the same content as the program listed in the head family. Since I am dealing with C ++ at home, this is shown as an example of getting an error, but in Python it does not cause an error as above and it works fine.

See the original home for more information on scopes.

problem

You can find the problem statement at the link below. EX8. Takoyaki set

Program written by Mr. A


p = int(input())

#pattern 1
if p == 1:
    price = int(input())

#Pattern 2
if p == 2:
    text = input()
    price = int(input())

n = int(input())

print(text + "!")
print(price * n)

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.09. Composite assignment operator

Key Point

--x = x + y can be written as short as x + = y --Python has no increments or decrements

Compound assignment operator

Assignment statements where the same variable name appears twice, such as x = x + 1, can be written shorter using the ** compound assignment operator **.

The following program simply adds (1 + 2) to the variable x and outputs it.

x = 5
x += 1 + 2
print(x)  # 8

Execution result


8
x += 1 + 2

Is

x = x + (1 + 2)

Has the same meaning as.

Composite assignment operators other than + =

You can do the same for other arithmetic operators.

a = 5
a -= 2
print(a)  # 3

b = 3
b *= 1 + 2
print(b)  # 9

c = 5
c /= 2
print(c)  # 2.5

d = 5
d //= 2
print(d)  # 2

e = 5
e %= 2
print(e)  # 1

f = 3
f **= 4
print(f)  # 81

Execution result


3
9
2.5
2
1
81

Increment and decrement

C ++ has increments and decrements, but Python doesn't. If you want to know about increment, please refer to the original home.

problem

You can find the problem statement at the link below. EX9. Let's use compound assignment operator

Sample program


x, a, b = map(int, input().split())

# 1.Output of
x += 1
print(x)

#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.10.while statement

Key Point

-** While statement ** can be used for iterative processing --Repeat the process when the conditional expression is true

while conditional expression:
processing

--When writing a program that "counts $ N $ times", write it in the format "start the counter variable from 0 and loop when the counter variable is smaller than $ N $".

i = 0  #Counter variable
while i < N:
processing
    i += 1

while statement

You can use the ** while statement ** to perform "repetitive processing" (loop processing), which is very important among the functions of the program.

infinite loop

The following program is a program that repeats "the process of outputting"Hello", starting a new line, and then outputting" AtCoder "" indefinitely.

while True:
    print("Hello")
    print("AtCoder")

Execution result


Hello
AtCoder
Hello
AtCoder
Hello
AtCoder
Hello
AtCoder
Hello
AtCoder
...(Infinitely)

The while statement is written as follows, and the process is repeated when the conditional expression is true.

while conditional expression:
processing

In the previous program, True is written in the conditional expression part, so the process continues infinitely. This infinite repetition is called an ** infinite loop **.

Count one by one

The following program continues to output integers starting from 1.

i = 1

while True:
    print(i)
    i += 1  #Increase by 1 for each loop

Execution result


1
2
3
4
5
6
7
8
...(Infinitely increase by 1)

Specifying the number of loops

To change the program that counts by 1 to "a program that outputs numbers from 1 to 5", do as follows.

i = 1

#Loop only while i is 5 or less
while i <= 5:
    print(i)
    i += 1

Execution result


1
2
3
4
5

Counter variable from 0 to less than N

Consider a program that outputs " Hello " five times. First, I will introduce the uncommon writing style (writing style that should be stopped), and then the general writing style (recommended writing style).

Uncommon writing

#start i from 1
i = 1

#Loop only while i is 5 or less
while i <= 5:
    print("Hello")
    i += 1

Execution result


Hello
Hello
Hello
Hello
Hello

When writing a program that "processes $ N $ times" with a while statement, it has been written in the format of "starting ʻi` from 1 and looping for less than $ N $".

i = 1
while i <= N:
processing
    i += 1

This format may seem straightforward at first glance. However, this writing style is not very common and should be written as follows.

General writing

#start i from 0
i = 0

#Loop only while i is less than 5
while i < 5:
    print("Hello")
    i += 1

Execution result


Hello
Hello
Hello
Hello
Hello

When writing a program that "processes $ N $ times", it is common to write it in the following format ** "Start ʻi from 0 and loop when ʻi is smaller than $ N $" Target **.

i = 0
while i < N:
processing
    i += 1

It may seem confusing at first, but it will be more and more simple to write a program later, so let's get used to it.

A variable that manages the "number of loops", such as the variable ʻi in this program, is sometimes called a ** counter variable **. The counter variable basically uses ʻi, and if ʻicannot be used, it is common to name it asj, k, l`, ....

Application example

Let's create a program to find the total score of $ N $ people. The following program receives "number of inputs $ N " and " N $ integers representing points" as inputs and outputs the total points.

n = int(input())

sum = 0  #Variable representing the total score
i = 0    #Counter variable

while i < n:
    x = int(input())
    sum += x
    i += 1

print(sum)

input


3
1
10
100

Execution result


111

I have created a variable sum that represents the total score, put it in the input variable x every time I loop, and add it to sum. There is a slide explaining the processing contents to the head family.

problem

You can find the problem statement at the link below. EX10. Output of bar graph

If you use only print (), a newline will be automatically inserted at the end, so you can use print (output content, end =" ") to prevent the newline from ending.

Sample program


a, b = map(int, input().split())

#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.11.for statement / break / continue

Key Point

-** for statement ** is a syntax for writing patterns that are common in iterative processing shorter than while statements --The contents of the column are assigned to the counter variables in order from the beginning.

for counter variable in column:
processing

--It is common to write the iterative process of $ N $ times with the following for statement.

for i in range(N):
processing

-** break ** allows you to break out of the loop -** continue ** allows you to skip later processing and go to the next loop

for statement

** for statement ** is a syntax for writing patterns that are common in iterative processing such as "process $ N $ times" shorter than while statements.

If you write a program that repeats three times with a while statement and a for statement, it will be as follows.

j = 0
while j < 3:
    print("Hello while:", j)
    j += 1

for i in range(3):
    print("Hello for:", i)

Execution result


Hello while: 0
Hello while: 1
Hello while: 2
Hello for: 0
Hello for: 1
Hello for: 2

The for statement is written as follows.

for counter variable in column:
processing

We'll talk more about columns in later sections, but there are sequences like [3, 1, 4, 1, 5] and strings like " abcdef ". Let's take a look at the following program.

for i in [3, 1, 4, 1, 5]:
    print("i:", i)

Execution result


i: 3
i: 1
i: 4
i: 1
i: 5

You can see that the contents of the list [3, 1, 4, 1, 5] are extracted from the beginning and assigned to ʻi`.

N times iterative processing

If you want to perform iterative processing such as "process $ N $ times", it is easier to use range (). Writing range (a, b) will generate a sequence of [a, a + 1, a + 2, ..., b-1].

for i in range(0, 5):  # [0, 1, 2, 3, 4]
    print(i)

Execution result


0
1
2
3
4

The ʻaofrange (a, b)can be omitted when it is 0 and can be written asrange (b)`. Therefore, the following two writing styles have the same meaning.

for i in range(0, 5):
    print(i)

for i in range(5):
    print(i)

Execution result


0
1
2
3
4
0
1
2
3
4

In other words, if you want to write "Iterate $ N $ times", you can write as follows. For now, let's start by learning this simple way of writing.

for i in range(N):
processing

Tips for using for statements

When using the for statement of "Iterate $ N $ times", do not think about the detailed operation of "assigning to the counter variable in order from the beginning of the column". Roughly speaking, it is easier to write a program that uses a for statement if you think of the ** for statement as a function that repeats processing $ N $ times while increasing $ i $ by 1.

break and continue

There are ** break ** and ** continue ** as instructions to control the while statement and for statement.

break break is an instruction to break the loop in the middle. This is an example of a program that uses break.

#Without break this loop would be i==Repeat up to 4
for i in range(5):

    if i == 3:
        print("Get out")
        break  # i ==Break out of the loop at 3

    print(i)

print("End")

Execution result


0
1
2
Get out
End

When ʻi == 3becomes true in the if statement, the for loop is exited by executing the instruction ofbreak, and end` is displayed.

continue continue is an instruction to skip the subsequent processing and go to the next loop. This is an example of a program that uses continue.

for i in range(5):

    if i == 3:
        print("Skip")
        continue  # i ==When it is 3, skip the processing after this

    print(i)

print("End")

Execution result


0
1
2
Skip
4
End

In the above program, when ʻi == 3becomes true in the if statement, the part below continue is skipped by executing the instruction ofcontinue`, and the next loop is entered.

problem

You can find the problem statement at the link below. EX11. Let's make a calculator 2

By writing print ("{} ". format (variable)) as follows, the contents of the variable will be embedded in the part of {}.

a = 1
b = "Hello"

print("{}:{}".format(a, b))  #First{}To a second{}To b

Execution result


1:Hello

Below is a sample program in question.

Sample program


n = int(input())
a = int(input())

#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.12. Character string (and characters)

Key Point

--In Python, both strings and characters are handled as ** str type ** --You can get the length of a string with len (string variable) --You can access the $ i $ character with the string variable [i] -- i of the string variable [i] `is called ** subscript ** --Subscripts start from 0 --An error will occur if the subscript value is not within the correct range

Character string (str type)

A character string is a character string that is arranged in order, such as ʻabcorhello`. C ++ distinguishes between strings and characters (length 1), but Python does not and treats both as strings (str type).

str1 = input()
str2 = ", world!"

print(str1 + str2)

input


Hello

Execution result


Hello, world!

String length

The length (number of characters) of the string can be obtained with len (string variable).

s = "Hello"
print(len(s))

Execution result


5

i-th character

You can get the $ i $ character by writing as follows.

String[i]

This ʻi` is called a ** subscript **.

Subscripts start at 0

Note that the subscripts start at 0.

s = "hello"
print(s[0])  # h
print(s[4])  # o

Execution result


h
o

s [0] gets the first character, and s [4] gets the fifth character. For the string " hello ", the correspondence between subscripts and characters is shown in the table below.

Subscript 0 1 2 3 4
letter h e l l o

Let's get used to subscripts starting from 0, just as we start loop counter variables from 0.

application

Combination with loop syntax

By combining the character string with the loop syntax, various processes can be described. The following program counts how many characters ʻO` are included in the characters entered.

s = input()

count = 0
for i in range(len(s)):
    if s[i] == "O":
        count += 1

print(count)

input


LOOOOL

Execution result


4

You can also write in Python as follows: Since the for statement looks from the beginning of the column, it also supports character strings. In the case of a character string, it looks at each character in order from the first character.

s = input()

count = 0
for i in s:
    if i == "O":
        count += 1

print(count)

input


LOOOOL

Execution result


4

important point

Out-of-range error

If the subscript value is not within the correct range, a run-time error will occur. The following program causes an error because it is trying to access the non-existent character number of [10] for a 5-character string hello (valid subscripts are 0 to 4). To do.

x = "hello"
print(x[10])

Run-time error


Traceback (most recent call last):
  File "./Main.py", line 2, in <module>
    print(x[10])
IndexError: string index out of range

Exit code


256

An error when the subscript is out of range is characterized by the error message " string index out of range " on line 4.

Handling of double-byte characters

Unlike C ++, Python can handle double-byte characters.

s = "Hello"
print(s[0])
print(s[2])

Execution result


This
To

problem

You can find the problem statement at the link below. EX12. Add or subtract

Sample program


s = input()

#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.13. List (array)

Key Point

--Python uses lists instead of arrays -** List ** is a function that can handle various columns of data --You can create a list with list variable name = [element 1, element 2, ...] --You can access the $ i $ th element with the list variable [i] --You can get the number of elements in the list with len (list variable) --By combining a list and a for statement, you can write a program that handles a large amount of data concisely. --List subscript rules are the same as strings

Lists and strings

Character strings were a function for handling "character strings". ** List ** is a very important feature that can handle not only characters but also various columns of data.

C ++ deals with arrays (vectors), while Python deals with lists (lists). The main differences are as follows.

the difference
C++Vector Only one type can be in an array
Python list You can put different types of data in one list

Strings and lists are used in the same way to some extent. The following program has a string of letters ""a","b","c","d"" and " 25, 100, 64 ". We are dealing with a sequence of integers.

#String
s = "abcd"  # "a", "b", "c", "d"Enter the character string

print(s[0])  #The first"a"Output

print(len(s))  #Outputs 4 which is the length of the string


#list
a = [25, 100, 64]  # 25, 100,Substitute an integer (int) column of 64

print(a[0])  #Output the first 25

print(len(a))  #Outputs the length of the list, 3.

Execution result


a
4
25
3

Generate list variable

The list variable is generated as follows.

List variable name= [Element 1,Element 2, ...]

Each piece of data in the list is called a ** element **. If you write ʻa = [25, 100, 64], the data string "25, 100, 64" is assigned to the list variable ʻa.

i-th element

Like strings, lists can use [i] to access the $ i $ th element.

List variable[i]

Subscripts also start at 0 in lists. For the list variable ʻa ʻa = [25, 100, 64], the table of subscript values and character correspondence is as follows:

Subscript 0 1 2
element 25 100 64

Number of elements in the list

Like strings, lists can use len () to get the number of elements (length).

len(List variable)

For the list variable ʻa with ʻa = [25, 100, 64], the value of len (a) will be 3.

Input to list

Whitespace delimited input

I used ʻinput (). split ()` in receiving space-separated input, but I'm actually receiving it as a list.

a = input().split()
print(a)

input


3 1 4 1 5

Execution result


['3', '1', '4', '1', '5']

If this is the only case, it will be received as a str type, so use map () to receive it as an int type. You can use map () to perform type conversions on all elements of the list.

a = list(map(int, input().split()))
print(a)

input


3 1 4 1 5

Execution result


[3, 1, 4, 1, 5]

If only map () is used, it will be a map object, so it is converted to a list by enclosing it with list ().

Enter line breaks

You may also want to receive newline delimited input like this:

3
1
4
1
5

In that case, first create an empty list and then add the elements in order. An empty list can be created by writing no elements.

List variable= []  #Empty list

To add an element to the list, use .append.

List variable.append(Elements to add)

By combining these with a for statement, you can receive line feed delimited input.

n = int(input())  #When the first line of input is the number of elements

a = []
for i in range(n):
    a.append(int(input()))

print(a)

Input (1st line is the number of elements)


5
3
1
4
1
5

Execution result


[3, 1, 4, 1, 5]

List usage

By combining a list and a for statement, you can write a program that handles a large amount of data. See the following example.

example

Please refer to the head family for the problem statement.

Answer example

If $ N $ is small, it is possible to solve this problem with just an int variable without using a list. However, if $ N $ is large, writing without a list can be very difficult. For example, if $ N = 1000 $, you have to declare 1000 variables.

Using a list and a for statement, you can write a process concisely regardless of the size of $ N $.

n = int(input())

#Receive math and English score data
math = list(map(int, input().split()))
english = list(map(int, input().split()))

#Output total points
for i in range(n):
    print(math[i] + english[i])

important point

Like strings, lists will result in an error if the subscript values are not within the correct range.

The following program tries to access a non-existent element with [10] against a three-element list of [1, 2, 3] (valid subscripts are 0 to 2). An error will occur.

a = [1, 2, 3]
print(a[10])

Run-time error


Traceback (most recent call last):
  File "./Main.py", line 2, in <module>
    print(a[10])
IndexError: list index out of range

Exit code


256

As with the string, the fourth line displays the error message " IndexError: list index out of range ".

Detailed story

It's a small story, so you can skip it and solve the problem.

Subscript from behind

In Python, you can see it from behind by using a minus for the subscript.

a = [1, 2, 3, 4, 5]

print(a[-1])  #First from the back
print(a[-3])  #Third from the back

Execution result


5
3

When viewed from behind, count the back as -1, the second from the back as -2, and the third as -3.

slice

In a Python list, there is an operation called ** slice ** to get a part of the list. Slices are used as follows.

List variable[Starting point subscript:End point subscript]

Starting from the subscript of the start point, the list is obtained up to the one before the subscript of the end point. If the list variable ʻais ʻa = [1, 2, 3, 4, 5], then ʻa [1: 3]becomes[2, 3]`. If the subscript is omitted, the start point is acquired from the beginning, and the end point is acquired from the end.

You can also specify the steps (how many times you want to see the slice).

List variable[Starting point subscript:End point subscript:Step]

For example, if you specify 2 for the step, you can get the element by skipping one element.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(a[::2])  #Skip one from the beginning → even number
print(a[1::2])  #Odd number

Execution result


[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]

problem

You can find the problem statement at the link below. EX13. Difference from average score

Sample program


n = int(input())

#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.14. Standard library built-in functions (STL functions)

Key Point

-** Functions ** make it easy to use the functions of a program. --A collection of functions provided by Python is called a ** standard library **. --The functions provided in the standard library are called ** built-in functions **. --You can call a function with function name (argument 1, argument 2, ...) --The value passed to the function with () is called ** argument **. --The calculation result of the function is called ** return value ** or ** return value **. --The type rules for arguments and return values are fixed, and if you make a mistake, an error will occur.

function min(a, b) max(a, b)
function Returns the smaller value of a and b(3 or more possible) Returns the larger value of a and b(3 or more possible)
function sorted(list) reversed(list)
function Sort the list (sort the elements in ascending order) Reverse the order of the elements in the list

Built-in functions

** Functions ** make it easy to use the functions of a program.

How to use the function

Let's take "a program that outputs the smaller of the values of two variables" as an example.

When writing without using a function, it looks like this:

a = 10
b = 5

if a < b:
    answer = a
else:
    answer = b

print(answer)

Execution result


5

If you use the "min function", you can write as follows.

a = 10
b = 5

answer = min(a, b)  #min function

print(answer)

Execution result


5

The min that appears in the program is a function that finds the smaller of the two values. Since the smaller value of ʻaandb can be obtained as the" calculation result "of min (a, b) , it is assigned to the variable ʻanswer.

What is the standard library?

In addition to min, Python has various functions, and you can use many functions without writing your own program. A collection of functions, etc. provided by Python is called a ** Standard Library **. The functions provided in the standard library are called ** built-in functions **.

You can also create your own functions. This will be explained in "1.15. Functions".

How to call a function

Using a function is called ** function call **.

The notation of the function call is as follows.

Function name(Argument 1,Argument 2, ...)

** Arguments ** are the values you pass to the function. In min (a, b), the variable a and the variable b correspond to it. The min function had two arguments, but the number of arguments depends on the function.

The value of the calculation result of the function is called ** return value (return value) ** or ** return value (return value) **. ʻAnswer = min (a, b)` assigns the return value of the min function to the variable answer.

Argument and return type

The type rules for arguments and return values are determined by the function, and if you make a mistake, an error will occur.

The following program is getting an error trying to pass an int and string type as arguments to the min function.

s = "hello"

a = min(10, s)

print(a)

error


Traceback (most recent call last):
  File "./Main.py", line 3, in <module>
    a = min(10, s)
TypeError: unorderable types: str() < int()

Function example

I will introduce two of the built-in functions. ** You don't have to memorize these **, but it's important to remember and look up, "I feel like this process was done with a built-in function."

min function

The min function returns the smallest of the arguments. It also supports 3 or more arguments.

answer = min(10, 5)

print(answer)  # 5

Execution result


5

Argument and return type

The argument and return types can be any numeric type (or comparable type) such as ʻintorfloat`. You can also take a list as an argument.

answer = min(1.5, 3.1)

print(answer)  # 1.5

Execution result


1.5

You can also compare int type and float type.

a = 1.5
print("a:", type(a))

b = 10
print("b:", type(b))

answer = min(a, b)

print(answer)  # 1.5

Execution result


a: <class 'float'>
b: <class 'int'>
1.5

max function

The max function returns the largest of the arguments. It also supports 3 or more arguments.

answer = max(10, 5)

print(answer)  # 10

Execution result


10

Argument and return type

The argument and return types are the same as min.

Function that takes a list as an argument

Here are two built-in functions that pass a list as an argument.

reversed function

You can use the reversed function to reverse the order of the elements in a list.

a = [1, 5, 3]

a = list(reversed(a))  # [3, 5, 1]

print(a)

Execution result


[3, 5, 1]

Since the iterator is returned, I am converting it to a list using list ().

You can also get a list in reverse order by using slices.

a = [1, 5, 3]

a = a[::-1]

print(a)

Execution result


[3, 5, 1]

sorted function

Sorting the data columns in order is called ** sorting **. You can use the sorted function to sort the elements of the list in ascending order.

a = [2, 5, 2, 1]

a = sorted(a)  # [1, 2, 2, 5]

print(a)

Execution result


[1, 2, 2, 5]

Also, the sorted function can be sorted in descending order by specifying reverse = True as the second argument.

a = [2, 5, 2, 1]

a = sorted(a, reverse=True)  # [5, 2, 2, 1]

print(a)

Execution result


[5, 2, 2, 1]

sum function

The sum function returns the sum of all the elements in the list of arguments.

a = [2, 5, 2, 1]

print(sum(a))

Execution result


10

problem

You can find the problem statement at the link below. EX14. Height difference between the three brothers

Sample program


a, b, c = map(int, input().split())

#Add the program here

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

1.15. Functions

Key Point

--Creating a function is called ** defining ** a function

def function name(Name of argument 1,Name of argument 2, ...):
processing

--The return value of the function is specified by return return value using the ** return statement **. --It is possible not to write the return value of the function --If you don't need function arguments, just write () in the definition and call --The processing of the function ends when the processing reaches the line of the return statement. --The value passed to the argument is basically copied

function

Creating a function is called ** defining ** a function.

The following example defines a function my_min that has similar functionality to the built-in min function.

#Function definition
def my_min(x, y):
    if x < y:
        return x
    else:
        return y


answer = my_min(10, 5)
print(answer)

Execution result


5

Function behavior

There is a slide in the head family that explains the operation of the entire program.

Function definition

The function is defined before the line that calls the function.

The notation of the function definition is as follows.

def function name(Name of argument 1,Name of argument 2, ...):
processing

As we saw in the previous section, the argument is the "value to pass to the function" and the return value is the "value of the result of the function".

The my_min function takes two arguments, so the definition looks like this:

def my_min(x, y):
    

The calling method is the same as the built-in function. If you call it as follows, the argument x is assigned 10 and the argument y is assigned 5.

my_min(10, 5)

Specifying the return value

The return value of the function is specified by the ** return statement **.

return Return value

The my_min function returns the smaller of the two arguments x and y, so write:

if x < y:
    return x
else:
    return y

Function with no return value

Sometimes there is no return value for the function. In that case, you don't need to write a return statement.

def hello(text):
    print("Hello, " + text)


hello("Tom")
hello("Python")

Execution result


Hello, Tom
Hello, Python

Function with no arguments

If you don't need function arguments, just write () in the definition and call.

def int_input():
    x = int(input())
    return x


num = int_input()
print(num, type(num))

input


10

Execution result


10 <class 'int'>

Why define the function yourself

Please refer to the head family.

important point

Return statement behavior

The processing of the function ends when the processing reaches the return statement.

It doesn't matter if there are multiple return statements in one function, but be aware that the processing written after the return statement will not be executed.

In the following program, the line following the output of " Hello, " writes return, so no further processing is performed.

def hello():
    print("Hello, ", end="")
    return  #Only run up to this line

    print("world!")
    return


hello()

Execution result


Hello, 

Arguments are copied

As with assigning values to other variables, the value passed to the argument is basically copied.

The add5 function in the following program adds 5 to the argument in the function, but the value of the calling variable num does not change.

def add5(x):
    x += 5
    print(x)


num = 10
add5(num)

print(num)

Execution result


15
10

The range in which the function can be called

Functions can only be called after the declared line.

In the following program, the error occurs because the hello function is called before the line that defines the hello function.

hello()


def hello():
    print("hello!")

error


Traceback (most recent call last):
  File "./Main.py", line 1, in <module>
    hello()
NameError: name 'hello' is not defined

Since it is read and executed in order from the top, at the time of the first line, an error "hello function is not defined yet" is displayed.

problem

You can find the problem statement at the link below. EX15. Present for three brothers

Program written by Mr. A


#A function that calculates and returns the total score from a list that represents the score of one test
#Argument scores: scores[i]Contains the score of the i-th test
#Return value:Total score of one test
def sum_scores(scores):
    #Add the program here


#A function that calculates and outputs the gift budget from the total points of three people
#Argument sum_a:Total score of Mr. A's test
#Argument sum_b:Total score of Mr. B's test
#Argument sum_c:Total score of Mr. C's test
#Return value:None
def output(sum_a, sum_b, sum_c):
    #Add the program here


# ---------------------
#Do not change from here
# ---------------------

#A function that takes input with one line of integers separated by spaces, puts it in a list, and returns it.
#Argument s:One line of input with integers separated by spaces
#Return value:List of input received
def list_int_input(s):
    a = list(map(int, s.split()))
    return a


#Receive N number of subjects
n = int(input())

#Receive points for each test
a = list_int_input(input())
b = list_int_input(input())
c = list_int_input(input())

#Output gift budget
output(sum_scores(a), sum_scores(b), sum_scores(c))

Answer example

** Be sure to try the problem yourself before you see it. ** ** Answer example

in conclusion

This is the end of Chapter 1. This article has covered only Chapter 1 of APG4b. If I feel like it, I will write about Chapter 2 and beyond.

As I wrote at the beginning, I will delete this article if there is a problem.

Recommended Posts

Introduction to Python (Python version APG4b)
[AWS SAM] Introduction to Python version
Introduction to Python language
Introduction to OpenCV (python)-(2)
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
How to change Python version
An introduction to Python Programming
Introduction to Python For, While
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
How to get the Python version
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python] Let's use pandas
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
Introduction to image analysis opencv python
[Introduction to Python] Let's use pandas
An introduction to Python for non-engineers
Python version to get unused ports
Introduction to Python Django (2) Mac Edition
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Python Tutorial] An Easy Introduction to Python
Introduction to MQTT (Introduction)
Introduction to Scrapy (1)
[Introduction to Udemy Python3 + Application] 18. List methods
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
Introduction to Scrapy (3)
Updated to Python 2.7.9
[Introduction to Udemy Python3 + Application] 28. Collective type
[Introduction to Python] How to use class in Python?
Introduction to Supervisor
Introduction of Python
Introduction to Tkinter 1: Introduction
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
[Introduction to Udemy Python3 + Application] 33. if statement
[Introduction to Udemy Python3 + Application] 13. Character method
[Introduction to Udemy Python3 + Application] 48. Function definition
A super introduction to Python bit operations
[Introduction to Udemy Python 3 + Application] 10. Numerical values
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
[Introduction to Udemy Python3 + Application] 21. Tuple type
Introduction to PyQt
[Introduction to Udemy Python3 + Application] 45. enumerate function
Introduction to Scrapy (2)
[Introduction to Udemy Python3 + Application] 41. Input function
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Udemy Python3 + Application] 17. List operation