23
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python文字列比較 / '=='と'or'じゃなくて'リスト'と'in'を使うんだ

Posted at

python文字列比較

引数の中身が'range'か'r'だったときにこの出力
引数の中身が'ladder'か'l'だったときにあの出力

っていうのをやりたくて
文字列比較で条件分岐しようとしたんだけど

def function1(mode):
	if mode == ('range' or 'r'):
		x=1
	elif mode == ('ladder' or 'l'):
		x=2
	return x
print(function1('r'))


'''実行結果
Traceback (most recent call last):
    print(function1('r'))
    return x
UnboundLocalError: local variable 'x' referenced before assignment
'''

orじゃ反応してくれないのかな?
==の前後逆にしてみたけど

def function2(mode):
	if ('range' or 'r') == mode :
		x=1
	elif ('ladder' or 'l') == mode :
		x=2
	return x
print(function2('r'))


'''実行結果
Traceback (most recent call last):
    print(function2('r'))
    return x
UnboundLocalError: local variable 'x' referenced before assignment
'''

どうすりゃいいんだ(・ω・`)
・・・と、思い立ってリストとin演算子を使ってみた。

def function3(mode):
	if mode in ['range' ,'r']:
		x=1
	elif mode in ['ladder' ,'l']:
		x=2
	return x
print(function3('r'))

'''実行結果
1
'''

うまくいきました
ぱっと調べて出てこなかったから誰か困るかもと思ってぱっと書いておく

python的にはメモするのも恥ずかしいくらいすごく基本的なことかもしれないね(・ω・`)

ちなみに比較演算子でisっていうのもあるけど、これは「オブジェクトがそれ自体を指しているのか?」みたいな意味らしくてもっと狭い使い方だそうな。

23
19
6

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
23
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?