Making Python simple for you, by exploring the fundamentals.
Posting tips, questions, explanations, solutions, and much more!
Building
@PythonResources
🚨 Python Testing Series 🚨
Employ testing to gamify your coding.
Learn how to test code using pytest.
Build a Cash Dispenser project in Test Driven style.
Ongoing series of posts, see README at:
@codewithvoid
If I had to mention just one:
Writing code without clearly understanding the problem.
A close second:
Using copied code from StackOverflow/ChatGPT/whatever without having a clue about what it's doing.
@codewithvoid
Learning to use Version Control.
Without version control, one is hesitant to make changes to the code, for the fear of breaking it.
Version control gives you a safety net, and you can edit your code with the assurance that you can get back the version if something goes wrong.
🚨 LIST METHODS CHEATSHEET
Python list methods are incredibly useful.
Here is a cheatsheet and reference doc for them.
The document has explanations & details of 11 list methods.
Peek at the cheat sheet in the attached image
Grab the PDF cheatsheet and the full doc 🆓 by
+
@clcoding
Answer: A. Solution:
TLDR
☑️ x.append(4) appends the value 4 at the end of the list x.
☑️ Hence, x, which was [1,2,3] before the append, now becomes [1,2,3,4]
Details👇
@clcoding
Answer: C. Solution:
x = 5
assigns the value 5 to x
y = x > 3
This statement has 2 operators, `=`, and `>`.
`>` is higher in precedence than `=`.
So, the comparison x>3 is performed.
x, ie, 5, is greater than 3, so the result is True.
+
@rupali_codes
Trying to put more thought into variable names.
It helps a lot later.
- No single letters (no x,y)
- Nouns, not verbs (washed_spoon_list, not wash_spoon_list)
- Descriptive (annual_interest_rate, not air)
- Shortest possible, while satisfying the above
@KevinNaughtonJr
Write tests because:
1. It is rare to write all the code correctly the first time
2. If you add a new feature, you should know if the old stuff still works
3. You can convince others of the correctness of your code
@RealBenjizo
Answer:A. Solution:
[1,2], (1,2)
are two values ( [1,2] and (1,2) ), separated by a comma.
Such comma-separated values are interpreted as a tuple by Python. Hence,
[1,2], (1,2)
is exactly the same as the tuple
( [1,2], (1,2) )
Thus, they type of `a` is tuple.
@driscollis
Answer: C. Solution:
TLDR
☑️ The list on the right hand side gets "unpacked" into variables on the left hand side
☑️ First element, ie 1, goes to a
☑️ Last element, ie 5, goes to c
☑️ All that is left [2,3,4] goes as a list into b
Details 👇
@codewithvoid
Jumping to code without thinking.
It was in a course where I first learned to code.
For exams, we had to scribble code on paper, in a rush.
That's how I got into that habit: To quickly jump and code, without careful thinking.
It took some time to break, but it was liberating.
🚨 LIST METHODS CHEATSHEET & REFERENCE 🆓
List methods are very commonly used.
Never fumble with them again.
Be more productive with a neat reference handy.
Grab now
✅ PDF cheat sheet
✅ Notion reference document
✅ Updates and more Python tips
here:
@clcoding
Nice!
You can open an http server using python with just one command.
python -m http.server
will start an HTTP server in the current directory, which you can use to share files with other devices on the network!
@clcoding
D. Explanation:
The ^ operator is overloaded (different operation for different classes).
For set operands (s1 and s2 are sets here), it returns the symmetric difference between the sets. See image for meaning.
Hence {2,6,9} from s1 and {5,7} from s2 give the answer D.
Python tip:
Use `dir` to list the attributes and methods of an object.
Useful for debugging and getting to know more about a class.
Eg (code in image description)
@clcoding
Answer:B. Explanation:
TLDR:
s.replace('e', 'r', 1) returns a copy of s in which only the first 'e' is replaced by 'r'.
Hence the output is 'awrsome', Option B.
Detailed answer, read on:
+
@_jaydeepkarale
Automate the Boring Stuff with Python
Excellent book that strengthens your Python knowledge, while helping you build your own useful projects!
@clcoding
Answer:D. Solution:
The function `my_func` works by calling itself, as we will shortly see.
Let us analyze the code and see what is happening.
my_func(5)
x is not 0, so the if-condition fails, and the return value is
5 + my_func(4)
Now, here is the tricky part...
+
Python tip
If you need both the quotient AND the remainder of a division, use `divmod`
divmod(dividend, divisor) returns the tuple
( dividend // divisor, dividend % divisor)
For example, to get the quotient and remainder of dividing 100 by 9,
(Code in alt text)
@RealBenjizo
Answer:A. Solution:
To solve this question, we need to understand:
1⃣ What is a method, and what is `self`?
2⃣ What does __init__ do?
Let's dive in!
+
@clcoding
Answer: A. Solution:
TLDR
s.replace('e','i',2)
replaces the first two occurrences of 'e' by 'i', in the string s.
Therefore, 'developer' becomes 'diviloper'.
Details 👇
@driscollis
Answer:D. Solution:
TLDR
☑️x = 7,8,9
assigns tuple (7,8,9) to x
☑️x == 7,8,9
here == takes place before tuple formation.
☑️So x (which is the tuple (7,8,9) ) is compared to 7, that gives False. Then the tuple with 8 and 9 formed
☑️So the output is (False, 8, 9)
Details 👇
Python question (inspired from a tweet by
@driscollis
)
Given:
a string, my_str, and
a character, my_chr
Task:
Find the index of
the SECOND occurrence
of my_chr within my_str
Eg:
my_str = 'twitter'
my_chr = 't'
# Expected output: 3
Can you do this in one line of code? 🤔
@clcoding
Answer:C. Solution:
Recall that the `*` operator between a list and an int, produces the repetition of the list.
Eg,
[1,2,3] * 2
gives
[1,2,3,1,2,3]
Now, consider
[]*3
Here the list is empty, ie, it has no elements
Therefore, 3 repetitions of 0 elements
+
@clcoding
Answer: B. Explanation:
The str.split method returns a list of substrings of the original string.
The split method by default splits a string around whitespace. However, this behaviour can be changed by passing an argument to split.
The argument `sep` specifies
+
@driscollis
Answer:C. Solution:
TLDR
☑️ The f-string will render `language`, ie, 'Python', as per the format specifier '*^30', this specifies
☑️ a width of 30 characters
☑️ ^ centered alignment ('Python' in the middle of a 30 character string)
☑️ * as the padding character
Details👇
Python Question
What is the output of the following code, and why?
A. [[1], [1]]
B. [[1, 5], [1]]
C. [[1], [1, 5]]
D. [[1, 5], [1, 5]]
(code in alt text)
This is the Rock, Paper and Scissor. I did which has scoreboard through the implement of the global variable and it also have a loop function if you wish to continue the game.
open for correction
@codewithvoid
Fast typing is not essential, but it does help.
As a developer, you will need to type all the time, be it code or documentation.
All these processes will be smoother if you can your thoughts to text quickly.
Python question: Break the math, v2
Here your task is to select a value for `x`, such that the code below prints: You got it!
You may use at most one import from the standard library.
Go for it, and explain how your solution works!
@driscollis
Answer:C. Solution:
TLDR
☑️ The list.append method modifies the list on which it operates, and returns None.
Details
👇
To solve this question, we need to understand 2 things:
1⃣Methods on objects
2⃣list method `append`
+
* Mini projects to do as you learn Python *
With arithmetic operations and conditionals:
- Income tax / electricity bill calculator
- Area/circumference calculator for circle/rectangle
- Simple interest calculator
- Unit converter
+
@_jaydeepkarale
@codewithvoid
This 👆 is great advice.
An additional tip:
If
you CANNOT think of
an honest name for the function,
without using the word "and",
then
consider splitting the logic into multiple functions.
Functions should ideally do only one thing, and the name should show what they do
@RealBenjizo
Answer: A. Solution:
d = {'name':'Bob', 'age':30}
creates a dictionary with keys 'name', 'age', with values 'Bob', and 30 respectively.
Now let us consider what happens when
len( set(d) )
is executed.
+
@clcoding
Answer:B. Solution:
TLDR
y = x
binds x and y together.
Changes made in y reflect in x.
Hence, y[1] = 4 sets x[1] to 4 as well.
Thus x becomes [1,4,3]
Details
👇
Played around with PyScript, and got a simple Password Generator made!
You can try it out here:
Please be patient, PyScript is slow to load :(
Hope to build more using this amazing tool by
@pyscript_dev
!
Screenshot:
🚨 Exciting news!
I'm starting a weekly newsletter to share thoughts on Python programming.
Take your coding skills to the next level, while keeping it simple and chill.
Subscribe now, stay tuned to get a goodie that will be ready soon!
Join here:
@driscollis
Answer:A. Solution:
For the purpose of arithmetic operations, Booleans are converted to integers.
False is converted to 0.
True is converted to 1.
Therefore,
True + True + False - True
equals
1 + 1 + 0 - 1
ie
1.
Hence, Option A is correct.
Python question
Which of the following code snippets throws an error? Why?
A. S1 only
B. S2 only
C. Both S1 and S2
D. Neither S1 nor S2
(code in alt text)
Python tip
If you need to install all the packages named in a file (conventionally named requirements.txt in Python projects),
use
pip install -r requirements.txt
@RealBenjizo
Answer: B. Solution:
TLDR
modify_dict doesn't mutate d, it returns a new dictionary.
That returned dictionary is not assigned to anything.
The d in the main namespace remains unchanged.
Details👇
Python tip
To list all the packages installed in your Python environment, use
pip freeze
It's also convenient to redirect this output to a file, like so
pip freeze > requirements.txt
@clcoding
None of the above. The code results in an IndentationError.
Python expects an indented block after the line with the 'while' keyword. However, there is no indentation hence the IndentationError.
See thread for more about indentation in
#Python
@clcoding
Answer: A, 🚨but better to call it IndentationError than SyntaxError. Explanation:
After the line def sign(num):,
The Python syntax expects an indented block (which is supposed to contain the body of the function).
Indentation in Python can be
+
@clcoding
Answer:D. Solution:
When s1 and s2 are sets, s1^s2 returns the *symmetric difference* of sets s1 and s2. (Check out the link in next tweet for a detailed explanation.)
That is, elements that are either in s1 or s2, but not in both s1 and s2.
+
Python One-line Challenge
Given a nested list (ie a list-of-lists) of numbers,
can you print the list which contains the largest number?
See snippet for example and expected output (code in alt text)
Python Question
What is the output of the following code, and why
dct = {0:'zero', 1:'one', 2:'two'}
lst = [i for i in dct]
keys = dct.keys()
print(lst == list(keys))
@clcoding
Answer: B. Solution:
TLDR
y = x
binds y and x to each other.
So mutation to y causes mutation to x too.
y[2] = 10
mutates x as well, making it [1,2,10,4,5]
Details👇
@mathsppblog
Similar. I say something like,
"return, but remember."
A return causes to "forget" in the sense, the function starts afresh on subsequent calls.
A yield causes to "remember" in the sense that the state of the generator is saved, and restored on the next item extraction.
@driscollis
Answer: D. Solution:
TLDR
☑️ (a:=6, 9) considers a:=6 as an expression, that assigns 6 to a
☑️ (a, b := 16, 19) considers b:=16 as an expression, that assigns 16 to b
☑️ So, at the time of printing a is 6 and b is 16
Details 👇
@CodingMantras
Answer: 32. Solution:
int(x, base=8)
converts `x` to `int`, interpreting it is a base-8 (octal) number.
The value of "40", when interpreted as an octal number is
4*(8**1) + 0*(8**0)
= 4*8 + 0
= 32
Hence, the value of
int(x, base=8)
is 32, and that is what gets printed.
@RealBenjizo
Answer: B. Solution:
Two key point in clearly answering this question is:
1. Functions are objects in Python.
2. Function names are identifiers, exactly like variable names.
How do these points lead to the solution?
+
@RealBenjizo
Answer:A. Solution:
To solve this question, we need to understand:
1⃣ What is a method, and what is `self`?
2⃣ What does __init__ do?
Let's dive in!
+
@clcoding
Answer: D. Explanation:
The list.pop method removes an element from the list, and returns the removed element.
When used without arguments, pop removes and returns the last element of the list.
When an argument index is specified,
+
@clcoding
Answer:B. Solution:
Here,
li = ['W']
creates a list ['W'], and assigns it to `li`.
Next, the `extend` method is called on `li`, with the argument 'XYZ'.
What this does is,
☑️ iterate through the argument
☑️ append each item to the list li
Let us make it more concrete,
+
@clcoding
Answer:B. Solution:
The `sum` function takes 2 arguments
1 required argument, `seq`, which is iterable, and
1 optional argument, `start`, whose default value is 0.
This function returns
`start` plus the sum of all elements in `seq`
In the question,
+
@clcoding
Answer: List
Solution: A set can never contain a list.
It may or may not be able to contain a tuple,
but that depends on the content of the tuple.
To understand the reason,
let's understand how a set works under the hood.
First of all, when you add an element to a set,
+
@clcoding
Answer: 3 9
Solution: The trick here is to understand `continue` in loops.
As we know, by default, a while loop executes till the condition remains truthy.
However, the `continue` adds a small twist to this.
Let's explore that
+
Python question!
Rack your brain, and break the math here.
Choose a value for x, such that the output of the following snippet is False.
Yes, you can do it.
Go for it, and explain why your method works!
@clcoding
Answer:
rows = 5
for count in range(1, rows*5+1):
print(
f"{('*' if count%2 else count//2):>3}",
end='' if count%5 else '\n'
)
(See image for output)
✅ Explanation:
First we specify the number of rows.
There are 5 rows in the question so 5 it is.
+
@driscollis
Answer:B. Solution:
TLDR
☑️ By default, `min` is a function to calculate minimum.
☑️ min=0 assigns 0 to `min`, it is no longer a function
☑️ min(numbers) attempts to invoke `min` (integer 0), that results in a TypeError
Details 👇
@codewithvoid
Great advice!
Trying to learn everything thins out your attention.
Instead, focus on one language, and work on it's fundamentals.
And, a complementary piece of advice:
"Never stop learning"
@driscollis
Answer: C. Solution:
TLDR
☑️ (lambda a,b: a*b) is a function that takes 2 arguments and returns their multiplication
☑️ (5,4) are given as arguments to the function. 20 is the output of the function
☑️ (20 - True) is 19, because True is taken as 1 for arithmetic
Details👇
@driscollis
Answer: D. Solution:
☑️ 5 * True is 5 (True is taken as 1 in numeric contexts
☑️ 5*"Spam" repeats "Spam" 5 times
☑️ 5*[1,2] repeats [1,2] 5 times
☑️ 5*None is not defined, raises the error
Details👇
Do you know a cool thing about Python ints?
Python does not impose any restriction on the size of ints.
So, you can create as big ints as your computer memory can fit.
This allows you to work with HUGE integers!
@driscollis
Answer:C. Solution:
TLDR
☑️ f"{message:{fill}{align}{width}}" formats the message 'hi' with:
☑️Left alignment because of '<'
☑️Text width of 10
☑️The remaining 8 characters to the right are filled with 's'
☑️That gives hissssssss (8 s characters)
Details 👇
#python
#pandas
#tip
Use `apply` method to apply a function to every element of a dataframe or series.
Very handy for creating new df columns based on existing.
See example image. (Code in image description)
@RealBenjizo
Answer: B. Solution:
`t` is the tuple (1,5,10) inside the function `change_tuple`.
t[2] is 10
t[1] is 5
so,
(t[2], t[1]) is the tuple
(10,5)
t[:0] is added to (10,5)
What is t[:0]?
+