I am working on the file "SearchEngine.ipynb".
The first task is:
Indexing
Es wird ein inversed Index aufgebaut.
Dabei werden die absoluten Vorkommen der Therme $w$ in den jeweiligen Dokumenten $d$ gespeichert.
Can you write Python code for it?

words = [word for doc in docs for word in doc['words']]

iindx = pd.DataFrame.from_dict({ doc['title']: [
    doc['words'].count(word) for word in words ]
    for doc in docs })
iindx.index = words

iindx = iindx[~iindx.index.duplicated(keep='first')]
iindx.to_csv('index.txt')
iindx.head(10)


I am working on the file "SearchEngine.ipynb".
The first task is:
Scoring und Suche
e)  TF - IDF
Term Freqency
Hier wurde sich für eine logarithmisch normierte Term Freqency entschieden.
Damit gilt:
$$
\mbox{log_freq}(w, d) =
   \begin{cases}
     1 + log10 tf(w,d) & \mbox{für}\,\,\,\,\,\,\,\,\,\,\,\,\,\, tf(w,d) > 0  \
     0 & \mbox{sonst} \
   \end{cases}
$$
bei $tf(w,d) := $ absolutes Vorkommen des Terms $w$ in Dokument $d$.
Die Term Frequency steht bereits im Index und muss nur ausgelesen werden.
 Inversed Document Frequency
Ist definiert als
$$\frac{\mbox{Anzahl der Dokumente}  (N)}{\mbox{Anzahl der Dokumente welche Term w enthalten }(df(w))  }$$
Eine Normierung erfolgt mit $\log_{10} df(w)$
Scoring und Suchfunktion
Das scoring der Dokumente eines spezifischen Terms kann über die Funktion search(words) ermittelt werden.
Dabei ist es auch möglich, Listen von Termen anzugeben. Diese werden über $A \land B$ verbunden.
Can you write Python code for it?

idx = pd.read_csv('./index.txt', index_col=0)

def log_freq(word, doc):
    tf = int(idx[doc].loc[word])
    return 1+log(tf, 10) if tf > 0 else 0

def idf(word):
    N = idx.shape[0]
    df = np.sum(idx.loc[word].map(lambda x: 0 if x == 0 else 1))
    return log (  (N / df), 10)

tfidf = lambda w,d : (log_freq(w, d) * idf(w))
weights = lambda w : [ {d: tfidf(w,d)}
    for d in idx.columns.values.tolist() ]

pd.DataFrame.from_dict([{word: weights(word) for word in words}])

tfiidx = pd.DataFrame.from_dict({ doc['title']: [
    tfidf(word, doc['title']) for word in words ]
    for doc in docs })
tfiidx.index = words
tfiidx = tfiidx[~tfiidx.index.duplicated(keep='first')]

def search (words):
    assert type(words) == list
    # - The weights are calculatet by

    return pd.DataFrame([tfiidx.loc[w] for w in words]).product()

s_terms = [['tokens'], ['index'], ['classification'], ['tokens', 'classification']]

search_df = pd.DataFrame([search(t) for t in s_terms])
search_df.index=[' AND '.join(s) for s in s_terms]

search_df

search_df.to_csv('tfidf_search.txt')


I am working on the file "SearchEngine.ipynb".
The first task is:
a ) Der Crawler
Der Crawler wurde mit der Bibliothek Scrapy umgesetzt. Es wurde sich hier gegen eine Einrichtung eines Projektes und für eine Scriptbasierte Lösung entschieden.
Um die Ausführung über das Notebook zu regeln, wurde über das MagicFlag %%writefile die Klasse in eine Datei geschrieben und der Aufruf über von Scrapy über subprocess umgesetzt.
Die Klasse HtwSpider implementiert über die Einstiegspunkte, die Extraktionsanweisungen sowie dem gewünschten Link-Verhalten den Crawler.
Dabei werden der Titel, der Text und die ausgehenden Links aller Seiten gespeichert, die von den EInstiegspunkten aus eirreichbar sind.
Can you write Python code for it?

%%writefile ./my_spider.py
# %%writefile ./my_spider.py
# %load ./my_spider.py

import scrapy
import json

class HtwSpider(scrapy.Spider):
    name = 'htw_spider'

    start_urls = [
        'http://people.f4.htw-berlin.de/~zhangg/pages/teaching/pages/d01.html',
        'http://people.f4.htw-berlin.de/~zhangg/pages/teaching/pages/d06.html',
        'http://people.f4.htw-berlin.de/~zhangg/pages/teaching/pages/d08.html'
    ]

    def parse(self, response):

        # - Extracting the needed attributes.
        title = response.xpath('//title/text()').extract()[0]
        text = ' '.join([t.strip() for t in response.xpath('//body/text()').extract()]).strip()
        hrefs =  [l.split('.')[0] for l in response.xpath('//a/@href').extract()]

        # - Printing the extracted data for logging.
        print("\n ----DATA\n\n%s\n" % json.dumps({title : {'text': text,
                        'refs' : hrefs }}))

        # - Yielding the extracted dataset as dict
        yield {'title': title,
               'text': text,
               'refs' : hrefs }
        # - Here we find the actual spider.
        # - This goes through all a_hrefs and scrapes the needed data.
        for next_page in response.xpath('//a/@href').extract():
            if next_page is None:
                continue
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)


I am working on the file "SearchEngine.ipynb".
The first task is:
b) Ausführung
Die Ausführung erfolgt außerhalb des Notebooks über subprocess.check_output().
Can you write Python code for it?

# - Here we call the scrapy process.
#
# - This is needed to call this inside the notebook.
# - Scrapy concatenates all outputs (with destroying the json)
#   so we need to remove it first.
!rm ./my_spider.json

# - Executing the spider.
pout = check_output('scrapy runspider my_spider.py -o my_spider.json', shell=True)
# - Writing the output into logfile.
with open('./my_spider.log', 'w') as logfile:
    logfile.write(pout.decode("utf-8"))


I am working on the file "SearchEngine.ipynb".
The first task is:
f) Scoring tfidf und pagerank
Um tfidf und pagerank in einem Wert zu vereinen, werden diese über eine Multiplikation zusammengebracht.
$$\mbox{score} = \mbox{tf_idf}(w, d) \cdot \mbox{rank}(d)$$
Can you write Python code for it?

r = pd.read_csv('rank.txt', index_col=0)
s = pd.read_csv('tfidf_search.txt', index_col=0)

score = pd.DataFrame(r.values * s.T.values, index=r.index, columns=s.index).T
score.to_csv('pageranke_search.txt')
score


I am working on the file "Second Order Response.ipynb".
The first task is:
All basic second order responses
Now we'll plot everything on a single plot
Can you write Python code for it?

fig, ax = plt.subplots()
ax.plot(time, resp1, label='Overdamped')
ax.plot(time, resp2, label='Underdamped')
ax.plot(time, resp3, label='Undamped')
ax.plot(time, resp4, label='Critically Damped')
ax.grid()
ax.legend()
plt.show()


I am working on the file "Second Order Response.ipynb".
The first task is:
Critically Damped Response
Two repeated poles on the real axis
$$
G(s) = \frac{9}{(s +3)^2}
$$
Can you write Python code for it?

G4 = signal.TransferFunction([9], [1, 6, 9])
time, resp4 = signal.step(G4)

fig, ax = plt.subplots()
ax.plot(time, resp4)
ax.grid()
plt.show()


I am working on the file "Second Order Response.ipynb".
The first task is:
Effect of $\omega_n$
Can you write Python code for it?

# plot many responses for varying zeta
time = np.linspace(0, 10, 100)
u = np.ones_like(time)
wn = np.linspace(1, 5, 5)
zeta = 0.5
fig, ax = plt.subplots()

for w in wn:
    num = [w**2]
    den = [1, 2*zeta*w, w**2]
    tout, resp, x = signal.lsim((num, den), u, time)
    ax.plot(tout, resp, label='wn={}'.format(w))

ax.grid()
ax.legend()
plt.show()


I am working on the file "Second Order Response.ipynb".
The first task is:
Effect of $\zeta$
Can you write Python code for it?

# plot many responses for varying zeta
time = np.linspace(0, 10, 100)
u = np.ones_like(time)
wn = 1
zeta = np.linspace(0.1, 1.1, 5)
fig, ax = plt.subplots()

for z in zeta:
    num = [wn**2]
    den = [1, 2*z*wn, wn**2]
    tout, resp, x = signal.lsim((num, den), u, time)
    ax.plot(tout, resp, label='zeta={:.2f}'.format(z))

ax.grid()
ax.legend()
plt.show()


I am working on the file "Second Order Response.ipynb".
The first task is:
Underdamped Response
Two complex poles in the left half plane
$$
G(s) = \frac{9}{s^2 + 2s + 9}
$$
Can you write Python code for it?

G2 = signal.TransferFunction([9], [1, 2, 9])
time, resp2 = signal.step(G2)

fig, ax = plt.subplots()
ax.plot(time, resp2)
ax.grid()
plt.show()


I am working on the file "Second Order Response.ipynb".
The first task is:
We want to investigate the relationship between the poles of a second order system, the damping ratio and natural frequency, and the various performance specifications.
Consider the general second order response for the transfer function:
\begin{align}
    G(s) = \frac{b}{s^2 + a s +b} = \frac{\omega_n^2}{s^2 + 2 \zeta \omega_n s + \omega_n^2}
\end{align}
subject to the the unit step input:
\begin{align}
    R(s) = \frac{1}{s}
\end{align}
Overdamped Response
Two real poles in the left half plane
$$
G(s) = \frac{9}{s^2 + 9s + 9}
$$
Can you write Python code for it?

G1 = signal.TransferFunction([9], [1, 9, 9])
time, resp1 = signal.step(G1)

fig, ax = plt.subplots()
ax.plot(time, resp1)
ax.grid()
plt.show()


