Python 3エンジニア認定基礎試験~模擬試験~ 2024年11月20日 ailearn 1. 次のコードについて、obj1.class_variable = "changed"の動作として正しいものを選んでください。 class MyClass:class_variable = "shared"obj1 = MyClass()obj2 = MyClass()obj1.class_variable = "changed"print(obj2.class_variable) "changed" "shared" None エラーが発生する None 2. 変数tempが20以下なら「寒いです」と表示し、20より大きく30未満なら「快適です」と表示するコードはどれでしょうか? if temp <= 20: print("寒いです") elif temp < 30: print("快適です") if temp < 20: print("寒いです") elif temp <= 30: print("快適です") if temp < 30: print("快適です") elif temp <= 20: print("寒いです") if temp > 30: print("寒いです") elif temp < 20: print("快適です") None 3. 次のコードの実行結果を選んでください。 try:result = "text" + 5except TypeError as e:print("TypeError occurred:", e) "TypeError occurred" "TypeError occurred: can only concatenate str (not "int") to str" エラーが発生する 何も出力されない None 4. 次のコードの実行結果を選んでください。 class MyClass:def __init__(self, value):self.value = valuedef multiply(self, factor):self.value *= factorobj = MyClass(5)obj.multiply(3)print(obj.value) エラーが発生する 3 5 15 None 5. 次のコードを実行したときの出力結果は何でしょうか? def add(a, b, *args):return a + b + sum(args)print(add(1, 2))print(add(1, 2, 3, 4)) 3 6 3 10 3 15 3 9 None 6. 次のコードを実行したときの出力結果は何でしょうか? def divide(a, b=1):return a / bprint(divide(6))print(divide(6, 2)) 1.0 3.0 0.5 3.0 6 3 6.0 3.0 None 7. 次のコードについて、正しい説明を選んでください。 class MyClass:class_attribute = "shared value" class_attributeはインスタンスごとに異なる値を持つ クラス定義において属性を直接定義することはできない class_attributeは全てのインスタンスで共有されるクラス属性 クラス内で定義された属性はインスタンスメソッドからアクセスできない None 8. 次のコードについて、os.listdir()の正しい動作を選んでください。 import osprint(os.listdir(".")) スクリプトの保存先ディレクトリにあるファイルやディレクトリのリストを返す 現在の作業ディレクトリにあるファイルやディレクトリのリストを返す 指定したディレクトリ内のファイルのみを返す プロジェクトのルートディレクトリにあるファイルやディレクトリを返す None 9. 次のコードで、数値を2倍にして返す関数doubleを正しく定義する方法はどれでしょうか? def double(x): return x * 2 def double(x): print(x * 2) double(x): return x * 2 func double(x): return x * 2 None 10. 次のコードを実行した後のstackの内容は何でしょうか? stack = [1, 2, 3, 4]stack.pop()stack.append(5)stack.pop()stack.pop()stack.append(6) [1, 3, 6] [1, 2, 4] [1, 2, 6] [2, 6] None 11. 次のコードの実行結果を選んでください。 try:with open("nonexistent.txt", "r") as f:content = f.read()except FileNotFoundError as e:print("Error:", e) "FileNotFoundError" エラーが発生する "Error: [Errno 2] No such file or directory: 'nonexistent.txt'" 何も出力されない None 12. 次のコードの実行結果を選んでください。 my_set = {1, 2, 3}another_set = {2, 3, 4}result = my_set.difference_update(another_set)print(my_set, result) {1} None {2, 3} None {1} {1} エラーになる None 13. 変数aが正の数で、変数bが偶数である場合に「条件を満たします」と表示し、どちらかの条件が満たされない場合に「条件を満たしません」と表示するコードはどれでしょうか? print("条件を満たします" if a > 0 and b % 2 == 0 else "条件を満たしません") print("条件を満たします" if a > 0 or b % 2 == 0 else "条件を満たしません") print("条件を満たしません" if a > 0 and b % 2 == 0 else "条件を満たします") print("条件を満たします" if a == 0 and b % 2 == 0 else "条件を満たしません") None 14. 次のコードでraise文の動作として正しい説明を選んでください。 if not isinstance(x, int):raise TypeError("x must be an integer") xが整数の場合にTypeErrorを発生させる xが整数でない場合にTypeErrorを発生させる 例外を無視する プログラムが正常に終了する None 15. 次のコードを実行した場合、出力は何ですか? lst = [1, 2, 3]lst.append(4)print(lst) [4, 1, 2, 3] エラー [1, 2, 3, 4] [1, 2, 3] None 16. 次のコードを実行したときの出力結果は何でしょうか? x = 10def modify_variable():x = 20return xprint(modify_variable())print(x) 20 20 20 10 10 20 エラー None 17. 次のコードの実行結果として正しいものを選んでください。 try:x = 10 / 0except ZeroDivisionError:print("Division by zero")except Exception:print("General exception") "General exception" "Division by zero" 両方のメッセージが出力される エラーが発生する None 18. 次のコードの実行結果を選んでください。 class MyClass:class_variable = "shared"obj = MyClass()MyClass.class_variable = "modified"print(obj.class_variable) "shared" エラーが発生する "modified" None None 19. 次のコードを実行した場合の出力として正しいものを選んでください。 $ pip install requests$ python -c "import requests; print(requests.get('https://httpbin.org/get').status_code)" エラーが発生する 200 404 None None 20. 次のコードのnonlocalキーワードの用途として正しいものはどれですか? def outer_function():x = 10def inner_function():nonlocal xx += 5 グローバル変数を変更する。 内部関数内で新しい変数を作成する。 外側スコープの変数を参照して変更する。 エラーを防ぐために使用される。 None 21. argparseでオプション引数を指定する正しい方法を選んでください。 import argparseparser = argparse.ArgumentParser()parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose mode")args = parser.parse_args()print(f"Verbose: {args.verbose}")実行コマンド:python script.py -v 何も出力されない エラーが発生する Verbose: False Verbose: True None 22. 次のコードを実行した場合、仮想環境の削除後にwhich pythonを実行した場合の出力として正しいものを選んでください。 $ python -m venv env$ source env/bin/activate$ deactivate$ rm -rf env$ which python システム全体のPythonのパスが表示される 仮想環境内のPythonのパスが表示される 仮想環境の削除エラーが表示される Pythonのパスが見つからないエラーが表示される None 23. 次のコードについて、クラス名として適切なものを選んでください。 class ???:pass MyClass 1stClass class def None 24. 次のコードについて、selfの役割として正しいものを選んでください。 class MyClass:def my_method(self):print("Hello") クラスの名前を表す特別な引数 インスタンス自身を表す特別な引数 他のクラスを参照するための引数 初期化専用のキーワード None 25. 次のコードについて、glob.glob("*[0-9].py")が返す結果として正しい説明を選んでください。 import globresult = glob.glob("*[0-9].py") ファイル名が数字を含む.pyファイルを検索する ファイル名が数字で終わる.pyファイルを検索する ファイル名が文字で終わる.pyファイルを検索する エラーが発生する None 26. 次のコードの実行結果を選んでください。 # パッケージ構造:# package/# ├── __init__.py# ├── subpackage/# │ ├── __init__.py# │ ├── module2.py# │ ├── module3.py# module2.pyfrom .module3 import greetprint(greet())# module3.pydef greet():return "Hello from module3" "Error: greet not found" "Hello from module3" None エラーが発生する None 27. 次のコードの実行結果を選んでください。 def greet(name):print("Hello,", name) SyntaxError: invalid syntax IndentationError: expected an indented block NameError: name 'name' is not defined エラーは発生しない None 28. 変数nが5と10の両方で割り切れる場合に「5と10の倍数」、そうでなければ「倍数ではない」と表示するコードはどれでしょうか? print("5と10の倍数" if n % 5 == 0 and n % 10 == 0 else "倍数ではない") print("5と10の倍数" if n % 5 == 0 or n % 10 == 0 else "倍数ではない") print("倍数ではない" if n % 5 == 0 and n % 10 == 0 else "5と10の倍数") print("倍数ではない" if n % 5 != 0 and n % 10 != 0 else "5と10の倍数") None 29. 次のコードで、文字列"apple"の各文字を逆順に出力するコードはどれでしょうか? for char in "apple"[::-1]: print(char) for char in range("apple"): print(char) for char in reversed("apple")[::-1]: print(char) for char in reversed("apple"): print(char) None 30. 変数numが偶数である場合に「偶数」、奇数である場合に「奇数」と表示するコードはどれでしょうか? print("奇数" if num % 2 == 0 else "偶数") print("偶数" if num % 2 else "奇数") print("偶数" if num % 2 == 0 else "奇数") print("奇数" if num % 2 else "偶数") None 31. 次のコードについて、Childクラスに追加された属性が正しく設定されているか確認する方法を選んでください。 class Parent:def __init__(self, name):self.name = nameclass Child(Parent):def __init__(self, name, age):super().__init__(name)self.age = ageobj = Child("Alice", 10)print(hasattr(obj, "age")) True False エラーが発生する None None 32. 次のコードを実行したときの出力結果は何でしょうか? def create_message(greeting, name="Guest", punctuation="."):return f"{greeting}, {name}{punctuation}"print(create_message("Hello"))print(create_message("Hi", "Alice"))print(create_message("Goodbye", "Bob", "!")) Hello, Guest. Hi, Guest. Goodbye, Bob! Hello, Guest. Hi, Alice. Goodbye, Guest! Hello, Guest. Hi, Alice. Goodbye, Bob! Hello, Guest! Hi, Alice! Goodbye, Bob. None 33. 次のコードを実行したときの出力結果は何でしょうか? y = 100def outer_function():y = 200def inner_function():global yy += 50inner_function()print(y)outer_function()print(y) 200 100 250 250 200 150 200 200 None 34. 次のコードを実行したときの出力結果は何でしょうか? def my_function():x = 5x += 10return xprint(my_function()) 5 10 15 エラー None 35. 次のコードについて、環境変数を取得するための正しい関数を選んでください。 import osprint(os.environ["HOME"]) 現在の作業ディレクトリを取得する プロジェクトのルートパスを取得する ユーザー名を取得する 環境変数HOMEの値を取得する None 36. 次のコードの実行結果を選んでください。 # ファイル名: sample.txtwith open('sample.txt', 'w') as f:lines = ["Line1\n", "Line2\n", "Line3\n"]f.writelines(lines) 空文字列 ファイルは作成されない エラーが発生する Line1 Line2 Line3 None 37. 次のコードの実行結果を選んでください。 # ファイル名: sample.txt# 初期内容: なし(ファイルは存在しない)try:with open('sample.txt', 'x') as f:f.write("Exclusive Content")except FileExistsError:print("File already exists") "Exclusive Content"が保存される "File already exists"が出力される ファイルは作成されない エラーが発生する None 38. 次のコードを実行したときの出力結果は何でしょうか? def add_items(item, items=None):if items is None:items = []items.append(item)return itemsprint(add_items("apple"))print(add_items("banana")) ["apple"] ["apple", "banana"] ["apple"] ["banana"] ["apple"] ["apple", "apple"] ["banana"] ["banana"] None 39. 次のコードの実行結果を選んでください。 class A:passclass B(A):passclass C(A):passobj = B()print(isinstance(obj, C)) True False エラーが発生する None None 40. 次のコードを実行した場合の出力として正しいものを選んでください。 import argparseparser = argparse.ArgumentParser()parser.add_argument("-n", "--name", required=True, help="Specify the name")parser.add_argument("-a", "--age", type=int, help="Specify the age")args = parser.parse_args()print(f"Name: {args.name}, Age: {args.age}")実行コマンド:python script.py -n Alice -a 30 Name: Alice Error: the following arguments are required: -n/--name Name: Alice, Age: None Name: Alice, Age: 30 None Time's up