[Introduction to Python3 Day 3] Chapter 2 Py components: Numbers, strings, variables (2.2-2.3.6)

2.2 Numerical value

Python has built-in support for integers (numbers without a decimal point, such as 5 and 10000000), immovable decimal numbers (3.12121, 14.99, 1.32e3, etc.), and imaginary numbers.

2.2.1 Integer

Four arithmetic operations.

>>> 5
5
>>> 0
0

#Do not put a zero in front of the number.
>>> 09
  File "<stdin>", line 1
    09
     ^
SyntaxError: invalid token  
>>> 123
123
>>> +123
123
>>> -123
-123
>>> 5+9
14
>>> 100-7
93
>>> 4-10
-6
>>> 5+9+3
17
>>> 4+3-2-1+6
10
>>> 6*7
42
>>> 7*7
49
>>> 6*7*2*3
252

#Floating point number (decimal) division
>>> 9/5  
1.8

#Integer (truncate) division
>>> 9//5  
1
>>> 9/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 9//0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

It's the same rule as C language, so I'd like to omit it. .. ..

>>> a=85
>>> a
85
>>> a-5
80
>>> a
85
>>> a=a-3
>>> a
82
>>> a
82
>>> a=95
>>> a-=3
>>> a
92
>>> a +=8
>>> a
100
>>> a *=3
>>> a
300
>>> a/=3
>>> a
100.0
>>> a=12
>>> a=13
>>> a//=4
>>> a
3
>>> 9%5
4

 #You can get the (truncated) quotient and the surplus together
>>> divmod(9,5) 
(1, 4)

2.2.2 Priority

As with other languages, multiplication and division have higher priority than addition and subtraction.

>>> 2+3*4
14
>>> 2+(3*4)
14

2.2.3 Cardinal

Integers are considered decimal (radix 10) unless the prefix specifies a radix.

The radix indicates how many numbers can be used until "carrying". For ex.binary, the numbers are only 0 and 1. 0 has the same meaning as decimal 0, and 1 has the same meaning as decimal 1 but adding 1 to 1 gives 10 (1 decimal number 2 and 0 1).


#In the case of a binary number, it means 1 decimal number 2 and 0 1
>>> 0b10  
2 

#In the case of decimal numbers, it means 1 decimal number 8 and 0 decimal numbers 1.
>>> 0o10  
8

#For hexadecimal numbers, it means 1 decimal number 16 and 0 decimal numbers 1.
>>> 0x10  
16

2.2.4 type conversion

int () function

Used when converting a non-integer data type in Python to an integer. Leave only the integer part and truncate the decimal part.

>>> int(True)
1
>>> int(False)
0
>>> int(98.6)
98
>>> int(1.0e4)
10000
>>> int('99')
99
>>> int(''-213)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> int('-123')
-123
>>> int(12345)
12345

#An error occurs when trying to convert something that does not look like a number
>>> int('9aaaaaa')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '9aaaaaa'  
>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> int('98.6')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '98.6'

#Does not process strings containing exponents or floating point numbers.
>>> int('1.9e2')  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.9e2'
>>> 4+7.4
11.4

#True is 1 or 1.Treated as 0
>>> True +2
3 

#False is 0 or 0.Treated as 0
>>> False+3.5
3.5  

How big is 2.2.5 int?

Can represent numbers larger than 64-bit. (Any size is OK)

2.2.6 Floating point number

Integers are numbers that do not have a decimal point, but floating point numbers have a decimal point.

>>> float(True)
1.0
>>> float(False)
0.0
>>> float(45)
45.0
>>> float('45')
45.0
>>> float('98.6')
98.6
>>> float('-1.2')
-1.2
>>> float('2.0e5')
200000.0

2.3 String

Python strings are immutable and cannot be rewritten on the fly. However, it is possible to copy a part of a character string to another character string.

2.3.1 Created with quotes

The interactive interpreter adds a single quote when echoing a string, but Python treats it exactly the same regardless of which quote you use.

>>> 'Snap'
'Snap'
>>> 'Crackle'
'Crackle'
>>> "Crackle"
'Crackle'
>>> "'Ue'mura"
"'Ue'mura"
>>> '"Ue"mura'
'"Ue"mura'
>>> ''
''
>>> """"""
''  #Empty string

2.3.2 Type conversion using str ()

You can use the str () function to convert other Python data types to strings. Python internally calls the str () function when a print () call is made with an object that is not a string as an argument or when a string is expanded.

>>> str(98.6)
'98.6'
>>> str(1.9e4)
'19000.0'
>>> str(True)
'True'

Escape with 2.3.3 \

Python escapes some characters in a string to achieve effects that are difficult to express in other ways.