I am working on the file "SecretCodes.ipynb".
The first task is:
(Did you forget to switch "everyletter" and "passphrase"?)
Finishing up
As our final task, we're going to give the user the option to encode or decode with the same script. Let's use "input" to ask the user whether she's encoding or decoding. If she's decoding, let's leave the table just like it is above. If she's encoding, let's rebuild the table like we did originally. Try it yourself on the code below. My answer is beneath that.
Can you write Python code for it?

#First, create our substitution table
table = {}
everyletter = "abcdefghijklmnopqrstuvwxyz"

sentence = "the quick brown fox jumped over the lazy dogs"
#Remove duplicate letters
passphrase=""
for letter in sentence:
    if letter not in passphrase and letter is not ' ':
        passphrase = passphrase + letter
print (passphrase)

#Build the table
for num in range(26):
    table[ passphrase[num]] = everyletter[num]
table[' '] = ' '

#Get a message from the user
uncoded_message = input("Type your message here, then press enter: ")

#Encode and print the message
coded_message = ""
for letter in uncoded_message:
    coded_message = coded_message + table[letter]
print (coded_message)

#First, create our substitution table
table = {}
everyletter = "abcdefghijklmnopqrstuvwxyz"

sentence = "the quick brown fox jumped over the lazy dogs"
#Remove duplicates
passphrase=""
for letter in sentence:
    if letter not in passphrase and letter is not ' ':
        passphrase = passphrase + letter
print (passphrase)

#Build a table for decoding
for num in range(26):
    table[ passphrase[num]] = everyletter[num]
table[' '] = ' '

#****  This is the new part. If we're encoding, we rebuild the table
#         But we switch everyletter and passphrase
task = input("Are you encoding or decoding?")
if task == "encoding":
    #Build a table for encoding instead
    print ("Remaking table for encoding...")
    for num in range(26):
        table[ everyletter[num]] = passphrase[num]

print (table)

#Get a message from the user
uncoded_message = input("Type your message here, then press enter: ")

#Encode and print the message
coded_message = ""
for letter in uncoded_message:
    coded_message = coded_message + table[letter]
print (coded_message)


I am working on the file "SecretCodes.ipynb".
The first task is:
A key can only appear in the left column one time. If I try to assign one letter on the left column to two different letters on the right, the dictionary will store the last value.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
Aha. No message that time. Notice that the indenting rules are the same for "if" statements as for "for" statements. As long as you indent, Python will treat each new statement as part of the "if" clause and only execute it if the "if" condition is true. What if I'm not Luke?
Next, let's let the user decide her own name.
Can you write Python code for it?

name = input("What is your name? ")
if name == "Luke":
    print ("May the force be with you, " + name)


I am working on the file "SecretCodes.ipynb".
The first task is:
BREAK TIME!
Congratulations! You're about halfway to the end. Take a minute to stand up, stretch your legs and savor your new  knowledge of Python dictionaries, lists and loops. Then, push Ctrl-Enter in the box below to watch the Minions. When you're done, we'll use the table we just created to encode our message.
Can you write Python code for it?

from IPython.display import YouTubeVideo
YouTubeVideo("rl6-zJharrs")


I am working on the file "SecretCodes.ipynb".
The first task is:
But what if someone discovered our passphrase ("the quick brown fox...")? We'd have to change each of the individual letters. Instead, we can tell Python to read the letters from the strings, everyletter and sentence, that we created above. Take a look at this. We're using some fancier Python tricks that I'll explain in a minute.
Can you write Python code for it?

table={}
table[ everyletter[0]] = sentence[0]
table[ everyletter[1]] = sentence[1]
table[ everyletter[2]] = sentence[2]
table[ everyletter[3]] = sentence[3]
table[ everyletter[4]] = sentence[4]
#And on and on...
table


I am working on the file "SecretCodes.ipynb".
The first task is:
Don't be afraid to change the code in the boxes. You'll learn a lot by playing around, so don't be shy. Make some changes to the code in the boxes, then push Ctrl-Enter to see what you changed. You might get an error from Python. That's OK. See if you can figure out how to fix it. As you play around, remember that the notebook is remembering your changes. If you want to clear the notebook's memory and start again, look for the menu option above called "Kernel." Select "Restart" from that sub menu.
Quick tip: In the box above, make sure to put the quotation marks around your letters.
Now that our table has some values in it, we can read from it like this:
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
Don't go on until you click into the box above and push Ctrl+Enter. You should see {} appear below the box. One more thing about Jupyter notebooks. Each time you execute a box, Python remembers what you've done. Here, we created a dictionary called "table." When we refer to "table" in the next box, Python will remember that "table" is an empty dictionary. The code in the box below adds one entry to your dictionary with the letter 'a' in the left column and 'n' in the right column. Try it out by pushing Ctrl-Enter in the box below.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
Getting Input From the User
It's a lot of work to modify your program for every new message you want to encode. Let's give the message another name like "uncoded_message"
Can you write Python code for it?

coded_message = ""
for letter in uncoded_message:
    coded_message = coded_message + table[letter]
print (coded_message)


I am working on the file "SecretCodes.ipynb".
The first task is:
Here, we gave Python a list of three names. For each name on the list, Python executes the commands that follow, replacing "name" with one of the names in the list. This is the first time we've seen + in Python, but it's an easy one. "Hi, " + name, just means that we add each name in the list to the end of "Hi, " and send that to print.
Try editing the loop above. Add your name (maybe it's Homer?). Make a list of your favorite sports teams and make Python cheer for them.
One tricky rule in Python involves indenting. It's possible to put lots of commands inside one for loop, but Python needs to be able to know which commands are in the loop and which are not. Each line that we want to be part of the loop, we indent, but we don't indent the for the loop statement itself. When Python sees a line that's not indented, it knows you've finished writing the loop. Take a look at this. Change the indenting and see what happens. What if you don't indent the "I'll stop you"? What if you do indent "You'll never get away with this"? Try it!
Can you write Python code for it?

for villain in ["Kylo Ren", "The Joker", "Magneto", "Megamind"]:
    print ("Oh no! It's " + villain)
    print ("I'll stop you!")
print ("You'll never get away with this.")


I am working on the file "SecretCodes.ipynb".
The first task is:
Important note for instructors: If students are getting an error above, you may be using Python version 2.7. If you can switch to Python 3, it will work better. Otherwise, you can get around these errors by putting your answers to "input" in quotation marks. For example, when it asks, What is your name? type "Marcus" with the quotation marks.
Let use the same thing for getting a secret message. Modify the code below to use input to create uncoded_message.
Can you write Python code for it?

uncoded_message = input("What message should I encode?")
coded_message = ""
for letter in uncoded_message:
    coded_message = coded_message + table[letter]
print (coded_message)


I am working on the file "SecretCodes.ipynb".
The first task is:
In a Python list, position 0 is the very start of the list. Now, there are 4 letters in the list. What do you think will happen if we ask for the letter in position 4?
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
In fact, what I'd like to do is to take an easy to remember phrase and use it to determine the right hand side of my table. I'd like to put 'abcdefghijklmnopqrstuvwxyz' down the left hand column and 'the quick brown fox jumped over the lazy dogs' down the right hand side. So 'a' changes to 't'. 'b' changes to 'h'. 'c' changes to 'e' and so on.

Old letter
	New letter

a	t

b	h

c	e

d	q

e	u

f	i

g	c

h	k

i	b

...	...

How can I do this in Python? We can write a loop to create a dictionary from two strings. Let's build the same string as before.
Can you write Python code for it?

sentence = "the quick brown fox jumped over the lazy dogs"


I am working on the file "SecretCodes.ipynb".
The first task is:
In the above code, we made a few other changes. Can you see them? We added some lines beginning with #. When we begin a line with #, we're telling Python that the line is just for other humans to read and Python ignores it. So, we can put whatever we want there and it won't affect our program. It's a good idea to put comments in your program so someone else knows what you're doing.
Decoding your message
Our encoded messages aren't much good if we can't decode them! To decode a message encoded with a substitution cipher, we switch the columns of the table. If during encoding, we replaced all the a's with t's, then to decode we should change the t's back into a's. But our table generated with the "quick brown fox" sentence creates a problem. Here it is below.

Old letter
	New letter

	Old letter
	New letter

A	T		N	F

B	H		O	O

C	E		P	X

D	Q		Q	J

E	U		R	U

F	I		S	M

G	C		T	P

H	K		U	E

I	B		V	D

J	R		W	O

K	O		X	V

L	W		Y	E

M	N		Z	R

In this table, 'c', 'u' and 'y' are all being changed into 'e'. So, when my encoded message contains an 'e', how will I know whether if began as a c, u or y?

We can solve this by making sure each letter appears only once in 'sentence.' We could, for example, assign sentence to be 'thequickbrownfxjmpdvlazygs'. This is easy to do and gives a well-behaved table, but with just a little thought, we can get Python to remove the duplicate...
Can you write Python code for it?

name = "Luke"
if name is "Luke":
    print ("May the force be with you, " + name)


I am working on the file "SecretCodes.ipynb".
The first task is:
It's the space! Python is complaining because we asked for the table entry with a space, ' ', in the left column. But there is no such entry. Remember when we called the left hand column the "keys"? A KeyError means we asked for a key that isn't in the table. It even told us the incorrect key was ' '--the space! There are several ways to solve this. What would you do? Take a minute and try it.
One way to solve this is just to add a dictionary entry for ' '.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
Just like before, we can treat it like a list of letters.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
Now, let's add this to our main program. One quick tip. For now, when our program asks for input, you might want to use all lower case letters--no capitals and no punctuation. You're welcome to try anything you want, but don't be frustrated by the error messages. We'll discuss the reason for those a little later.
Can you write Python code for it?

#First, create our substitution table
table = {}
everyletter = "abcdefghijklmnopqrstuvwxyz"
sentence = "thequickbrownfoxjumpedoverthelazydogs"
for num in range(26):
    table[ everyletter[num]] = sentence[num]
table[' '] = ' '

#Get a message from the user
uncoded_message = input("Type your message here, then press enter: ")

#Encode and print the message
coded_message = ""
for letter in uncoded_message:
    coded_message = coded_message + table[letter]
print (coded_message)


I am working on the file "SecretCodes.ipynb".
The first task is:
Now, let's create another string like this.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
Oops! It seemed to be doing fine, but we crashed on the 5th letter. Python called it a "KeyError". What do you think that means?
We'll need to do some "debugging." Try modifying your loop like this. This way, we'll see each letter before and after it's encoded. We won't leave this in out final program, but it will help us to find the problem.
Can you write Python code for it?

for letter in "this is a super secret message":
    print ("old: " + letter)
    print ("new: " + table[letter])


I am working on the file "SecretCodes.ipynb".
The first task is:
Ouch! Errors again. Unfortunately, lots of computer programming is finding problems ("bugs") in your code. Try to solve the problem above. It might help to add some "print" statements.
If you couldn't find the problem above (which is OK. It's a hard bug to see), I'll tell you that we've gone to the trouble of creating a "passphrase" with no spaces or duplicates, but then we still used "sentence" to create our table. In place of the line
table[ everyletter[num]] = sentence[num]

