You will be an engineer in 100 days ――Day 25 ―― Python ―― Basics of Python language 2

Today is a continuation of the Python language

Click here for the last time

You will be an engineer in 100 days-Day 24-Python-Basics of Python language 1

index

I'm sorry if it doesn't appear

What is the index in the program? It is a number that represents that.

You can do various things in your program by using indexes.

** Index notation **

[] Enclose in square brackets and enter a number in it

[5]

Character index example

print('First step'[5])

Ayumu

Because the character string is data consisting of multiple characters You can retrieve the characters of the index number.

** How to count indexes **

Since the index starts with 0

If you want to take the first character of a string, the index is 0 If you want to take the second, the index will be 1

The nth index value is n-1 Be careful as it will be off by one

If you want to specify the last character, you can specify it with -1 If you add a minus, you can count from the end.

#the first
print('AIUEO'[0])

#The second
print('AIUEO'[1])

#last
print('AIUEO'[-1])

#Third from the end
print('AIUEO'[-3])

Ah I O U

Also Specifying an index value that does not exist will result in an error.

print('AIUEO'[7])

IndexError Traceback (most recent call last) in () ----> 1 print ('aiueo' [7]) IndexError: string index out of range

ʻIndex Error is an error that occurs when the index value is out of range. What is ʻindex out of range? It means that the index value refers to a value that does not exist.

The index must always specify an existing value.

slice

Using indexes in Python There is a function that can retrieve data by specifying a range We call it a "slice".

How to write a slice:

[n: m] nth to mth [n:] nth and subsequent [: n] up to nth [n: m: o] Skip o from nth to mth

#3rd to 5th
print('Aiue Okaki'[2:5])

#Second and subsequent
print('Aiue Okaki'[1:])

#Up to 3rd
print('Aiue Okaki'[:3])

#From the beginning to the last one
print('Aiue Okaki'[0:-1])

#Skip one from the beginning to just before the last one
print('Aiue Okaki'[0:-1:2])

Ueo Iue Okaki Ah Aiueoka Auoo

variable

I'm sorry if it doesn't appear

The program has a function to reuse the input data. That is the concept of variables.

By using variables, you can reuse the entered data.

** Variable declaration and value assignment **

Variable name = value

= Is an operator that represents assignment (assignment operator) Substitute the right side to the left side of =.

a = 12345
b = 23456

If the numbers match, multiple declarations and assignments can be made at the same time.

a,b,c = 4,5,6
d,e,f = '10','20','30'

** Characters that can be used in variable names **

ʻA --zalphabet (uppercase and lowercase) Numbers up to0-9 _` (underscore)

Variable names can be anything because you can think of them yourself. It is better to give a name considering what kind of data is stored in it.

In this lecture at the underscore We recommend using two or more English words.

#Example:
magic_spell_name
attack_point

Note that the variable name does not correspond to the reserved word or built-in function name. You can attach anything.

For reserved words etc., see the next section.

** How to use variables **

After declaring it, you can use it by entering the variable.

#Substitute the numerical value 12345 for the variable a
a = 12345
#Substitute the numerical value 23456 for the variable b
b = 23456
#Output the result of adding variables a and b
print(a + b)

35801

#Variable c to a+Substitute the result of b
c = a+b
#result
print(c)

35801

Assigning a value to the same variable name will overwrite it.

#Substitute the numerical value 123 for the variable a
a = 123
print(a)

#Substitute the number 234 for the variable a
a = 234
print(a)

123 234

a,b = 12345,23456
print(a)
print(b)

# a +Substitute the result of b into a again(Overwrite)
a = a+b
print(a)

12345 23456 35801

The shape of the data is also important in the program. Letters and numbers cannot be calculated together.

a = 'letter'
b = 1
print(a + b)

TypeError Traceback (most recent call last) in () 1 a ='character' 2 b = 1 ----> 3 print(a + b) TypeError: Can't convert 'int' object to str implicitly

TypeError: Because the data shapes of variables a and b are different This is an error that means that it cannot be calculated (cannot be converted).

Since the data type is different between the number type and the character type, they cannot be combined.

** Confirmation of data shape **

Check the data type of a variable using the type function

type (variable name)

#Variables a and c are numbers, b is a string
a,b,c = 1 , '3' , 4
print(type(a))
print(type(b))
print(type(c))

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

ʻIntis an integer type str` is a word that represents the type of a string.

What is stored in a variable is also called an "object". Variable = Data type = Object So let's remember the names and concepts.

Reserved word

I'm sorry if it doesn't appear

The reserved word has been used in advance in the program. A word that has a special meaning in the program.

** List of reserved words **

#List reserved words
__import__('keyword').kwlist
False
None
True
and
as
assert
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

