LoginSignup
0
0

More than 3 years have passed since last update.

if True >= False: Python「True」 Go「は???」

Posted at

$\huge{True >= False}$
  何だこれ……

TL;DR

Python3
arr = ['りんご', 'ごりら', 'らっぱ']
print(arr[False])
# りんご
print(arr[True])
# ごりら

気持ち悪いが過ぎる

はじめに

バーチャルエンジニアの星野ニアです。
この記事は星野ニア Advent Calendar 2020 の 17日目(の記事の感想文)です。正しくは記事中に出てきた True >= False という一文に対するプログラム処理上の疑問の解決です。

Pythonの条件分岐はTrue

Python3
if True >= False:
    print('True')
else:
    print('False')
# True

どうして

Python の Bool 型は整数のサブクラスとして実装されているので
1 >= 0 扱いで True が返ってきます。
Boolean オブジェクト — Python 3.9.1 ドキュメント
Falseで割るとZeroDivisionErrorが返ってくる

print(str(True + False));
# 1
print(str(True + True));
# 2
print(str(False + False));
# 0
print(True / False)
# ZeroDivisionError: division by zero

他の言語の場合

型付けゆるふわ言語筆頭 Javascript: true
Javascriptの0除算結果はInfinityになる

Javascript
console.log(true >= false);
// true
console.log(true);
// true
console.log(true + true);
// 2
console.log(true + false);
// 1
console.log(true / false);
// Infinity

静的型付け Golang : operator >= not defined on bool
 振る舞いとしては本当に正しい

Go
package main
import "fmt"
func main(){
    if true >= false{
        fmt.Println("true")    
    }else{
        fmt.Println("false")
    }
    // invalid operation: true >= false (operator >= not defined on bool)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0