write
table[ everyletter[num]] = passphrase[num]

See if you get better answers.
Decoding
At last, we're ready to do some decoding. Suppose your friend encoded a message with the program above and sent it to you. The message you got was "nuuv nu bf vku jtpo tv dby vkbpvg". How would you decode it?
Well, if we can build the same table, we can use it in reverse. In our new table m's become n's during encoding. So, during decoding, I change all the n's back to m's. All the e's became u's so I change all u's back to e's. The t's were changed to v's, so I change them back to t's and so on. Already I know that the first two words of the message are "meet me". Here's the full table so you can decode the rest of the message. Once you're done, we'll see how to do get Python to do it.

Old letter
	New letter

	Old letter
	New...
Can you write Python code for it?

#First, create our substitution table
table = {}
everyletter = "abcdefghijklmnopqrstuvwxyz"

sentence = "the quick brown fox jumped over the lazy dogs"
#Remove duplicate letters
passphrase=""
for letter in sentence:
    if letter not in passphrase and letter is not ' ':
        passphrase = passphrase + letter
print (passphrase)

#Build the table
for num in range(26):
    table[ everyletter[num]] = passphrase[num]
table[' '] = ' '

#Get a message from the user
uncoded_message = input("Type your message here, then press enter: ")

#Encode and print the message
coded_message = ""
for letter in uncoded_message:
    coded_message = coded_message + table[letter]
print (coded_message)


I am working on the file "SecretCodes.ipynb".
The first task is:
Our string acts just like a list
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
Python first tests
name is "Anakin"

then the "not" tells Python to reverse that decision and execute the code only if the name is not Anakin.
Removing our duplicates with "if"
Now, let's use an if loop to remove the duplicates from our sentence. It looks a lot like our greeting loop above.
Can you write Python code for it?

sentence = "the quick brown fox jumped over the lazy dogs"
passphrase = ""
for letter in sentence:
    if not letter in passphrase:
        passphrase = passphrase + letter
print (passphrase)


I am working on the file "SecretCodes.ipynb".
The first task is:
So, to make our table, we make a list of numbers from 0 to 25, then for each number, Python repeats the command
table[ everyletter[num] ] = sentence[num]

but it replaces 'num' with each of the numbers in the list. So it's exactly the same as writing
table[ everyletter[0] ] = sentence[0]
table[ everyletter[1] ] = sentence[1]
table[ everyletter[2] ] = sentence[2]
table[ everyletter[3] ] = sentence[3]
table[ everyletter[4] ] = sentence[4]
table[ everyletter[5] ] = sentence[5]
...
(skip a few)
...
table[ everyletter[25] ] = sentence[25]

except we only had to write those two lines. Much easier! (P.S. Why just 25? What happened to 26?)
We can combine everything we've done so far into one script. Read it through carefully and see if you can describe what each line does.
Can you write Python code for it?

table = {}
everyletter = "abcdefghijklmnopqrstuvwxyz"
sentence = "thequickbrownfoxjumpedoverthelazydogs"
for num in range(26):
    table[ everyletter[num]] = sentence[num]
table


I am working on the file "SecretCodes.ipynb".
The first task is:
That looks almost right. It would be perfect if not for that lousy space. To get rid of that, we can use "and" to test two different things. With "or" we only needed one of the two tests to be true ("either Luke OR Leia") but with "and", both statements must be true. Try this.
Can you write Python code for it?

sentence = "the quick brown fox jumped over the lazy dogs"
passphrase = ""
for letter in sentence:
    if letter not in passphrase and letter is not ' ':
        passphrase = passphrase + letter
print (passphrase)


I am working on the file "SecretCodes.ipynb".
The first task is:
That looks easy enough.
Can you write Python code for it?

name = "Anakin"
if name is "Luke":
    print ("May the force be with you, " + name)


I am working on the file "SecretCodes.ipynb".
The first task is:
The "range" function just generates a list of numbers beginning with zero. The code below creates a list from 0 to 4 (5 total numbers), then prints each one.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
The colon (:) separates a "key" from its "value."  'a':'n' means that all the a's become n's during encoding.
What if we ask for a table entry that hasn't been set yet?
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
The first line, newletter = table['a'], tells Python to read the entry we gave it for 'a' and call it by a new name, newletter. In this case, table['a'] is 'n'. After that, everytime we refer to newletter Python will remember that we told it newletter is 'n'. So, when we ask Python to print newletter, it remembers and prints 'n'. newletter is what programmers call a 'variable'--a name that refers, in your program, to some other value.
A few more things about our Python tables (also called 'dictionaries'). The values on the left hand side of the table are called the "keys." The right hand are called the "values." Let's add a few rows to our table, then ask Python some questions. Push Ctrl-Enter in the boxes below and see what Python answers.
Can you write Python code for it?

table['b'] = 'f'
table['c'] = 'r'
print(table)

table.keys()

table.values()

print(table['c'])
print(table)


I am working on the file "SecretCodes.ipynb".
The first task is:
The other way is to explicitly leave Anakin out. Python also understands "not", but in a funny way. Watch.
Can you write Python code for it?

for name in ["Luke", "Leia", "Anakin"]:
    if not name is "Anakin":
        print ("May the force be with you, " + name)


I am working on the file "SecretCodes.ipynb".
The first task is:
The output above just looks like two quote marks, but there's actually a space between them. The 4th "letter" in our string is actually a space.
Take a minute to write some code yourself involving strings. You can edit the code in the box above and push Ctrl-Enter to execute it. Can you figure out which letter is 'q'? Or 'b'? What if you pick a number that's too large, like 100?
Creating a cipher table from a sentence
Let's create a table we can use to encode and decode our messages. I want to change all of my a's into t's. How can we create a Python dictionary to do that?
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
The spaces before the print statements tell us whether they're part of the loop to be executed once for each villain, or just a lone command to be executed only once.
What about this?
Can you write Python code for it?

for villain in ["Kylo Ren", "The Joker", "Magneto", "Megamind"]:
    print ("Oh no! It's " + villain)
print ("I'll stop you!")
    print ("You'll never get away with this.")


I am working on the file "SecretCodes.ipynb".
The first task is:
This is pretty slick. All we have to do is replace "this is a super secret message" with our own and Python does the rest of the work. Now, it's time to play around. Change the script above to encrypt a message of your own. One word of warning. We're not ready to use capital letters or punctuation yet. Use just lower case letters.
You can also try replacing "thequickbrownfox.." with your own sentence. What if your sentence is all x's ("xxxxxxxxxxxxx")?
Here are some other things to try:
- Try encoding "abcdefghijklmnopqrstuvwxyz" as your secret message? Where did the "lazy dogs" go?
- Encode your message twice to make it harder to crack. You can do this by putting your encoded output in as your secret message, but there's an easier way. What if you replace the line
    coded_message = coded_message + table[letter]

with
     coded_message = coded_message + table[table[letter]]

What do you expect it to do? See if you can predict the result for a short message like your name.
- Can you decode your message? What happens if your switch the alphabet and the sentence? Why?
Here's another copy of the same code so you'll still have a clean copy to refer to as you play around.
Can you write Python code for it?

table = {}
everyletter = "abcdefghijklmnopqrstuvwxyz"
sentence = "thequickbrownfoxjumpedoverthelazydogs"
for num in range(26):
    table[ everyletter[num]] = sentence[num]
print (table)
table[' '] = ' '
coded_message = ""
for letter in "my teacher is a handsome genius":
    coded_message = coded_message + table[letter]
print (coded_message)


I am working on the file "SecretCodes.ipynb".
The first task is:
Uh-oh! Can you find and fix the problem above?
We need to assign uncoded_messageto be something. We can add a line like this:
uncoded_message = "this is a super secret message"

Add it to the program above and see how it works. Make sure to add it <i>before</i> the loop. Python runs your commands starting from the top. Before it can use the variable uncoded_message it needs you to tell it what uncoded_message is.
Instead of having the secret message in the program, there is a way to ask the user to provide the message. The command for this is "input." Try this.
Can you write Python code for it?

name = input("What is your name? ")
print ("Well, hello, " + name)


I am working on the file "SecretCodes.ipynb".
The first task is:
Using our table to encode
Welcome back! We're almost ready to encode our message using our table. Start with this for loop. Before you hit Ctrl-Enter, see if you can predict how Python will respond. Then run it and see if you were right.
Can you write Python code for it?

for letter in "this is a super secret message":
    print (letter)