There are only these reserved words in Python. This reserved word cannot be used for variable names or function names.

If you use the reserved word on the jupyter notebook The display will change to green, so you should be aware of it.

for in with
スクリーンショット 2020-04-14 18.14.14.png

** List of built-in functions **

#Show built-in functions
dir(__builtins__)
ArithmeticError
AssertionError
AttributeError
BaseException
BlockingIOError
BrokenPipeError
BufferError
BytesWarning
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
DeprecationWarning
EOFError
Ellipsis
EnvironmentError
Exception
False
FileExistsError
FileNotFoundError
FloatingPointError
FutureWarning
GeneratorExit
IOError
ImportError
ImportWarning
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
KeyboardInterrupt
LookupError
MemoryError
NameError
None
NotADirectoryError
NotImplemented
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
PermissionError
ProcessLookupError
RecursionError
ReferenceError
ResourceWarning
RuntimeError
RuntimeWarning
StopAsyncIteration
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TimeoutError
True
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
__IPYTHON__
__build_class__
__debug__
__doc__
__import__
__loader__
__name__
__package__
__spec__
abs
all
any
ascii
bin
bool
bytearray
bytes
callable
chr
classmethod
compile
complex
copyright
credits
delattr
dict
dir
divmod
dreload
enumerate
eval
exec
filter
float
format
frozenset
get_ipython
getattr
globals
hasattr
hash
help
hex
id
input
int
isinstance
issubclass
iter
len
license
list
locals
map
max
memoryview
min
next
object
oct
open
ord
pow
print
property
range
repr
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
tuple
type
vars
zip

If you use this for the variable name, the function of the function will be It will be overwritten with a variable and the function will not be usable.

If you make a mistake, restart your notebook.

By declaring the variable name with two or more English words It is recommended because it can avoid such problems.

#Example:
magic_spell_name
attack_point

Data type

I'm sorry if it doesn't appear

Data handled in the program language has data types How to write is decided. Even when handling with variables, it is necessary to write according to the data type.

** How to find out Python data types **

Use the type function type (data type)

** Integer type **

A type for handling integer values Also called ʻint` type (abbreviation for integer) A data type that can perform four arithmetic operations.

num = 1234
print(type(num))

<class 'int'>

In the program, if you write a normal number, it will be interpreted in decimal. You can also use 2,8,hexadecimal notation.

Precede the number with the following 0b binary notation 0o octal 0xhexadecimal

#Binary
num = 0b11000100
print(num)

#Octal
num = 0o777
print(num)

#Hexadecimal
num = 0xffff
print(num)

196 511 65535

Decimal notation counts from 0 to 9 and goes up to 10 to carry one digit. The binary system is 0, 1 and counts two and moves up. Octal is carried up from 0 to 7 If you go from 0 to 9 in hexadecimal, then go to abcdef in English It is to move up.

** Decimal type **

Integer type cannot handle decimal point Decimal type can also handle decimal point. Also called floating point type or float type.

num = 1.234
print(type(num))

<class 'float'>

You can also use exponential notation.

Exponential notation is a numerical value with the alphabetic letter ʻe` to represent the nth power.

ʻE3represents 10 to the 3rd power, and if-` is added, it becomes -nth power.

# 1.2 to 10 3
num = 1.2e3
print(type(num))
print(num)

# 1.2 of 10-3rd power
num = 1.2e-3
print(num)

<class 'float'> 1200.0 0.0012

Note that even if the number is the same, the integer type and the decimal type have different shapes. The calculation result of decimal type and integer type is decimal type.

#Integer divide integer
print(10/4)
#Integer divide integer(Not too much)
print(10//4)
#Integer divide decimal
print(10//4.0)
#Decimal to decimal
print(12.3/4.0)

2.5 2 2.0 3.075

** Logical type **

A type for handling boolean values It is also called bool type for short for boolean. It is a type that contains either a value of True or False.

answer = True
print(answer)
print(type(answer))

True <class 'bool'>

The judgment result of the calculation is bool type.

You can use == to determine if the left and right sides of == are equal.

1==2

False

If it is judged whether they are equal, if it is correct, True If it is not correct, the result will be False.

** String type **

It is a type for handling character strings and is also called string type. The string (str) is " double quotes Or you must enclose it in 'single quotes.

#String type
print(type('12345'))

#This is a numerical value
print(type(12345))

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

If you write the number as it is, it will be an integer type or a decimal point type. If you want to treat it as a character string, you need ' etc.

** Character-to-number conversion **

When converting a character string to an integer type ʻInt ('number') `

When converting integer type or decimal type to a character string str (number)

#Convert a string to an integer type
a = '12345'
#Since the characters have been converted to numbers, it will be possible to calculate.
print(int(a) + 12345)

