Pythonで単一変数と複数変数を出力しますか?
このセクションでは、2つの異なるPythonバージョンでの単一変数と複数変数の出力の出力を確認します。
#Python 2.7
単一変数の印刷
>>> #Python 2.7
>>> #Print single variable
>>> print 27
27
>>> print "Rahul"
Rahul
>>> #Print single variable, single brackets
>>> print(27)
27
>>> print("Rahul")
Rahul Python 3.6
>>> #Python 3.6 >>> #Print single variable without brackets >>> print 27 SyntaxError: Missing parentheses in call to 'print' >>> print "Rahul" SyntaxError: Missing parentheses in call to 'print'
上記の3.6の構文は、次の理由によるものです。python 3.xでは、printはステートメントではなく、関数(print())です。したがって、printはprint()に変更されます。
>>> print (27)
27
>>> print("Rahul")
Rahul 複数の変数を出力する
Python 2.x(例:python 2.7)
>>> #Python 2.7
>>> #Print multiple variables
>>> print 27, 54, 81
27 54 81
>>> #Print multiple variables inside brackets
>>> print (27, 54, 81)
(27, 54, 81)
>>> #With () brackets, above is treating it as a tuple, and hence generating the
>>> #tuple of 3 variables
>>> print ("Rahul", "Raj", "Rajesh")
('Rahul', 'Raj', 'Rajesh')
>>> したがって、上記の出力から、Python 2.xで、角かっこ()内に複数の変数を渡すと、複数のアイテムのタプルとして扱われることがわかります
Python 3.x(例:python 3.6)
#Python 3.6
#Print multiple variables
>>> print(27, 54, 81)
27 54 81
>>> print ("Rahul", "Raj", "Rajesh")
Rahul Raj Rajesh python2.xとpython3.xの複数のステートメントの別の例を見てみましょう
-
Python例外メッセージをキャプチャして出力する方法は?
Python例外メッセージは、以下の2つのコード例に示すように、さまざまな方法でキャプチャおよび印刷できます。最初の例では、例外オブジェクトのメッセージ属性を使用します。 例 try: a = 7/0 print float(a) except BaseException as e: print e.message 出力 integer division or modulo by zero 指定されたコードの場合、sysモジュールをインポートし、sys.exc_value属性を使用して例外メッセージをキャプチャして出力します。 例 import sys def catchEverything(
-
Python変数が存在するかどうかを確認するにはどうすればよいですか?
次のコードを使用して、Pythonに変数が存在するかどうかを確認します。 例 x =10 class foo: g = 'rt' def bar(self): m=6 print (locals()) if 'm' in locals(): print ('m is local variable') else: print ('m is not a local variable') f = foo() f.bar() print (globals()) if hasattr(f, 'g'): print ('