I am working on the file "SecretCodes.ipynb".
The first task is:
Wait, but isn't 'e' the third letter in the list? It's important to remember that computers start counting from zero.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
We combined the for loop that we already know with the if statement we're just learning about. We made a list and for every name in the list we first checked if that name is "Luke", then sent a message only to Luke.
The indentation was tricky here. Look at the line that starts with print. We indented that one a long way! That's because we wanted that line to be part of the "if" code. But the "if" statement was already indented because it's in the for loop. So we indented it twice. If we don't indent enough, we'll get an error from Python. Try it. One rule about Python is that after a line that ends with a colon (like if and for statements) we always have to indent one more level.
Poor Leia. It's a shame to leave her out. (Spoiler alert: she's Luke's sister). We can include her in one of two ways. Python understands the word "or", so we can give Python two names.
Can you write Python code for it?

for name in ["Luke", "Leia", "Anakin"]:
    if name is "Luke" or name is "Leia":
        print ("May the force be with you, " + name)


I am working on the file "SecretCodes.ipynb".
The first task is:
We did it! This is just what we'd expect if we encoded this message by hand.
We can do a few things to improve it. First, we can create a new string rather than printing our encoded message with one letter on each line. We'll first create a string that has no letters in it. As we encode each letter, we'll add it to the string. Then we'll print it at the end.
Can you write Python code for it?

coded_message = ""
for letter in "this is a super secret message":
    coded_message = coded_message + table[letter]
print (coded_message)


I am working on the file "SecretCodes.ipynb".
The first task is:
We just asked Python, "Is d one of the keys in our table?" Python said, "No."
Now, let's create a table entry for 'd' and ask again.
Can you write Python code for it?


I am working on the file "SecretCodes.ipynb".
The first task is:
We're going to use these two strings to create a table like this

Old letter
	New letter

a	t

b	h

c	e

d	q

e	u

f	i

g	c

h	k

i	b

j	r

k	o

l	w

m	n

n	f

o	o

p	x

q	j

r	u

s	m

t	p

u	e

v	d

w	o

x	v

y	e

z	r

To create this list in Python, we could do this:
Can you write Python code for it?

table={}
table['a']='t'
table['b']='h'
table['c']='e'
table['d']='q'
table['e']='u'
table['f']='i'
table['g']='c'
#And on and on...
table


I am working on the file "SecretCodes.ipynb".
The first task is:
What changed? Why? This is another good chance to play around by writing your own code.
Loops in Python
Instead of writing 26 lines like table[ everyletter[14]] = sentence[14], I'd like to write it just once, then have the computer repeat it 26 times increasing the number each time. For this, we use a "for loop." Try this
Can you write Python code for it?

table={}
for num in range(26):
    table[ everyletter[num]] = sentence[num]
table


I am working on the file "SecretCodes.ipynb".
The first task is:
What do you think this error means? (Hint: "index" is the number inside the square brackets.)
The first element in our list is number 0. The last is number 3.
A quick note: if Python starts responding to you with errors like 'myList' is not defined it usually means you missed executing one of the code boxes. Make sure you push Ctrl-Enter in each box with a In [ ] next to it.
Python strings are lists
A bunch of text all together in Python is called a "string." Here's a string
Can you write Python code for it?

myString = "the quick brown fox jumped over the lazy dogs"
myString


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
Comments
The character # marks the beginning of a comment. Any text after the # will be ignored until the end of the line, with the exception of functional comments.
Functional comments are used to:

change the encoding of the source file of the program by adding a comment with the text # - * - coding:  <encoding> - # - at the beginning of the file, in which <encoding> is the file encoding (usually latin1 or utf-8). Changing encoding is required to support characters that are not part of the English language, in the source code of the program.
define the interpreter that will be used to run the program on UNIX systems, through a comment starting with #! at the beginning of the file, which indicates the path to the interpreter (usually the comment line will be something like #!/usr/bin/env python ).

Block Comments
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).
Paragraphs inside a block comment are separated by a line containing a single # .
```python
Date:
Time:
Author:
Method Name:
Description:
```
Inline Comments
An inline comment is a comment statement on the same line as a code statement and they are usually separated by at least two spaces from the statement and should start with a # and a single space.
Inline comments are unnecessary and in fact distracting if they state the obvious. Don't do this:
python
x = x + 1                 # Increment x
But sometimes, it is useful as shown below:
python
x = x + 1                 # Compensate for border
Tips for Comments

Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of...
Can you write Python code for it?

#!/usr/bin/env python

# A code line that shows the result of 7 times 3
# A CODE LINE THAT SHOW THE RESULT OF 7 TIMES 3 (BAD Comments)

print (7 * 3) # This is also a comment
"""
This is a multi
line comment / String
"""
st = '''
This is a multi line

String
"With me"
'
'
'''
print(st)


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
For those C/C++/Java developers who are not initially comfortable without { can also use #{ #} pair, as shown in the example below, to denote the starting block and ending blocks.
Can you write Python code for it?

if True: #{
    print("Answer")
    print("True")
#}
else: #{
    print("Question")
    print("False")
#}


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally.

For new code Knuth's style is suggested.

Blank Lines

Surround top-level function and class definitions with two blank lines.
Method definitions inside a class are surrounded by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character as whitespace; Many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place.

### Imports
Imports should usually be on separate lines, e.g.:
Can you write Python code for it?

# Yes:
import os
import sys

# No:
import sys, os

# It's okay to say this though:
from subprocess import Popen, PIPE

#from abc import Popen

from subprocess import * # BIG NO

from os import * # -> xyz
from sys import * # -> xyz

# from os import xyz as os_xyz
# from sys import xyz as sys_xyz


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
In the example given above, we have uniform four&eight spaces respectively and in both examples, the code worked without any issue. You will also note that in the second example the code is not very readable and the first example it's readable. So, please choose count of spaces which suits your need.

!!! NOTE !!!:
One can choose any number of spaces from 1 - inifinity but have to stick to them, most commonly used spaces are 2 or 4.

Execution of below block of code will result in error as the indentation level is not uniform. In line 5 we have few extra spaces without any cause, hence the code will fail to execute.
Can you write Python code for it?

if (True):
    print("True")
else:
    print("Test")
       print("False")


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
Indentation

Use 4 spaces per indentation level
If your code has continuation lines, then they should align wrapped elements either vertically using Python''s implicit line joining inside parentheses, brackets and braces, or using a hanging indent.
When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.
Can you write Python code for it?

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Aligned with opening delimiter.
foo = long_function_name("var_one", "var_two",
                         "var_three", "var_four")

# Hanging indents should add a level.
foo = long_function_name(
    "var_one", "var_two",
    "var_three", "var_four")


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
Lets fix the above issue, by setting the indentation and execute the code again
Can you write Python code for it?

if True:
    print("Answer")
    print("True")
else:
    print("Question")
    print("False")


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
Multiline code

In Python, multi-line code is supported by using the backslash character (\) at the end of the line or parentheses, brackets or braces in expressions that use such characters.
Examples of broken lines:
Can you write Python code for it?

# A line broken by backslash
a = 7 * 3 + \
5 / 2

# A list (broken by comma)
b = ['a', 'b', 'c',
'd', 'e']

# A function call (broken by comma)
c = range(1,
        11)

# Prints everything
print(a, b, c)

# For i on the list 234, 654, 378, 798:
for i in [234, 654, 378, 798]:
    # If the remainder dividing by 3 is equal to zero:
    if i % 3 == 0: #{
       # Prints...
        print (i, '/ 3 =', i / 3)
    #}


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
Tabs or Spaces?

"""" Spaces are the preferred indentation method """"

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Python 3 disallows mixing the use of tabs and spaces for indentation.

Maximum Line Length

Limit all lines to a maximum of 79 characters.

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.

Limiting the required editor window width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.

The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters (effectively increasing the maximum length to 99 characters), provided that comments and docstrings are still wrapped at 72 characters.

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple with -statements cannot use implicit continuation, so backslashes are acceptable:
Can you write Python code for it?

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_04. Syntax.ipynb".
The first task is:
or it may be lined up under the first character of the line that starts the multi-line construct, as in:
Can you write Python code for it?

def some_function_that_takes_arguments(a1,a2,a3,a4,a5,a6):
    pass

my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f'
)


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
2. Assigning multiple values to multiple variables:
Can you write Python code for it?

x, y, z = 10, 20, 30
print(x)
print(y)
print(z)
print(id(x))
print(id(y))
print(id(z))

x, y, z = 10, 120, 10
print(x)
print(y)
print(z)
print(id(x))
print(id(y))
print(id(z))


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
In the above example, all x, y and z are pointing to same memory location which contains 1000, which we are able to identify by checking the id of the variables. They are pointing to the same memory location, thus value of id for all three are same.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
In the above example, current_month is the variable name and "MAY" is the value associated with it. Operation performed in the first line is called assignment and such statements are called assignment statements. Lets discuss them in details.
Assignment Statements
You’ll store values in variables with an assignment statement. An assignment statement consists of a variable name, an equal sign (called the assignment operator), and the value to be stored. If you enter the assignment statement current_month = "MAY", then a variable named current_month will be pointing to a memory location which has the string value "MAY" stored in it.

In Python, we do not need to declare variable explicitly. They are declared automatically when any value is assigned. The assignment is done using the equal (=) operator as shown in the below example:
Can you write Python code for it?

current_month = "MAY" # A comment.
date = 10


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
NOTE:
The value of refcount will almost always be more than you think. It is done internally by python to optimize the code. I will be adding more details about it in "Section 2 -> Chapter: GC & Cleanup"

Multiple Assignment:
In multiple assignment, multiple variables are assigned values in a single line. There are two ways multiple assignment can be done in python. In first format all the variables point to the same value and in next all variables point to individual values.
1. Assigning single value to multiple variables:
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
Now, lets test something else. Can different data types impact the behavior of python memory optimization. We will first test it with integer, string and then with list.
Can you write Python code for it?

### INTEGER
x=1000
y=1000
z=1000
print(x)
print(y)
print(z)
print(id(x))
print(id(y))
print(id(z))

### INTEGER
x=24
y=24
z=24
print(x)
print(y)
print(z)
print(id(x))
print(id(y))
print(id(z))

