Python Flashcards

1
Q

What is snake case in python?

A

Using underscores to form a long variable name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the type of the result of a division operation in python?

A

floating point

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you get integer value out out of a division in python?

A

By using the ‘//’ operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Does // operator do a round-off?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you distinguish between a variable definition and further use in python?

A

You can’t, both have same syntax

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

f-strings are available from which python version?

A

3.6 onwards.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are f-strings?

A

A convenient way to format different types into string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is another way (than f-strings) to format strings without explicitly converting them?

A

By having placeholders in the string with “{}” and calling the format method of the string with requisite parameters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the constraint on the number of parameters for the format method of the string?

A

It can be more, but cannot be less

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

In what ways “format” can take parameters for a string?

A

format can take parameters as positional as well as keyword based.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How does “format” method take keyword based arguments?

A

keyword based arguments have to be given in the last after positional arguments. They cannot be mixed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is necessary for passing keyword based arguments to “format” method of string?

A

The string should contain the keyword in { } in it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Is string.format(name=name) valid? Both identifiers

A

Yes, the first one will be looked for in the string, while the second one is treated as a proper variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does f-string and format compare?

A
  • f-string takes actual parameters, while format takes formal parameters (which is to be filled in by passing format with actual parameters)
  • f-string can take expressions that evaluate to a value, while format cannot
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which function in python reads input from keyboard and returns a string?

A