24690

#Convert decimal point to string
b = 2.5
#Since the number has been converted to a string, it can be added as a string.
print('Egashira' + str(b) + 'Minutes')

Egashira 2.5 minutes

** byte type **

The string " ... " or '...' that you want to treat as a byte string If you write b or B before, to indicate that it is a sequence of bytes (bytes) It is a byte type.

byte_st = b'0123456789abcdef'
print(byte_st)
print(type(byte_st))

b'0123456789abcdef' <class 'bytes'>

If b is attached, it is a byte type and is different from the character string type.

Summary

Regardless of the Python language, there are various data types in programming languages. Since the program handles data, it is necessary to write it according to the data type.

In the program, data is reused using variables. Let's keep track of how to handle variables along with the data type.

The data type that stores multiple data is Because you can use the slice function to retrieve the value using the index Let's hold down how to handle it.

Indexes are often used in many places You need to remember it early.

75 days until you become an engineer

Author information

Otsu py's HP: http://www.otupy.net/

Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw

Twitter: https://twitter.com/otupython

Recommended Posts

You will be an engineer in 100 days ――Day 24 ―― Python ―― Basics of Python language 1
You will be an engineer in 100 days ――Day 30 ―― Python ―― Basics of Python language 6
You will be an engineer in 100 days ――Day 25 ―― Python ―― Basics of Python language 2
You will be an engineer in 100 days --Day 29 --Python --Basics of the Python language 5
You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
You will be an engineer in 100 days --Day 27 --Python --Python Exercise 1
You will be an engineer in 100 days --Day 31 --Python --Python Exercise 2
You will be an engineer in 100 days --Day 63 --Programming --Probability 1
You will be an engineer in 100 days --Day 65 --Programming --Probability 3
You will be an engineer in 100 days --Day 64 --Programming --Probability 2
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
You will be an engineer in 100 days --Day 86 --Database --About Hadoop
You will be an engineer in 100 days ――Day 61 ――Programming ――About exploration
You will be an engineer in 100 days ――Day 73 ――Programming ――About scraping 4
You will be an engineer in 100 days ――Day 75 ――Programming ――About scraping 6
You will be an engineer in 100 days --Day 68 --Programming --About TF-IDF
You will be an engineer in 100 days ――Day 70 ――Programming ――About scraping
You will be an engineer in 100 days ――Day 81 ――Programming ――About machine learning 6
You will be an engineer in 100 days ――Day 82 ――Programming ――About machine learning 7
You will be an engineer in 100 days ――Day 79 ――Programming ――About machine learning 4
You will be an engineer in 100 days ――Day 76 ――Programming ――About machine learning
You will be an engineer in 100 days ――Day 80 ――Programming ――About machine learning 5
You will be an engineer in 100 days ――Day 78 ――Programming ――About machine learning 3
You will be an engineer in 100 days ――Day 84 ――Programming ――About machine learning 9
You will be an engineer in 100 days ――Day 83 ――Programming ――About machine learning 8
You will be an engineer in 100 days ――Day 77 ――Programming ――About machine learning 2
You will be an engineer in 100 days ――Day 85 ――Programming ――About machine learning 10
You will be an engineer in 100 days ――Day 60 ――Programming ――About data structure and sorting algorithm
You become an engineer in 100 days ――Day 66 ――Programming ――About natural language processing
You become an engineer in 100 days ――Day 67 ――Programming ――About morphological analysis
The basics of running NoxPlayer in Python
Become an AI engineer soon! Comprehensive learning of Python / AI / machine learning / deep learning / statistical analysis in a few days!
Basics of Python ①
Basics of python ①
Python: Deep Learning in Natural Language Processing: Basics
Basics of I / O screen using tkinter in python3
Japan may be Galapagos in terms of programming language
How to use Python Kivy ① ~ Basics of Kv Language ~
When you get an error in python scraping (requests)
How much do you know the basics of Python?
Basics of Python scraping basics
# 4 [python] Basics of functions
Basics of python: Output
If you draw an Omikuji with a probability of 1% 100 times in a row, will you win once?
A liberal arts engineer tried knocking 100 language processes in Python 02
What beginners learned from the basics of variables in python
A liberal arts engineer tried knocking 100 language processes in Python 00
Python is an adult language
Equivalence of objects in Python
python: Basics of using scikit-learn ①
Implementation of quicksort in Python
Basics of Python × GIS (Part 1)
Will the day come when Python can have an except expression?
How to know the internal structure of an object in Python
Various ways to create an array of numbers from 1 to 10 in Python.
For Python beginners. You may be confused if you don't know the general term of the programming language Collection.
[Fundamental Information Technology Engineer Examination] I wrote an algorithm for the maximum value of an array in Python.