### String
x="1000"
y=1000
z="1000"
print(x)
print(y)
print(z)
print(id(x))
print(id(y))
print(id(z))


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
The pictorial representation of variables from above example.
<img src="files/variables.png">
Now lets perform some actions on the variable current_month and observe the changes happening on it.
In the example shown below, we will reassign a new value JUNE to the variable current_month and observe the effects of it.
Image below shows the process of re-assignation. You will note that a new memory is assigned to the variable instead of using the existing one.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
Variable Names & Naming Conventions
There are a couple of naming conventions in use in Python:
- lower_with_underscores: Uses only lower case letters and connects multiple words with underscores.
- UPPER_WITH_UNDERSCORES: Uses only upper case letters and connects multiple words with underscores.
- CapitalWords: Capitalize the beginning of each letter in a word; no underscores. With these conventions in mind, here are the naming conventions in use.

Variable Names: lower_with_underscores
Constants: UPPER_WITH_UNDERSCORES
Function Names: lower_with_underscores
Function Parameters: lower_with_underscores
Class Names: CapitalWords
Method Names: lower_with_underscores
Method Parameters and Variables: lower_with_underscores
Always use self as the first parameter to a method
To indicate privacy, precede name with a single underscore.
Can you write Python code for it?

pm_name = "Narendra Modi"
prime_minister = "Narendra Modi"
cong_p_name = "Rahul Gandhi"
corrent_name_of_cong_president = "Rahul Gandhi"
cong_president = "Rahul Gandhi"
cname = "RG"


I am working on the file "Section 1 - Core Python/Chapter 01 - Introduction/01_05. Python Identifiers.ipynb".
The first task is:
current_month was initially pointing to memory location containing value MAY and after reassination, it was pointing to a new memory location containing value JUNE and if no other referencing the previous value, then automatically Python GC will clean it at some future time.
Can you write Python code for it?

current_month = "JUNE"
print(id(current_month))

next_month = "JUNE"
print(id(next_month))

next_month = "June"
print(id(next_month))


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.1. Syntax.ipynb".
The first task is:
Comments
The character # marks the beginning of a comment. Any text after the # will be ignored until the end of the line, with the exception of functional comments.
Functional comments are used to:

change the encoding of the source file of the program by adding a comment with the text # - * - coding:  <encoding> - # - at the beginning of the file, in which <encoding> is the file encoding (usually latin1 or utf-8). Changing encoding is required to support characters that are not part of the English language, in the source code of the program.
define the interpreter that will be used to run the program on UNIX systems, through a comment starting with #! at the beginning of the file, which indicates the path to the interpreter (usually the comment line will be something like #!/usr/bin/env python ).

Block Comments
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).
Paragraphs inside a block comment are separated by a line containing a single # .
```python
Date:
Time:
Author:
Method Name:
Description:
```
Inline Comments
An inline comment is a comment statement on the same line as a code statement and they are usually separated by at least two spaces from the statement and should start with a # and a single space.
Inline comments are unnecessary and in fact distracting if they state the obvious. Don't do this:
python
x = x + 1                 # Increment x
But sometimes, it is useful as shown below:
python
x = x + 1                 # Compensate for border
Tips for Comments

Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of...
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.1. Syntax.ipynb".
The first task is:
For those C/C++/Java developers who are not initially comfortable without { can also use #{ #} pair, as shown in the example below, to denote the starting block and ending blocks.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.1. Syntax.ipynb".
The first task is:
In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally.

For new code Knuth's style is suggested.

Blank Lines

Surround top-level function and class definitions with two blank lines.
Method definitions inside a class are surrounded by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character as whitespace; Many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place.

### Imports
Imports should usually be on separate lines, e.g.:
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.1. Syntax.ipynb".
The first task is:
In the example given above, we have uniform four&eight spaces respectively and in both examples, the code worked without any issue. You will also note that in the second example the code is not very readable and the first example it's readable. So, please choose count of spaces which suits your need.

!!! NOTE !!!:
One can choose any number of spaces from 1 - inifinity but have to stick to them, most commonly used spaces are 2 or 4.

Execution of below block of code will result in error as the indentation level is not uniform. In line 5 we have few extra spaces without any cause, hence the code will fail to execute.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.1. Syntax.ipynb".
The first task is:
Indentation

Use 4 spaces per indentation level
If your code has continuation lines, then they should align wrapped elements either vertically using Python''s implicit line joining inside parentheses, brackets and braces, or using a hanging indent.
When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.1. Syntax.ipynb".
The first task is:
Lets fix the above issue, by setting the indentation and execute the code again
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.1. Syntax.ipynb".
The first task is:
line break before or after a binary operator

Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations".
Following the tradition from mathematics usually results in more readable code:
Can you write Python code for it?

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

# No: Not easy to match operators with operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
2. Assigning multiple values to multiple variables:
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
Good Variable Name

Choose meaningful name instead of short name. roll_no is better than rn.
Maintain the length of a variable name. Roll_no_of_a_student is too long?
Be consistent; roll_no or RollNo
Begin a variable name with an underscore(_) character for a special case.

Exercises
Q 1. Find the valid and in-valid variable names from the followings:

balance
current-balance
current balance
current_balance
4account
_spam
42
SPAM
total_$um
account4
'hello'

Q 2. Multiple Choice Questions & Answers

Is Python case sensitive when dealing with identifiers?
a) yes
b) no
c) machine dependent
d) none of the mentioned

What is the maximum possible length of an identifier?
a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned

What does local variable names beginning with an underscore mean?
a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) None of the

Which of the following is true for variable names in Python?
a) unlimited length
b) Only _ and $ special characters allowed in variable name
c) private members should have leading & trailing underscores
d) None of the above
Can you write Python code for it?

_ is used
* To use as ‘Internationalization(i18n)’ or ‘Localization(l10n)’ functions.


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
In the above example, current_month is the variable name and "MAY" is the value associated with it. Operation performed in the first line is called assignment and such statements are called assignment statements. Lets discuss them in details.
Assignment Statements
You’ll store values in variables with an assignment statement. An assignment statement consists of a variable name, an equal sign (called the assignment operator), and the value to be stored. If you enter the assignment statement current_month = "MAY", then a variable named current_month will be pointing to a memory location which has the string value "MAY" stored in it.

In Python, we do not need to declare variable explicitly. They are declared automatically when any value is assigned. The assignment is done using the equal (=) operator as shown in the below example:
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
NOTE:
The value of refcount will almost always be more than you think. It is done internally by python to optimize the code. I will be adding more details about it in "Section 2 -> Chapter: GC & Cleanup"

Multiple Assignment:
In multiple assignment, multiple variables are assigned values in a single line. There are two ways multiple assignment can be done in python. In first format all the variables point to the same value and in next all variables point to individual values.
1. Assigning single value to multiple variables:
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
Note: That value of MAY has not updated but a new memory was allocated for value JUNE and varialbe now points to it.

Later in the chapter, we will show the above senario with more examples.
How to find the reference count of a value
Can you write Python code for it?

########## Reference count ###################
# NOTE: Please test the below code by saving
#       it as a file and executing it instead
#       of running it here.
#############################################
import sys

new_var = 10101010101000
print(sys.getrefcount(new_var))


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
Now, lets test something else. Can different data types impact the behavior of python memory optimization. We will first test it with integer, string and then with list.
Can you write Python code for it?

### INTEGER
x=1000
y=1000
z=1000
print(x)
print(y)
print(z)
print(id(x))
print(id(y))
print(id(z))

