Home > Backend Development > Python Tutorial > Tricky Python Questions

Tricky Python Questions

PHPz
Release: 2024-07-25 01:00:52
Original
853 people have browsed it

In the last two years, I have been using Python as my main programming language. I thought maybe it's a good reason to "go deep" as I did in Tricky JavaScript Questions. some of the next questions were issues that I needed to deal with in my current job, others inspired by the web.

So are you ready to get your mind blow away (from Python question)?

Tricky Python Questions

Questions

Notice 1!: To each question, there is an answer with an explanation (link below each item).
Notice 2!: For each question think what will be the output.

Question 1
exapmle_dict = dict()
exapmle_dict.a = "string"
print(exapmle_dict)
Copy after login

Go to answer 1

Question 2
class Json:
    def __init__(self, *args, **kwargs):
        import json

    def print_dict_as_json(self, obj):
        print(json.dumps(obj))

example_json = Json()
example_json.print_dict_as_json({"a": "string"})
Copy after login

Go to answer 2

Question 3
def myFun(arg1, arg3, **kwargs):
    for key, value in kwargs.items():
        print("%s == %s" % (key, value))


my_dict = {'arg1':1, 'arg2': 2}
myFun(**my_dict, arg3=3)
Copy after login

Go to answer 3

Question 4
def add_to_all_1(arr):
    for i in range(len(arr)):
        arr[i] +=1

def my_func():
    arr = [1,2,3]
    add_to_all_1(arr)
    arr2 = arr
    print(arr2)

my_func()
Copy after login

Go to answer 4

Answers

Answer To Question 1

If you said:

{"a": "string"}
Copy after login
Copy after login

unfortunately, you are wrong, the answer is:

AttributeError: 'dict' object has no attribute 'a'
Copy after login

If you like me and came from javascript first, the access dictionary (object in Javascript) is not by dot like in Javascript, you can access only by [], and inside the key you want to set "a".

Back to question 1

Answer To Question 2

If you said:

{"a": "string"}
Copy after login
Copy after login

You are wrong again, the answer is:

...
NameError: name 'json' is not define
Copy after login

You may know the differences between local and global scope in Python (if not you should read this: Python Scope). The __init__ is a function, the import is inside a local scope so it doesn't know what is json. You can fix it by import it globally like this:

import json

class Json:
    def print_dict_as_json(self, obj):
        print(json.dumps(obj))

example_json = Json()
example_json.print_dict_as_json({"a": "string"})
Copy after login

Or in a more advanced way:

class Json:
    import json as json
    def print_dict_as_json(self, obj):
        print(self.json.dumps(obj))

example_json = Json()
example_json.print_dict_as_json({"a": "string"})
Copy after login

You can see using import inside class for more details.

Back to question 2

Answer To Question 3

If you said:

arg2 == 2
Copy after login

You are right! In Python, we have 3 ways to pass an argument:

  • By the argument itself:
def myFun(arg1):
   print(arg1)

myFun('arg1')
Copy after login
  • By *args - list or tuples of arguments ( allows us to pass a variable number of non-keyword arguments to a Python function):
def myFun(*arg1):
   print(*arg1)

my_tuple = ('arg1', 'arg2')
myFun(my_tuple)
Copy after login
  • By kwargs can pass key=value arguments (kwargs allows us to pass a variable number of keyword arguments to a Python function) - like in the question. If you want to read more about the subject you can read here: freecodecamp - How to Use *args and **kwargs in Python

Back to question 3

Answer To Question 4

The answer is:

[2, 3, 4]
Copy after login

For some people who know scopes and assignments, it can seem a pretty easy question. For those who don't know, python saves variable memory as a reference, so in this case, the arr will point to a reference in a memory -> the function will change the values (but still the same reference) -> arr2 will get the reference address of arr but after values were modified.

Back to question 4

Thank you for reading this article. I hope you enjoyed and learned new things. If you have any questions or suggestions, please leave a comment.

The above is the detailed content of Tricky Python Questions. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template