#\n means line break
>>> palindorome = "A man,\nA plan,\nA canal:\nPanama" 
>>> print(palindorome)
A man,
A plan,
A canal:
Panama

#\t is used to align the text
>>> print('\tabc')  
	abc
>>> print('a\tbc')
a	bc
>>> print('abc\t')
abc

#If you want to use quotes in the string, before them\Enter.
>>> testimony = "\"I did nothing! \""  
>>> print(testimony)
"I did nothing! "
>>> testimony = "I did nothing! \\"
>>> print(testimony)
I did nothing! \

2.3.4 + connection

You can concatenate literal strings and string variables by using the + operator as shown below.

>>> 'a' + "a"
'aa'
#In the case of literal strings, you can concatenate them just by arranging them in order.
>>> 'a'  "a"  
'aa'
>>> a="Duck."
>>> b=a
>>> c="Great Duck."

#No space
>>> a+b+c
'Duck.Duck.Great Duck.'  

#Space is automatically entered
>>> print(a,b,c)
Duck. Duck. Great Duck.  

2.3.5 * Repeat

You can use the * operator to repeat a string.

>>> start ="Na" * 4 + "\n"
>>> start 
'NaNaNaNa\n'
>>> middle="Hey" * 3 + "\n"
>>> middle
'HeyHeyHey\n'
>>> end = "goobye."
>>> print(start + start + middle + end)
NaNaNaNa
NaNaNaNa
HeyHeyHey
goobye.

2.3.6 Extracting characters with []

When you want to extract one character in a character string, add the offset of the character enclosed in square brackets ([]) after the character string name. How to count the offset The first (leftmost) offset is 0, to the right is 1 ... The (rightmost) offset of the last character is -1, to the left is -2 ....

>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[0]
'a'
>>> letters[-1]
'z'
>>> letters[-2]
'y'
>>> letters[25]
'z'
>>> letters[4555]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

IndexError: string index out of range # If you specify an offset greater than the length of the string, an error will occur. (Remember that the offset ranges from ["0" to "length-1".)


#Since the string is immutable, you cannot insert characters directly into the string or rewrite the character at the specified index position.
>>> name="Henny"
>>> name[0]=P  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'P' is not defined
>>> name[0]='P'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

#String function replace()And slice combinations should be used.
>>> name.replace('H','P') 
'Penny'
>>> 'P'+name[1:]
'Penny'

Impressions

Most of this chapter has also been learned in C language. Let's do our best tomorrow.

References

"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"

Recommended Posts

[Introduction to Python3 Day 3] Chapter 2 Py components: Numbers, strings, variables (2.2-2.3.6)
[Introduction to Python3 Day 2] Chapter 2 Py Components: Numbers, Strings, Variables (2.1)
[Introduction to Python3 Day 4] Chapter 2 Py Components: Numbers, Strings, Variables (2.3.7-2.4)
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python3 Day 8] Chapter 4 Py Skin: Code Structure (4.1-4.13)
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
[Introduction to Python3 Day 7] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.3-3.8)
[Introduction to Python3 Day 6] Chapter 3 Py tool lists, tuples, dictionaries, sets (3.2.7-3.2.19)
[Introduction to Python3 Day 22] Chapter 11 Concurrency and Networking (11.1 to 11.3)
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Introduction to Python3 Day 23] Chapter 12 Become a Paisonista (12.1 to 12.6)
[Introduction to Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python3 Day 10] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.4-5.7)
[Introduction to Python3 Day 9] Chapter 5 Py's Cosmetic Box: Modules, Packages, Programs (5.1-5.4)
[Introduction to Udemy Python3 + Application] 11. Character strings
Introduction to Effectiveness Verification Chapter 1 in Python
Introduction to effectiveness verification Chapter 3 written in Python
Introduction to Effectiveness Verification Chapter 2 Written in Python
Introduction to Python language
Introduction to OpenCV (python)-(2)
[Chapter 5] Introduction to Python with 100 knocks of language processing
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
[Chapter 4] Introduction to Python with 100 knocks of language processing
Introduction to Python Django (2) Win
Introduction to serial communication [Python]
Display numbers and letters assigned to variables in python print
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
Introduction to Python For, While
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy
Python learning memo for machine learning by Chainer Chapter 10 Introduction to Cupy
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 1
[Introduction to Udemy Python3 + Application] 12. Indexing and slicing of character strings
Python learning memo for machine learning by Chainer Chapter 9 Introduction to scikit-learn
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 2
[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 Udemy Python 3 + Application] 57. Decorator
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python] Let's use pandas
[Python] Convert natural numbers to ordinal numbers
Convert decimal numbers to n-ary numbers [python]
[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