### String
x="1000"
y=1000
z="1000"
print(x)
print(y)
print(z)
print(id(x))
print(id(y))
print(id(z))


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
Options can be used to override the default regular expression associated to each type. The table below lists the types, their associated options, and their default regular expressions.
|        Type       |         Default Expression        |
|:-----------------:|:-----------------------------------------:|
|      Argument     | [a-z_][a-z0-9_]                    |
|     Attribute     | [a-z_][a-z0-9_]                    |
|       Class       | [A-Z_][a-zA-Z0-9]                       |
|      Constant     | (([A-Z_][A-Z0-9_]            |
|      Function     | [a-z_][a-z0-9_]                    |
|       Method      | [a-z_][a-z0-9_]                    |
|       Module      | (([a-z_][a-z0-9_]), ([A-Z][a-zA-Z0-9])) |
|      Variable     | [a-z_][a-z0-9_]                    |
| Variable, inline1 | [A-Za-z_][A-Za-z0-9_]                   |
Please find the invalid variables name from the below list
Can you write Python code for it?

this_is_my_number
THIS_IS_MY_NUMBER
ThisIsMyNumber
this_is_number
anotherVarible
This1
this1home
1This
__sd__
_sd


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
The pictorial representation of variables from above example.
<img src="files/variables.png">
Now lets perform some actions on the variable current_month and observe the changes happening on it.
In the example shown below, we will reassign a new value JUNE to the variable current_month and observe the effects of it.
Image below shows the process of re-assignation. You will note that a new memory is assigned to the variable instead of using the existing one.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.2. Python Identifiers.ipynb".
The first task is:
Variable Names & Naming Conventions
There are a couple of naming conventions in use in Python:
- lower_with_underscores: Uses only lower case letters and connects multiple words with underscores.
- UPPER_WITH_UNDERSCORES: Uses only upper case letters and connects multiple words with underscores.
- CapitalWords: Capitalize the beginning of each letter in a word; no underscores. With these conventions in mind, here are the naming conventions in use.

Variable Names: lower_with_underscores
Constants: UPPER_WITH_UNDERSCORES
Function Names: lower_with_underscores
Function Parameters: lower_with_underscores
Class Names: CapitalWords
Method Names: lower_with_underscores
Method Parameters and Variables: lower_with_underscores
Always use self as the first parameter to a method
To indicate privacy, precede name with a single underscore.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/2.3. Maths Operators.ipynb".
The first task is:
Order of Operations

Python uses the standard order of operations as taught in Algebra and Geometry classes. That, mathematical expressions are evaluated in the following order (memorized by many as PEMDAS or BODMAS {Brackets, Orders or pOwers, Division, Multiplication, Addition, Subtraction}) .
(Note that operations which share a table row are performed from left to right. That is, a division to the left of a multiplication, with no parentheses between them, is performed before the multiplication simply because it is to the left.)
| Name  | Syntax    | Description   | PEMDAS Mnemonic   |
|----------------------------   |---------- |----------------------------------------------------------------------------------------------------------------------------------------   |-----------------  |
| Parentheses   | ( ... )   | Before operating on anything else, Python must evaluate all parentheticals starting at the innermost level. (This includes functions.)    | Please    |
| Exponents     | **   | As an exponent is simply short multiplication or division, it should be evaluated before them.    | Excuse    |
| Multiplication and Division   | * / // %  | Again, multiplication is rapid addition and must, therefore, happen first.    | My Dear   |
| Addition and Subtraction  | + -   | They should happen independent to one another and finally operated among eachother    | Aunt Sally    |
Formatting output

round()
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Basics/Starting Point.ipynb".
The first task is:
pass: This function does nothing and acts only as a placeholder for the implementation in future.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/2.3. Operators.ipynb".
The first task is:
1011
"""
OR
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 1
AND
0 0 | 0
0 1 | 0
1 0 | 0
1 1 | 1
"""
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/2.3. Operators.ipynb".
The first task is:
Complex Number
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/2.3. Operators.ipynb".
The first task is:
Complex Vs Numeric
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/2.3. Operators.ipynb".
The first task is:
Numeric Vs Complex
Can you write Python code for it?

a = 10
b = 10 + 21j

# print(a < b)
# print(a > b)
# print(a <= b)
# print(a >= b)
print(a == b)
print(a != b)


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/2.3. Operators.ipynb".
The first task is:
Relational Operators
Can you write Python code for it?

There are following relational operators supported by Python language


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/2.3. Operators.ipynb".
The first task is:
| Syntax    | Math   | Operation Name       |
|---------- |--------|----------------------|
| <         | a < b  | Less- than           |
| >         | a > b  | Greater- than        |
| <=        | a <= b | Less- than- equal    |
| >=        | a >= b | Greater- than- equal |
| ==        | a == b | Equal to             |
| !=        | a != b | not equal to         |
Numeric Vs Numeric
Can you write Python code for it?

a = 10
b = 21.22

print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
print(a == b)
print(a != b)


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/Dictionary.ipynb".
The first task is:
NOTE: Dictionaries are implemented with a hash table and hash of 10.0 and 10 are same, thus  10.0 and 10 keys of dict are same and only one key/value pair is shown for them. Please check the url for details.
- https://stackoverflow.com/questions/32209155/why-can-a-floating-point-dictionary-key-overwrite-an-integer-key-with-the-same-v/32211042#32211042
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/Dictionary.ipynb".
The first task is:
NOTE: Last key will override the previous one
Can you write Python code for it?

print(dic.items())

for i, j in {"a": "test", "b": "test2"}.items():
    print(i, j)

# Progs and their albums
progs = {'Yes': ['Close To The Edge', 'Fragile'],
    'Genesis': ['Foxtrot', 'The Nursery Crime'],
    'ELP': ['Brain Salad Surgery']}

# More progs
progs['King Crimson'] = ['Red', 'Discipline']

# items() returns a list of
# tuples with key and value
for singer, album  in progs.items():
    print(singer, ":=>", album)

for albums in progs.values():
    print(albums)

for prog in progs:
    print(prog, "=>", progs[prog])

# If there is 'ELP', removes
if 'ELP' in progs:
    del progs['ELP']

print(progs)

multid = {'school': 'DMS',
          'students_details': {
              1001: {
               "name": "Mayank",
                  "age": 41
              },
              1002: {
                "name" : "Vishal",
                "age": 42
              },
              1003: {
                  "name": "Rajeev Chaturvedi",
                  "age": 41
              }
          }
        }
print(multid)

print(multid['students_details'][1001])
print(multid['students_details'][1002]['name'])

print(multid['students_details'][1004]['name'])

multid = {'school': 'DMS',
          'students_details': {
              "students":
                  [
                      "Mayank",
                      "Vishal",
                      "Rajeev"
                  ]
          }}
print(multid)

dupli = {
    "meme" : "mjmj",
    "test" : "TESt value",
    "meme" : "wewe"
}

print(dupli)
for k in dupli:
    print(k)

# Matrix in form of string
matrix = '''0 0 0 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 4 0 0
0 0 0 0 0 0 0 3 0 0 0 0
0 0 0 0 0 0 5 0 0 0 0 0
0 0 0 0 6 0 0 0 0 0 0 0'''

mat = {}

# split the matrix in lines
for row, line in enumerate(matrix.splitlines()):

    # Splits the line int cols
    for col, column in enumerate(line.split()):

        column = int(column)
        # Places the column in the result,
        # if it is differente from zero
        if column:
           ...


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/Lists.ipynb".
The first task is:
Appending
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/Lists.ipynb".
The first task is:
NOTE: Only one level of extending happens, apple and camel are still in sub-list
Can you write Python code for it?

fruits.extend(['kiwi', ['Apple', 'Camel']])
print(fruits)


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
>>> TODO !!!
Explain the below examples
Can you write Python code for it?

'{} {}'.format('सूर्य', 'नमस्कार')

'{1} {0}'.format('सूर्य', 'नमस्कार')

s = '{:>30}'.format('सूर्य नमस्कार')
print(s)
print(len(s))

s = '{:>2}'.format('सूर्य नमस्कार')
print(s)
print(len(s))

'{:20}'.format('सूर्य नमस्कार')

'{:4}'.format('Bonjour')

'{:^<5}'.format('Ja')

'{:^7}'.format('こんにちは')

'{:.5}'.format('Bonjour')

## ??????

s = '{:10.5}'.format('testdd नमस्कार')
print(len(s))
print(s)

'{:10.5}'.format('Bonjour')

'{:{align}{width}}'.format('Bonjour', align='^', width='9')

'{:.{prec}} = {:.{prec}f}'.format('Bonjour', 2.22, prec=4)

'{:d}'.format(1980)

'{:f}'.format(3.141592653589793)

'{:2f}'.format(3.141592653589793)

'{:04d}'.format(119)

'{:06.2f}'.format(3.141592653589793)

'{:+d}'.format(119)

'{:+d}'.format(-119)

### Need to find for complex & boolean numbers
## '{:+d+d}'.format(-3 + 2j)

'{:=5d}'.format((- 111))

'{: d}'.format(101)

'{name} {surname}'.format(name='Mayank', surname='Johri')

user = dict(name='Mayank', surname='Johri')
'{u[name]} {u[surname]}'.format(u=user)

lst = list(range(10))
'{l[2]} {l[7]}'.format(l=lst)

from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2017, 12, 23, 14, 15))

class Yoga(object):

    def __repr__(self):
        return 'सूर्य नमस्कार'

'{0!r} <-> {0!a}'.format(Yoga())


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
Concatenation
String concatenation is a process of joining two or more strings into a single string. As we have already discussed that string is an immutable datatype thus we have to create a new string for concatenation, what that means is the original strings will still remain the same and new one will be created using the texts from the originals.
There are multiple ways in which we can achive the concatenation. The most common method of achiving the concatenation, is to use + operator.
Lets take an example, where we have three string's and lets try to concatenate them using it.
Can you write Python code for it?

st_the = "The "
st_action = " ran away !!!"
st = st_the + s + st_action
print(st)
print(s)
print(st_the)
print(st_action)
print(id(st))

print(id(st_the))
print(id(s))
print(id(st_action))

print(dir(s))


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
Create a string from a list of string items
Can you write Python code for it?

" ".join(x)

book_desc = ["This", "book", "is good"]
" ".join(book_desc)


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
NOTE: both r and R work the same way

Formatted String Literal or F-String
F-String are prefixed with f or F. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time. {New in 3.6}
String Operations:
Creation / Assignation
Can you write Python code for it?

s = 'Camel'
print(id(s))

a = 'Roshan\tMusheer'
print(a)


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
Note: The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:

checking: substring in main_string : returns true or false
Can you write Python code for it?

print("ma" in myStr)

print("M" in myStr)

c = "one"
print(c.isalpha())
c = "1"
print(c.isalpha())

superscripts = "\u00B2"
five = "\u0A6B"
five_punjabi = "੫"
ten_hindi = "१०"
num_one = "1"
one = "one"
fractions = "\u00BC"

print(superscripts)
print(five)
print(five_punjabi)
print(ten_hindi)
print(num_one)
print(one)
print(fractions)


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
String Module

Various functions for dealing with text are implemented in the module string.
Can you write Python code for it?

import string

# the alphabet
print(dir(string))

a = string.ascii_letters
print(a)

# Shifting left the alphabet
b = a[1:] + a[0]
print(b)

print(b.__doc__)

print(string.digits)
print(string.hexdigits)
print(help(string.printable))


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
Template
The module also implements a type called Template, which is a model string that can be filled through a dictionary. Identifiers are initialized by a dollar sign ($) and may be surrounded by curly braces, to avoid confusion.
Example:
Can you write Python code for it?

import string

# Creates a template string
st = string.Template('Dated: $when\n$warning occurred in $when $$$what $$what.')

# Fills the model with a dictionary
s = st.substitute({'warning': 'Lack of electricity',
    'when': 'April 3, 2002',
    'what': 'EOM'})

# Shows:
# Lack of electricity occurred in April 3, 2002
print(s)

# Unicode String
u = u'Hüsker Dü'
# Convert to str
s = u.encode('latin1')
print (s, '=>', type(s))

# String str
s = 'Hüsker Dü'
# u = s.decode('latin1')

print (repr(u), '=>', type(u))


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
The operator % is used for string interpolation. The interpolation is more efficient in use of memory than the conventional concatenation.
Symbols used in the interpolation:

%s: string.
%d: integer.
%o: octal.
%x: hexacimal.
%f: real.
%e: real exponential.
%%: percent sign.

Symbols can be used to display numbers in various formats.
Example:
Can you write Python code for it?

# Zeros left
print ('Now is %02d:%02d.' % (6, 30))

# Real (The number after the decimal point specifies how many decimal digits )
print ('Percent: %.1f%%, Exponencial:%.2e' % (5.333, 0.00314))

# Octal and hexadecimal
print ('Decimal: %d, Octal: %o, Hexadecimal: %x' % (10, 10, 10))


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
case-insensitive string comparison
for ASCII strings
Can you write Python code for it?

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are not the same (case insensitive)")


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
format
In addition to interpolation operator %, the string method and function format() is available.

The function format() can be used only to format one piece of data each time.

Examples:
Can you write Python code for it?

peoples = [('Mayank', 'friend', 'Manish'),
('Mayank', 'reportee', 'Roshan Musheer')]

# Parameters are identified by order
msg = '{0} is {1} of {2}'

for name, relationship, friend in peoples:
    print(msg.format(name, relationship, friend))

# Parameters are identified by name
msg = '{greeting}, it is {hour:02d}:{minute:02d}'

print(msg.format(greeting='Good Morning', minute=2, hour=10))
print(msg)
# Builtin function format()
print ('Pi =', format(3.14159, '.3e'))
print ('Pi =', format(3.14159, '.1e'))


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
str in-build module
Strings implement all of the common sequence operations, along with the additional methods described below.
Can you write Python code for it?

myStr = "maya Deploy, version: 0.0.3 "

print(myStr.capitalize())
print(myStr.center(60))
print(myStr.center(60, "*"))
print(myStr.center(10, "*"))

print(myStr.count('a'))
print(myStr.count('e'))

print(myStr.endswith('all'))

print(myStr.endswith('.0.3'))
print(myStr.endswith('.0.3 '))

print(myStr.find("g"))
print(myStr.find("e"))


I am working on the file "Section 1 - Core Python/Chapter 02 - Data Types Part - 1/String.ipynb".
The first task is:
str.isnumeric

Digits,
Fractions,
Subscripts,
Superscripts
Can you write Python code for it?

print(superscripts.isnumeric())
print(five.isnumeric())
print(five_punjabi.isnumeric())
print(ten_hindi.isnumeric())
print(num_one.isnumeric())
print(one.isnumeric())
print(fractions.isnumeric())

print(superscripts.isalnum())
print(five.isalnum())
print(five_punjabi.isalnum())
print(ten_hindi.isalnum())
print(num_one.isalnum())
print(one.isalnum())
print(fractions.isalnum())
ten_One = "10 One"
print(ten_One.isalnum())
tenOne = "10One"
print(tenOne.isalnum())
print("one".isalnum())
print("thirteen".isalnum())


I am working on the file "Section 1 - Core Python/Chapter 03 - Control Flow/3.1 Compound Statements.ipynb".
The first task is:
Imagine that in the above program, 23 is the temperature which was read by  some sensor or manually entered by the user and Normal is the response of the program.
Can you write Python code for it?

a = "apple"
b = "banana"
c = "Mango"
if a == "apple":
    print("apple")
elif b == "Mango":
    print("mango")
elif c == "Mango":
    print("My Mango farm")


I am working on the file "Section 1 - Core Python/Chapter 03 - Control Flow/3.1 Compound Statements.ipynb".
The first task is:
One line if
There are instances where we might need to have
If the code block is composed of only one line, it can be written after the colon:
if temp < 0: print 'Freezing...'

Since version 2.5, Python supports the expression:
<variable> = <value 1> if <condition> else <value 2>

Where <variable> receives <value 1> if <condition> is true and <value 2>  otherwise.
Can you write Python code for it?

x = 20

if x > 10: print ("Hello ")

print("-"*30)

val = 1 if x < 10 else 24
print(val)


I am working on the file "Section 1 - Core Python/Chapter 03 - Loops/Loops.ipynb".
The first task is:
Continue Statement
The continue statement is used in a while or for loop to take the control to the top of the loop without executing the rest statements inside the loop. Here is a simple example.
Can you write Python code for it?

for x in range(8):
    if (x == 3 or x==6):
        print("\tSkipping:", x)
        continue
        print("This should never print")
    else:
        print(x)


I am working on the file "Section 1 - Core Python/Chapter 03 - Loops/Loops.ipynb".
The first task is:
In the above example, "Manish Gupta" is a sequence of characters and for loop traverse that sequence of characters. Also you will note that we are ending the print statement with space instead of new line using the option end=.
Similarly in the below example we are going to use the range function to generate the sequence of numbers starting from 30 and ending with 5 with difference of 5.
The range() function
The function range(m, n, p), is very useful in loops, as it returns a list of integers starting at m through smaller than n in steps of length p, which can be used as the order for the loop.
We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if not provided.
We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).
This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
Can you write Python code for it?

# Output: range(0, 10)
print(range(10))

# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))

# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))

# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))

print(list(range(20, 2, -3)))

print(dir(range(10)))

# Sum 0 to 99
s = 0
for x in range(30, 1, -5):
    print(x)
    s = s + x
print("sum of 30 to 1 with steps -5 is", s)

# Sum 0 to 99
s = 0
for x in range(30, 1, -5):
    print(x)
    s += x
print("sum of 30 to 1 with steps -5 is", s)


I am working on the file "Section 1 - Core Python/Chapter 03 - Loops/Loops.ipynb".
The first task is:
NOTE: When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.
The tricky onces
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 03 - Loops/Loops.ipynb".
The first task is:
Traversing the keys
Can you write Python code for it?

color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
for col in color:
    print(col, color[col])

color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
for value in color.values():
    if(value=="Green"):
        break
    print(value)
else:
    print("Done")

color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
for value in color.values():
    if(value=="Green"):
        continue
    print(value)
else:
    print("Done")


I am working on the file "Section 1 - Core Python/Chapter 03 - Loops/Loops.ipynb".
The first task is:
Usecases for else
A common use case for the else clause in loops is to implement search loops; say you’re performing a search for an item that meets a particular condition, and need to perform additional processing or raise an error if no acceptable value is found:
Can you write Python code for it?

def meets_condition(x):
    return x==20

data = [10, 20, 33, 42, 44]
for x in data:
    if meets_condition(x):
        break
else:
    print("No one met the condition")
print("lets end it")

def meets_condition(x):
    return x==21

data = [10, 20, 33, 42, 44]
for x in data:
    if meets_condition(x):
        break
else:
    print("No one met the condition")
print("lets end it")

print(list(range(2, 4)))
print(4%2)


I am working on the file "Section 1 - Core Python/Chapter 03 - Loops/Loops.ipynb".
The first task is:
we can also have conditions where multiple values are returned every iteration.
Can you write Python code for it?

# Advance code, to be used after learning slicing. Please use instead the other code
# for x in "Manish Gupta"[::-1]:
#     print(x, end=" ")

reverse_text = ""
for char in "Manish Gupta":
    reverse_text = char + reverse_text
print(reverse_text)

x_test = [[1,2],[3,4],[5,6]]

for x in x_test:
    print(x)
    a = x[0]
    b = x[1]
    print (a, b)

x_test = [[1,2],[3,4],[5,6], [7,8,9]]

for x in x_test:
    print(x)

x_test = [[1, 2],[3, 4],[5, 6], [7, 8]]

for x, y in x_test:
    print(x, y)

x_test = [[1, 2],[3, 4],[5, 6], [7, 8, 9]]

try:
    for x, y in x_test:
        print(x, y)
except Exception as e:
    print(e)

x_test = [[1,2],[3,4],[5,6], [7,8,9]]

for x in x_test:
    print(x)
    a = x[0]
    b = x[1]
    print (a, b)


I am working on the file "Section 1 - Core Python/Chapter 04 - Control Flow/3.1 Compound Statements.ipynb".
The first task is:
Imagine that in the above program, 23 is the temperature which was read by  some sensor or manually entered by the user and Normal is the response of the program.
Can you write Python code for it?

a = "apple"
b = "banana"
c = "Mango"
if a == "apple":
    print("apple")
elif b == "Mango":
    print("mango")
elif c == "Mango":
    print("My Mango farm")

x = list(range(10))

a = 0
x.reverse()
print(x)
while x:
    a = x.pop()
    print(a)
print(a)

x = list(range(10))
print(x)
a = 0
x.reverse()
while x:
    a = x.pop(0)
    print(a)
print(a)

items = "This is a test"
for count, item in enumerate(items[1:], start=11):
    print(item, count, end=" ")
    if 'i' in item: break
else:
    print("\nFinished")

print(count)


I am working on the file "Section 1 - Core Python/Chapter 04 - Control Flow/3.1 Compound Statements.ipynb".
The first task is:
if ... else statement
python
if <condition>:
    <code block>
else:
    <code block>
Where:

<condition>: sentence that can be evaluated as true if statement if statemente or false.
<code block>: sequence of command lines.
The clauses elif and else are optional and  several elifs for the if may be used but only  one else at the end.
Parentheses are only required to avoid ambiguity.
Can you write Python code for it?

x = "Anuja"

if x == "mayank":
    print("Name is mayank")
else:
    print("Name is not mayank and its", x)


I am working on the file "Section 1 - Core Python/Chapter 04 - Control Flow/3.1 Compound Statements.ipynb".
The first task is:
if ...elif ... else statement
python
if <condition>:
    <code block>
elif <condition>:
    <code block>
elif <condition>:
    <code block>
else:
    <code block>
Where:

<condition>: sentence that can be evaluated as true or false.
<code block>: sequence of command lines.
The clauses elif and else are optional and  several elifs for the if may be used but only  one else at the end.
Parentheses are only required to avoid ambiguity.
Can you write Python code for it?