input(“message”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are boolean keywords in python?

A

True and False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does print take?

A

An expression that can be evaluated

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are python’s boolean operators?

A

and, not, or

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does and/or return?

A
  • and returns first value if it is false, otherwise it returns the second value
  • or returns the first value it is true, otherwise it returns the second value
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does not return?

A

not always returns True or False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does list.remove() take?

A

The value of the element which needs to be removed from the list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Is parens mandatory for writing tuples?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to minimally express a tuple of only one item?

A

a,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you add a new element to a tuple variable?

A

By adding “+” another tuple of single element to the variable: v = v + (e,)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How do we represent set1 - set2 in python?
set1.difference(set2)
26
How do we represent symmetric difference between two sets (set1 U set2) - (set1 AND set2)
set1.symmetric_difference(set2)
27
What type is "{}"
dict, not set
28
How do we represent set intersection in python?
set1.intersection(set2)
29
How do we represent set union in python?
set1.union(set2)
30
How do we represent an empty set in python?
set()
31
Does dictionary keep order of elements inserted?
Yes, in python 3.7
32
How to make a dict from values?
Have a list of 2-element tuples and feed it to dict()
33
A list of grades, a tuple of grades, a set of grades - which is not a correct choice
set of grades
34
A list of grades, a tuple of grades - which is a better option?
if grades are not going to be added, a tuple is better, otherwise a list is better
35
sum(), len() - can be used on which of the following data structures: set, list, tuple
all of them
36
How come we can pass values and expressions to if or while in python?
Python implicitly passes all those expressions through bool to get True or False
37
What is the else/if keyword in python?
elif
38
What is the difference between while loop and for loop in python?
While loop runs an undefined number of times - based on an external event, and for loop runs for a defined number of times
39
What is the difference between: if a in b: for a in b:
In the first one, "a" is a known identifier or a constant, while in the second one, "a" is a new identifier
40
What is the act of taking a collection into more than one variable is called?
destructuring
41
What does for d in dict give?
A list of all the keys
42
How do you iterate over values of a dict?
dict.values()
43
How do you destructure key, value from a dict?
dict.items()
44
what does while-else/for-else statement do in python?
If for doesn't encounter a break, then else clause will be executed, otherwise else clause will not be executed
45
What is the difference between aList and aList[:]
The second one gives a new copy of aList
46
what does aList[0] and aList[-1] represent?
The first and the last elements of the list
47
what does aList[-x] represent?
xth element in the list starting from the last element with index as 1 towards left side
48
how do you mathematically repreent aList[x:y]?
[x, y)
49
What is the direction of slicing a list?
Always from left to right
50
What happens if a list is sliced with indices pointing to elements from right to left?
An empty list is returned
51
In aList[-x:-y], what is the constraint to get at least one element?
x > y
52
How do you differently explain list comprehension?
Expression followed by the for statement with an optional if statement
53
What is a readable way to write a list comprehension?
expression, for statement, if statement - each in one line
54
Comprehension is applicable for which of the following collections? list, set, dict
All of them
55
When you create a collection, think about _____
comprehension
56
How do you create a list of tuples with lists to feed to dict()?
With a zip function
57
Which is more simpler? a dict made out of comprehension or a dict made out of a zip?
dict made out of a zip
58
When does a dict made out of comprehension make sense over a dict made out of zip?
When we want to conditionally add the list elements into the zip
59
Does zip takes only two lists?
No, it can take more than two
60
What happens if the lists given to zip are of different lengths?
zip will make a list of tuples of the size of the smallest list
61
can the argument to a function be nameless?
Yes
62
How is a variable resolved i.e. searched for resolution?
First in local scope, then in global scope
63
What is the type of the value returned from a function which has no explicit return statement?
None
64
What are the two types of arguments in python to a function?
positional and keyword arguments
65
What is the constraint for passing positional and keyword arguments in python?
positional arguments should precede keyword arguments
66
What is the constraint for defining a function with default and non-default parameters?
non-default parameters must precede default parameters
67
What is the argument given to print to change what is printed between the arguments?
sep=xyz
68
When are the default parameters for a function evaluated and stored?
At the time of function definition, not function invocation
69
What are the consequences of having non-constant expressions as values for default parameters?
Any change in the variables will not change the value of default parameters and it becomes less readable
70
What is the difference between a normal function and a lambda function?
Normal function is assigned to a variable with the function definition itself, where as lambda function has to be explicitly assigned to a variable through an assignment statement
71
When is a function vs lambda destroyed in python?
When the function or lambda reference goes out of scope
72
Can a lambda definition span more than one line?
No
73
What happens when a lambda definition is not assigned to anything?
it is destroyed immediately
74
How do you check for the presence of a key in dict?
with the "in" operator
75
Which string method is used to validate if the string is a number?
isdigit(), isdecimal(), isnumeric()
76
What is the difference between two string methods: isdigit() and isnumeric()
The latter works with unicode characters
77
What is the no-op statement in python?
pass
78
What happens if a function is defined two times?
The latest definition overrides the old definition
79
What is a clean and extensible way to implement a menu of options to be selected by the user?
A dictionary with key as the supported options and values as the function handlers
80
How does lambda functions help write generic code
It helps by the caller pass the paramater(object) as is to the lambda function without interpreting the type of the parameter
81
In the class definitions, is the "self" keyword mandatory?
No, the first parameter refers to the object and it can be named anything.
82
What is the function that gets called first when a class is instantiated?
__init__
83
__init__ is also called as?
dunder init function
84
What are the different valid ways of calling an object method?
1. object.method() | 2. class.method(object)
85
How does the list of attributes in a class defined?
As and when they are assigned.
86
Can a class attributes grow dynamically after object creation?
Yes
87
List of arguments to python script is stored in?
sys.argv list
88
Current OS is stored in?
sys.platform
89
Name the fully qualified function to write to stdout
sys.stdout.write(str)
90
Python version is stored in?
sys.version
91
PATH contents are available in?
sys.path
92
Function to check if a file exists in file system?
os.path.isfile()
93
Function to check access permissions of a file?
os.access(file, os.)
94
Function to list the contents of a directory?
os.listdir(dir)
95
Function to get current working directory?
os.getcwd()
96
Function to execute a shell command?
os.system()
97
Function to walk the current directory?
os.walk()
98
What does os.walk() return?
it returns the root directory (which is being walked), a list of directories and files in the root
99
Function to check OS?
platform.system()
100
What is the difference between sys.platform and platform.system() ?
sys.platform is an variable attribute, platform.system is a method attribute
101
What are different ways to run a command?
os.system(), subprocess.run(), subprocess.call(), os.spawn(), os.popen() etc.
102
When executing commands like "clear" through subprocess, what needs to be indicated?
shell=True
103
What does subprocess.run() return?
An instance of CompletedProcess class
104
What does subprocess.check_call() function return?
Nothing if the call succeeds, otherwise raises a CalledProcessError exception
105
What does subprocess.check_output() function return?
Returns the output as a byte string if it exits normally otherwise raises CalledProcessError exception
106
What does os.system() return?
the exit code of the process
107
What does stdout=subprocess.PIPE mean?
Instead of pointing to standard output, stdout is now pointing to a pipe (which will be instantiated and returned)
108
What does stdout=subprocess.PIPE, stderr=subprocess.STDOUT mean?
output is given a new pipe and err is redirected to stdout (to the new pipe here)
109
Why subprocess.wait() needs to be used?
to let the child finish so as to collect output
110
What does subprocess.communicate() return?
A tuple of (stdout, stderr)
111
What is the general sequence of steps to spawn a process and collect its output with subprocess?
``` sp=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ret=sp.wait() out, err = sp.communicate() #check ret, out, err ```
112
How to convert bytes to string?
str(, "UTF-8") #encoding scheme
113
How can "ps aux | grep xyz" be achieved in python with subprocess methods?
ps=subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) grep=subprocess.check_output(["grep", "xyz"], stdin=ps.output) ret = ps.wait() #check return code
114
Once a Popen object is created with PIPE, how can that be used elsewhere or assigned elsewhere?
we can refer to stdout, stdin of the Popen object
115
When a command and its parameters is given as a string to subprocess.Popen(), what should shell=?
True, as it is passed as is to the shell to execute, without which it will fail
116
With shell=True, what happens if we give command as a list of command, parameters?
The parameters are ignored and only the command is executed
117
What is given to subprocess.Popen to get output and error as text (string) instead of byte object?
universal_newlines=True
118
What are the 4 steps of argument parsing?
import argparse; create a parser; add arguments; parse arguments
119
How is an argument parser created?
argparse.ArgumentParser
120
What is the function in argparse to add an argument?
add_argument()
121
How do we convert arguments passed to add_argument to different types?
with type=xyz
122
How do we add description to an argument in add_argument?
with help=abc
123
How do we validate that given input is within a specified list when adding an argument with add_argument?
with choices=[a, b, c]
124
which kwarg specifies that an argument is mandatory or not in add_argument
required=True or required=False
125
How are positional arguments in add_argument referred to in the code?
when we give dest="xyz", it is referred to with attribute xyz on the argumenr parser object
126
How are optional arguments given a default value in add_argument of argparse?
with default=abc
127
How are optional arguments added with | add_argument?
with a "-" or with a "--"
128
How are optional arguments referred to in the code?
the name given with "-" or "--" or with a dest=abc
129
How is a boolean flag specfied in add_argument of argparse?
with action="store_true"
130
When short and long names are given in add_argument of argparse, which one prevails?
long one
131
Which function in argparse is used to create a set of mutually exclusive arguments?
add_mutualy_exclusive_group, group.add_argument()
132
With argparse, how do we specify that an argument is a file that has to be read or written?
with type=argparse.FileType('r') or type=argparse.FileType('w', encoding="UTF-8")
133
How do we import scapy into python code?
import scapy.all as scapy and call scapy.xxx()
134
Which operator is used to stack different layers in a scapy constructed packet?
'/' operator
135
What denotes the latest result in python?
"_"
136
Which function will omit showing default in scapy constructed packets?
hide_defaults()
137
which scapy function is used to read pcap files?
rdpcap()
138
Which scapy function is used to dump the packet in hex?
hexdump()
139
Which scapy function is used to format the packet with a format specifier?
pkt.sprintf()
140
Which scapy function is used to dump the packet in the command format (which can be executed to generate the same packet)?
pkt.command()
141
Which scapy function is used to display the packet after proper processing (dns resolution, cheksum calculation etc.)
pkt.show2()
142
In scapy, how to set a field to a range of values?
ttl=[1,2,(5, 9)]
143
In scapy, when we give a range (a,b), is it inclusive or exclusive?
Inclusive
144
In scapy, which function sends packets at layer 3?
send()
145
In scapy, which function sends packets at layer 2?
sendp()
146
In scapy, with send/sendp, which kwarg is used to get back the list of packets sent?
return_packets=True
147
In scapy, which function is used to randomize the packet fields?
fuzz()
148
In scapy, how is fuzz() used to randomize fields?
fuzz(IP()/UDP()) etc.
149
In scapy, what all fuzz() can randomize and what it cannot?
Fields overridden by upper layers and fields that are not defaults - are not fuzzed
150
In scapy, to randomize (fuzz) IP addresses which function should be used?
RandIP()
151
In scapy, what does the send and receive family of functions return?
a couple of two lists - the first list is a couple of (sent, received packets), the second list is unanswered packets
152
In scapy, in the send/receive family of functions what is the advantage of receiving unanswered packets in return?
We can call send/receive again with the unanswered list as is
153
In scapy, in send/receive family of functions, what do the kwargs inter, retry and timeout mean?
inter - interval (in secs) between transmitting two packets retry - if retry is x, then unanswered list is retransmitted "x" number of times. If the retry is -x, then the unanswered list is transmitted until the unanswered list is the same for the last x tries timeout - when to start treating sent packets as unanswered
154
In scapy, which function lists all the available packet types?
ls()
155
In scapy, how do we see all the supported fields for a given packet type?
ls(pkt_type)
156
In scapy, which function lists all the commands available?
lsc()
157
In scapy, how do we see the help for a command?
help(cmd)
158
In scapy, which function is used to write packets to a pcap file?
wrpcap()
159
In scapy, which function is used to read packets from a pcap file?
rdpcap()
160
In scapy, when we create a ICMP() packet, which type of the packet is created by default?
echo-request
161
In scapy, how can we change the configuration on which scapy operates?
conf.xyz = abc;