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
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 n
th 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)
ʻ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
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 to
0-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)
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.
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
** 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 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
0x
hexadecimal
#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.
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
Otsu py's HP: http://www.otupy.net/
Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw
Twitter: https://twitter.com/otupython
Recommended Posts