# temperature value used to test
temp = 31

if temp < 0:
    print ('Freezing...')
elif 0 <= temp <= 20:
    print ('Cold')
elif 21 <= temp <= 25:
    print ('Room Temprature')
elif 26 <= temp <= 35:
    print ('Hot')
else:
    print ('Its very HOT!, lets stay at home... \nand drink lemonade.')

# temperature value used to test
temp = 60

if temp < 0:
    print ('Freezing...')
elif 0 <= temp <= 20:
    print ('Cold')
elif 21 <= temp <= 25:
    print ('Room Temprature')
elif 26 <= temp <= 35:
    print ('Hot')
else:
    print ('Its very HOT!, lets stay at home... \nand drink lemonade.')


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
Continue Statement
The continue statement is used in a while or for loop to take the control to the top of the loop without executing the rest statements inside the loop. Here is a simple example.
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
NOTE: Bad Code Below
Can you write Python code for it?

while x < 0:
    print("Hello")
else:
    print("Sorry")

# while x > 0:
#     print("Hello")
# else:
#     print("Sorry")


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
NOTE: Please avoid below case
Can you write Python code for it?

for x in range(1, 6):
    for x in range(1, x+1):
        print(x, x)


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
Nested loops
We can also have nested for loops as shown in the below example
Can you write Python code for it?

for x in range(1, 6):
    for y in range(1, x+1):
        print(x, y)


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
Traversing the keys
Can you write Python code for it?


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
Usecases for else
A common use case for the else clause in loops is to implement search loops; say you’re performing a search for an item that meets a particular condition, and need to perform additional processing or raise an error if no acceptable value is found:
Can you write Python code for it?

def meets_condition(x):
    return x==20

data = [10, 20, 33, 42, 44]
for x in data:
    if meets_condition(x):
        break
else:
    print("No one met the condition")
print("lets end it")

def meets_condition(x):
    return x==21

data = [10, 20, 33, 42, 44]
for x in data:
    if meets_condition(x):
        break
else:
    print("No one met the condition")
print("lets end it")

print(list(range(2, 4)))
print(4%2)

n-> 2:
    x <- []
n -> 3:
    x -> 2
    3%2
    Prime number
n -> 4
    x -> [2, 3]
        4%2
n -> 5:
    x -> [2, 3, 4]

for n in [2, 3, 4, 5, 6, 7, 8, 9]:
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n/x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
Uses of forloops

Reading & processing a log file which contains logs one line at a time.

While
Executes a block of code in response to a condition.
Syntax:
while <condition>:
    <code block>
    continue/break/pass
else:
    <code block>

The code block inside the while loop is repeated while the loop condition is evaluated as true.
Example:
Can you write Python code for it?

# Sum 0 to 99
s = 0
x = 1

while x < 100:
    s = s + x
    x = x + 1
else:
    print("!!! Hurry Hurry !!!")
    print(x)

print ("Sum of 0 to 99", s)

# Sum 0 to 99
s = 0
x = 1

while x < 100:
    s += x
    x += 1
else:
    print("!!! Hurry Hurry !!!")
    print(x)

print ("Sum of 0 to 99", s)


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
for loop with a list
Can you write Python code for it?

cols = ["Red", "Green", "Yellow", "White"]

for color in cols:
    print(color)

cols = ["Red", "Green", "Yellow", "White"]

for color in cols:
    print(color)
else:
    print(" ~~~~ Done ~~~~")


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
for loop with dictionary.

Traversing the values.
Can you write Python code for it?

color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
for value in color.values():
    print(value)


I am working on the file "Section 1 - Core Python/Chapter 04 - Loops/Loops.ipynb".
The first task is:
we can also have conditions where multiple values are returned every iteration.
Can you write Python code for it?

# Advance code, to be used after learning slicing. Please use instead the other code
# for x in "Manish Gupta"[::-1]:
#     print(x, end=" ")

reverse_text = ""
for char in "Manish Gupta":
    reverse_text = char + reverse_text
print(reverse_text)

x_test = [[1,2],[3,4],[5,6]]

for x in x_test:
    print(x)
    a = x[0]
    b = x[1]
    print (a, b)

x_test = [[1,2],[3,4],[5,6], [7,8,9]]

for x in x_test:
    print(x)

x_test = [[1,2],[3,4],[5,6], [7,8]]

for x, y in x_test:
    print(x, y)

x_test = [[1,2],[3,4],[5,6], [7,8,9]]

for x in x_test:
    print(x)
    a = x[0]
    b = x[1]
    print (a, b)


I am working on the file "Section 1 - Core Python/Chapter 05 - Data Types Part - 2/5.1 Uses of collection and datatype.ipynb".
The first task is:
Convert A List To A Tuple
You can change a list to a tuple in Python by using the tuple() function. Pass your list to this function and you will get a tuple back!
NOTE: tuples are immutable thus can’t change them afterwards :(
Convert Your List To A Set In Python
a set is an unordered collection of unique items. That means not only means that any duplicates that you might have had in your original list will be lost once you convert it to a set, but also the order of the list elements.
You can change a list into a set with the set() function. Just pass your list to it!
Convert Lists To A Dictionaries
A dictionary works with keys and values, so the conversion from a list to a dictionary might be less straightforward.
helloWorld = ['hello','world','1','2']
You will need to make sure that hello and world and ‘1’ and ‘2’ are interpreted as key-value pairs. The way to do this is to select them with the slice notation and pass them to zip().
zip() actually works like expected: it zips elements together. In this case, when you zip the helloWorld elements helloWorld[0::2] and helloWorld[1::2]
Can you write Python code for it?

helloWorld = ['hello','world','1','2']
# print(list(zip(helloWorld)))

helloWorldDictionary = dict(zip(helloWorld[0::2], helloWorld[1::2]))

# Print out the result
print(helloWorldDictionary)


I am working on the file "Section 1 - Core Python/Chapter 05 - Data Types Part - 2/5.1 Uses of collection and datatype.ipynb".
The first task is:
Note that the second element that is passed to the zip() function makes use of the step value to make sure that only the world and 2 elements are selected. Likewise, the first element uses the step value to select hello and 1.
If your list is large, you will probably want to do something like this:
Can you write Python code for it?

a = [1, 2, 3, 4, 5]

# Create a list iterator object
i = iter(a)
for k in i:
    print(k)

# Zip and create a dictionary
print(dict(zip(i, i)))

## Difference Between The Python append() and extend() Methods?
# Append [4,5] to `shortList`
# This is your list
shortList  = [1, 2, 3]
longerList = [1, 2, 3]
# Check whether it's iterable
list.__iter__

shortList.append([4, 5])

# Use the `print()` method to show `shortList`
print(shortList)

# Extend `longerList` with [4,5]
longerList.extend([4, 5])

# Use the `print()` method to see `longerList`
print(longerList)


I am working on the file "Section 1 - Core Python/Chapter 05 - Data Types Part - 2/5.2 Advance Data Types.ipynb".
The first task is:
Adding
Can you write Python code for it?

import collections

# Add to the right
d1 = collections.deque()
d1.extend('Vande')
print('extend    :', d1)

for a in " Mataram":
    d1.append(a)

d1.extend(" !!!")
print('append    :', d1)
d1.extendleft(" #!* ")
print('append    :', d1)

# Add to the left
d2 = collections.deque()
d2.extendleft(range(6))
print('extendleft:', d2)
d2.appendleft(6)
print('appendleft:', d2)


I am working on the file "Section 1 - Core Python/Chapter 05 - Data Types Part - 2/5.2 Advance Data Types.ipynb".
The first task is:
Changing the values associated with existing keys and adding new elements works the same way.
It is also possible to set values through the ChainMap directly, although only the first mapping in the chain is actually modified.
Can you write Python code for it?

import collections

a = {'a': '1', 'c': '3'}
b = {'b': '2', 'c': '33'}

cm = collections.ChainMap(a, b)
print('Before: {}'.format(cm['c']))
cm['c'] = '3.3'
print('After : {}'.format(cm['c']))
print(a['c'])
print(b['c'])

import collections

a = {'a': '1', 'c': '3'}
b = {'b': '2', 'c': '33'}

cm = collections.ChainMap(b, a)
print('Before: {}'.format(cm['c']))
cm['c'] = '3.3'
print('After : {}'.format(cm['c']))
print(a['c'])
print(b['c'])

import collections

a = {'a': '1', 'c': '3'}
b = {'b': '2', 'c': '33'}

cm = collections.ChainMap(a, b)
print('Before: {}'.format(cm['c']))
cm['d'] = '3.3'
print('After : {}'.format(cm['c']))
print(cm.maps)
print(a)
print(b)


I am working on the file "Section 1 - Core Python/Chapter 05 - Data Types Part - 2/5.2 Advance Data Types.ipynb".
The first task is:
Consuming
OrderedDict
It is a dictionary subclass that remembers the order in which its contents are added.
Lets start with a normal dictionary:
Can you write Python code for it?

fruitsCount = {}
fruitsCount["apple"] = 10
fruitsCount["grapes"] = 120
fruitsCount["mango"] = 200
fruitsCount["kiwi"] = 2000
fruitsCount["leeche"] = 20
print(fruitsCount)
for fruit in fruitsCount:
    print(fruit)

# Now lets try this with OrderedDict

from collections import OrderedDict as OD

fruitsCount = OD()
fruitsCount["apple"] = 10
fruitsCount["grapes"] = 120
fruitsCount["mango"] = 200
fruitsCount["kiwi"] = 2000
fruitsCount["leeche"] = 20
print(fruitsCount)
for fruit in fruitsCount:
    print(fruit)


I am working on the file "Section 1 - Core Python/Chapter 05 - Data Types Part - 2/5.2 Advance Data Types.ipynb".
The first task is:
Counter methods
Can you write Python code for it?

# find the most common words

# Methods with Counter()
c = Counter(wordList)
print(c.most_common(4))
print(c.items())