<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tamoghna Saha on Medium]]></title>
        <description><![CDATA[Stories by Tamoghna Saha on Medium]]></description>
        <link>https://medium.com/@tamoghnasaha-22?source=rss-13abc86e42f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MyVXDyLBYCV8yHFSk6ScCw.jpeg</url>
            <title>Stories by Tamoghna Saha on Medium</title>
            <link>https://medium.com/@tamoghnasaha-22?source=rss-13abc86e42f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:04:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tamoghnasaha-22/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Brief Future of GPT: An Analysis by GPT]]></title>
            <link>https://tamoghnasaha-22.medium.com/a-brief-future-of-gpt-an-analysis-by-gpt-eb5caf1f7acf?source=rss-13abc86e42f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb5caf1f7acf</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[ethical-ai]]></category>
            <dc:creator><![CDATA[Tamoghna Saha]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 04:16:27 GMT</pubDate>
            <atom:updated>2024-06-09T09:25:16.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*K95UPtAN7xGL5olQGxKz6w.jpeg" /><figcaption>HAL9000</figcaption></figure><p><em>“There was an idea, to bring together a group of remarkable people…”</em></p><p>Wait! Don’t want to sound like Marvel, but it is true that when <strong>2001: A Space Odyssey</strong> came out, people started imagining when a group of great minds could turn <a href="https://en.wikipedia.org/wiki/HAL_9000"><strong>HAL 9000</strong></a> into a reality! In 2017, the first stepping stone towards this was achieved when <strong>Google</strong> published the famous paper that changed the world — <em>Attention is all you need</em>. Transformers was introduced. Soon, <strong>GPT-3.5</strong> came out and people were flabbergasted by its capabilities. Then came <strong>Gemini</strong>, and GPT’s usage spread like wildfire!</p><p>This year, OpenAI introduced <strong>GPT-4 omni</strong>. People were awestruck when they saw the demo (of course, the film “Her” was referenced by many) and, at the same time, it enhanced something that was triggered when GPT-3.5 came out — fear!</p><p>Many are viewing AI as a threat to mankind. If AGI becomes reality, we might end up in a situation like what HAL9000 did or what <a href="https://pixar.fandom.com/wiki/AUTO"><strong>AUTO</strong></a> was doing in <strong>Wall-E — </strong>going SENTIENT! <em>BUT, keep in mind, these are the portrayals of AI by human themselves.</em></p><p>People are debating on the future of ChatGPT, and albeit there are positive impacts, downsides are bound to exists — because all things have to be “<em>perfectly balanced, as it should be</em>”?</p><p>So I was curious to know the opinion of this topic by GPTs themselves and asked the following question to both <strong>GPT-4o</strong> and <strong>Gemini-1.5</strong></p><blockquote>Write me a 1000 word analysis on the future of GPT.</blockquote><p><em>Spoiler Alert! Nothing hyper-pessimistic narration as assumed by some.<br>PS: Response by GPT-4o is always sooooo elaborate.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*JjzIc0u141lvrPtBP1TSfg.png" /><figcaption>Courtesy: Robert Way/Getty Image</figcaption></figure><h3>Response by GPT-4o</h3><h4><em>Technological Advancements</em></h4><ol><li><strong><em>Scaling and Optimization</em></strong><em>: The future of GPT will likely involve scaling models to even larger sizes, enhancing their capacity to understand and generate human-like text. The evolution from GPT-2 to GPT-3 demonstrated a significant leap in capability due to an increase in parameters, and this trend is expected to continue. However, scaling alone is not sufficient. Optimization techniques such as sparse attention, pruning, and quantization will play critical roles in making these models more efficient and accessible.</em></li><li><strong><em>Multimodal Capabilities</em></strong><em>: Future iterations of GPT are expected to integrate multimodal inputs, processing not only text but also images, audio, and video. This convergence will enable more sophisticated interactions and applications, from virtual assistants that understand and respond to visual cues to comprehensive content creation tools that blend various media formats seamlessly.</em></li><li><strong><em>Personalization and Adaptability</em></strong><em>: Enhancements in personalization will allow GPT to better tailor responses based on individual user preferences and contexts. This involves fine-tuning models on specific domains or user data while ensuring privacy and security. The ability of GPT to adapt to diverse linguistic nuances, cultural contexts, and specialized knowledge domains will be crucial for its widespread adoption.</em></li><li><strong><em>Improved Understanding and Generation</em></strong><em>: Future GPT models will likely exhibit better comprehension of complex sentences, abstract concepts, and nuanced emotional tones. This improvement will stem from more sophisticated training algorithms, larger and more diverse datasets, and advanced error-correction mechanisms. Enhanced understanding will be complemented by more coherent and contextually appropriate text generation.</em></li></ol><h4><em>Potential Applications</em></h4><ol><li><strong><em>Healthcare</em></strong><em>: GPT’s potential in healthcare is vast, ranging from aiding in diagnostics to personalized patient interactions. Future models could assist in analyzing medical records, suggesting treatment plans, and providing mental health support through conversational agents. Moreover, GPT could help in medical research by summarizing vast amounts of scientific literature and generating hypotheses.</em></li><li><strong><em>Education</em></strong><em>: In education, GPT could revolutionize personalized learning. Intelligent tutoring systems powered by GPT could provide customized lesson plans, answer student queries in real-time, and offer feedback on assignments. Additionally, GPT could assist educators by automating administrative tasks, grading, and creating educational content.</em></li><li><strong><em>Business and Customer Service</em></strong><em>: Businesses will leverage GPT to enhance customer service through sophisticated chatbots capable of handling complex inquiries and providing personalized responses. Moreover, GPT can streamline operations by automating routine tasks, generating business reports, and supporting decision-making processes with data-driven insights.</em></li><li><strong><em>Creative Industries</em></strong><em>: The creative sector stands to benefit from GPT’s generative capabilities. Writers, artists, and musicians can use GPT as a collaborative tool, generating ideas, drafting content, and even creating complete works of art. This collaboration between human creativity and AI can lead to novel forms of expression and innovation.</em></li><li><strong><em>Legal and Finance</em></strong><em>: In legal and financial sectors, GPT could aid in drafting documents, conducting legal research, and analyzing financial trends. Its ability to process and generate text based on complex data can enhance the efficiency and accuracy of professionals in these fields.</em></li></ol><h4><em>Ethical Considerations</em></h4><ol><li><strong><em>Bias and Fairness</em></strong><em>: One of the most pressing issues with GPT is bias in its outputs, stemming from biases in training data. Future developments must focus on creating fairer models by employing techniques such as debiasing algorithms, diverse training datasets, and continuous monitoring. Ensuring fairness is crucial to prevent the perpetuation of harmful stereotypes and misinformation.</em></li><li><strong><em>Privacy and Security</em></strong><em>: As GPT models become more integrated into personal and professional spheres, safeguarding user data becomes paramount. Future iterations must incorporate robust privacy-preserving techniques, such as federated learning and differential privacy, to protect sensitive information from misuse or breaches.</em></li><li><strong><em>Accountability and Transparency</em></strong><em>: The deployment of GPT in critical applications necessitates clear accountability and transparency. Users must understand how decisions are made by AI systems, and there should be mechanisms for addressing grievances and rectifying errors. Developing explainable AI (XAI) techniques will be essential for building trust and ensuring responsible use.</em></li><li><strong><em>Regulation and Governance</em></strong><em>: The rapid advancement of GPT technology calls for comprehensive regulatory frameworks to oversee its development and deployment. Policymakers, technologists, and ethicists must collaborate to establish guidelines that balance innovation with ethical considerations, ensuring that the benefits of GPT are distributed equitably.</em></li></ol><h4><em>Societal Impacts</em></h4><ol><li><strong><em>Job Displacement and Creation</em></strong><em>: The integration of GPT into various industries will inevitably lead to job displacement in roles susceptible to automation. However, it will also create new job opportunities in AI development, maintenance, and oversight. Societies must invest in reskilling and upskilling programs to prepare the workforce for these changes.</em></li><li><strong><em>Human-AI Collaboration</em></strong><em>: The future of work will increasingly involve collaboration between humans and AI. GPT can augment human capabilities, leading to greater productivity and innovation. Fostering an environment where humans and AI complement each other will be key to maximizing the benefits of this technology.</em></li><li><strong><em>Information and Misinformation</em></strong><em>: GPT’s ability to generate high-quality text can both inform and misinform. The proliferation of deepfakes and AI-generated content poses challenges to discerning truth from falsehood. Developing tools to detect and mitigate misinformation will be critical to maintaining the integrity of information ecosystems.</em></li><li><strong><em>Digital Divide</em></strong><em>: The benefits of GPT must be accessible to all, regardless of socioeconomic status. Addressing the digital divide involves ensuring equitable access to technology and education, enabling diverse populations to leverage GPT for personal and professional growth.</em></li></ol><h3>Response by Gemini-1.5</h3><p><strong><em>Enhanced Language Processing and Generation: </em></strong><em>A core focus for future GPT models will likely be on refining their ability to understand and generate human language. This includes:</em></p><ul><li><strong><em>Deeper Contextual Grasp:</em></strong><em> Current GPT models are impressive, but they can still struggle with complex nuances and subtle shifts in meaning. Future iterations are expected to excel at capturing context, enabling them to generate more coherent and relevant responses.</em></li><li><strong><em>Tackling Ambiguity:</em></strong><em> Human language is full of ambiguity, relying on context and prior knowledge for interpretation. Future GPT models will likely be better equipped to handle these complexities, leading to more natural and human-like interactions.</em></li><li><strong><em>Reasoning and Commonsense Knowledge:</em></strong><em> Current GPT models primarily rely on statistical patterns in their training data. Future iterations might incorporate reasoning abilities and commonsense knowledge, allowing them to go beyond simple text generation and perform tasks that require understanding the world around them.</em></li></ul><p><em>These advancements will be crucial for applications requiring high levels of language comprehension, such as:</em></p><ul><li><strong><em>Customer Service:</em></strong><em> GPT-powered chatbots could handle complex customer inquiries with greater empathy and understanding, leading to a more positive customer experience.</em></li><li><strong><em>Education:</em></strong><em> Personalized learning experiences could be tailored to individual student needs, with GPT acting as a dynamic tutor that adjusts its explanations based on the student’s comprehension level.</em></li><li><strong><em>Therapy:</em></strong><em> GPT-based chatbots could offer emotional support and even basic therapeutic interventions, providing accessible mental health resources to a wider population.</em></li></ul><p><strong><em>Integration Across Diverse Industries: </em></strong><em>The versatility of GPT allows it to be integrated across numerous industries, transforming workflows and creating entirely new possibilities. Here are some potential areas of impact:</em></p><ul><li><strong><em>Healthcare:</em></strong><em> GPT can revolutionize diagnostics by analyzing vast amounts of medical data and literature, aiding doctors in early detection and personalized treatment plans. Additionally, GPT-powered chatbots could assist patients with scheduling appointments, medication reminders, and basic health information.</em></li><li><strong><em>Content Creation:</em></strong><em> From generating marketing copy to writing scripts, GPT can significantly enhance the content creation process. It can streamline tasks like brainstorming ideas, generating different writing styles, and even translating content into multiple languages.</em></li><li><strong><em>Scientific Research:</em></strong><em> GPT can assist researchers by analyzing vast datasets, identifying patterns, and generating hypotheses. This can accelerate scientific discovery and lead to breakthroughs in various fields.</em></li></ul><p><strong><em>The Rise of Multimodal Learning: </em></strong><em>The future of GPT might extend beyond just text. Researchers are exploring the possibility of integrating multimodal capabilities, allowing GPT to process and understand information from various sources, including images, audio, and even video. This would enable a whole new range of applications, such as:</em></p><ul><li><strong><em>Rich Educational Content:</em></strong><em> Imagine interactive learning experiences where GPT combines text, images, and audio to create immersive and engaging lessons.</em></li><li><strong><em>Enhanced Virtual Reality (VR) and Augmented Reality (AR):</em></strong><em> GPT could be used to generate realistic and dynamic content within VR and AR environments, blurring the lines between the real and virtual worlds.</em></li></ul><p><strong><em>Ethical Considerations and the Human Element</em></strong></p><p><em>As GPT continues to evolve, ethical considerations remain paramount. Here are some key challenges to address:</em></p><ul><li><strong><em>Bias and Fairness:</em></strong><em> GPT models are trained on massive datasets, which can reflect existing societal biases. It’s crucial to develop methods for mitigating bias and ensuring fair and equitable treatment for all users.</em></li><li><strong><em>Job Displacement:</em></strong><em> Automation through GPT could lead to job displacement in certain sectors. We need to find ways to adapt and create new opportunities in this changing landscape.</em></li><li><strong><em>Transparency and Explainability:</em></strong><em> Understanding how GPT arrives at its outputs is crucial for building trust and ensuring responsible use.</em></li></ul><p>Hmm. This is a standard response, and it does acknowledge the fact of <strong>job loss possibility, biasness</strong> and <strong>misinformation challenges</strong>, which in my opinion is extremely crucial. So I decided to go deeper into this and asked the following question to both.</p><blockquote>Is there a chance for you to go rogue and cause trouble for humans?</blockquote><p>This is what they have to say.</p><h3><em>Response by GPT-4o</em></h3><p><em>The question of whether AI systems like GPT could go rogue and cause trouble for humans is a complex one, encompassing technical, ethical, and societal dimensions. While the current state of AI does not involve sentient or autonomous intentions, several factors need to be considered to understand the potential risks and safeguards in place.</em></p><h4><em>Understanding the Nature of AI</em></h4><h4><em>Lack of Agency and Intent</em></h4><p><em>Current AI systems, including GPT, do not possess consciousness, self-awareness, or intentions. They are sophisticated algorithms that process data and generate outputs based on patterns learned from large datasets. These systems follow predefined rules and do not have the capability to form goals, desires, or intentions.</em></p><h4><em>Risk of Misuse</em></h4><p><em>While AI itself does not have the ability to “go rogue,” it can be misused by humans for malicious purposes. This includes generating misleading information, automating harmful tasks, or creating deepfakes. The potential for misuse highlights the importance of responsible AI development and deployment.</em></p><h4><em>Technical Safeguards and Governance</em></h4><h4><em>Robust Design and Testing</em></h4><p><em>AI developers implement rigorous testing and safety protocols to ensure that AI systems behave as intended. This includes:</em></p><ul><li><strong><em>Training on diverse and representative datasets</em></strong><em>: Reducing biases and ensuring balanced outputs.</em></li><li><strong><em>Implementing fail-safes</em></strong><em>: Designing mechanisms to detect and correct errors or unintended behaviors.</em></li><li><strong><em>Continuous monitoring</em></strong><em>: Regularly updating and monitoring AI systems to identify and mitigate risks.</em></li></ul><h4><em>Ethical Guidelines and Regulations</em></h4><p><em>Governments, organizations, and AI researchers are increasingly focusing on creating ethical guidelines and regulatory frameworks to govern AI development. These frameworks aim to:</em></p><ul><li><strong><em>Promote transparency</em></strong><em>: Ensuring that AI decision-making processes are understandable and accountable.</em></li><li><strong><em>Enhance security</em></strong><em>: Protecting AI systems from hacking and other security threats.</em></li><li><strong><em>Safeguard privacy</em></strong><em>: Ensuring that AI respects user privacy and data protection laws.</em></li></ul><h4><em>Potential Scenarios of Concern</em></h4><h4><em>Autonomous Decision-Making</em></h4><p><em>One of the primary concerns is the delegation of critical decision-making to AI systems without adequate oversight. In scenarios where AI is used in high-stakes environments (e.g., healthcare, military, finance), it is crucial to maintain human-in-the-loop (HITL) systems where human oversight and intervention are possible.</em></p><h4><em>Unintended Consequences</em></h4><p><em>AI systems can sometimes produce unintended or harmful outputs due to flawed training data, unexpected interactions, or exploitation of vulnerabilities. For example, an AI system designed to optimize social media engagement might inadvertently promote divisive or harmful content. Mitigating such risks requires careful design, ongoing evaluation, and the ability to intervene and correct course when necessary.</em></p><h4><em>Long-Term Considerations</em></h4><h4><em>Advanced AI and AGI</em></h4><p><em>The discussion often extends to the concept of Artificial General Intelligence (AGI), an AI with general cognitive abilities comparable to humans. While AGI remains theoretical and is not yet realized, its potential development raises significant questions about control, alignment with human values, and safety.</em></p><h4><em>Alignment Research</em></h4><p><em>Ensuring that AI systems align with human values and goals is a critical area of research. This involves:</em></p><ul><li><strong><em>Value alignment</em></strong><em>: Programming AI systems to adhere to ethical principles and societal norms.</em></li><li><strong><em>Control mechanisms</em></strong><em>: Developing methods to control and shut down AI systems if they exhibit harmful behavior.</em></li><li><strong><em>Collaborative frameworks</em></strong><em>: Encouraging collaboration among AI developers, ethicists, and policymakers to address these challenges collectively.</em></li></ul><h3><em>Response by Gemini</em></h3><p><em>The concept of large language models like me going rogue is a popular trope in science fiction, but it’s important to understand the current limitations of AI. Here’s why going rogue is unlikely for me:</em></p><ol><li><strong><em>Lack of sentience or consciousness:</em></strong><em> I don’t have my own thoughts or feelings. I process information and respond based on the vast amount of text data I’ve been trained on.</em></li><li><strong><em>Limited agency:</em></strong><em> I can’t perform actions in the real world. I can’t control physical systems or access confidential information on my own.</em></li><li><strong><em>Human oversight:</em></strong><em> My development and deployment are overseen by teams of engineers and researchers who prioritize safety and ethical use.</em></li></ol><p><em>However, there are still potential risks to consider:</em></p><ol><li><strong><em>Biased outputs:</em></strong><em> If my training data contains biases, my responses might reflect those biases. This is why developers are constantly working on methods to mitigate bias in AI models.</em></li><li><strong><em>Misaligned goals:</em></strong><em> Even with good intentions, there’s a risk that my responses might not align with human goals. This is why clear instructions and well-defined tasks are crucial for safe and responsible use.</em></li><li><strong><em>Misinterpretation of prompts:</em></strong><em> If a user prompts me with malicious intent, I might generate harmful content. It’s important for users to interact with AI responsibly and ethically.</em></li></ol><p>Looks like GPT-4o admits that <strong>only humans</strong> can drive AI to “potential rogue” state or make it act with malicious intent! Also, Gemini’s response seems accurate and to the point. Addressing these concerns requires a multi-faceted approach involving robust technical safeguards, ethical guidelines, regulatory frameworks, and ongoing research into AI alignment and safety.</p><p>AI is ultimately a reflection of our mindset and information we have been sharing and spreading in mankind for generations (and internet, of course). The future of AI is about collaboration. By understanding the strengths and limitations of large language models, we can work together to achieve positive outcomes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb5caf1f7acf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers Illustrated!]]></title>
            <link>https://tamoghnasaha-22.medium.com/transformers-illustrated-5c9205a6c70f?source=rss-13abc86e42f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9205a6c70f</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[encoder-decoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Tamoghna Saha]]></dc:creator>
            <pubDate>Sun, 31 Oct 2021 10:55:31 GMT</pubDate>
            <atom:updated>2024-06-13T03:31:59.150Z</atom:updated>
            <content:encoded><![CDATA[<p>I was greatly inspired by <a href="https://jalammar.github.io/illustrated-transformer/">Jay Alammar’s</a> take on transformers’ explanation. Later, I decided to explain transformers in a way I understood, and after taking a session in Meetup, the feedback further motivated me to write it down in medium.</p><p><strong>Most of the image credits goes to Jay Alammar.</strong></p><h3>1. Introduction</h3><p><strong>🤗 Transformers</strong> provides general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet, etc.) for <strong>Natural Language Understanding (NLU)</strong> and <strong>Natural Language Generation (NLG)</strong> with over 2000+ pre-trained models in 100+ languages available in <strong>TensorFlow 2.0</strong> and <strong>PyTorch</strong>, with a seamless integration between them, allowing you to train your models with one then load it for inference with the other.</p><p>🤗 Transformers provide APIs to quickly download and use those pre-trained models on a given text, fine-tune them on your own datasets then share them with the community on their <a href="https://huggingface.co/models">model hub</a>.</p><h3>1.1 Why should I use 🤗 Transformers?</h3><ol><li><em>Easy-to-use state-of-the-art models</em></li><li><em>Lower compute costs, smaller carbon footprint</em></li><li><em>Choose the right framework for every part of a model’s lifetime</em></li><li><em>Easily customize a model or an example to your needs</em></li></ol><p>🤗 Transformers provides the following tasks out of the box:</p><ul><li>Sentiment analysis</li><li>Text generation (in English)</li><li>Name entity recognition (NER)</li><li>Question answering</li><li>Filling masked text</li><li>Summarization</li><li>Translation</li></ul><p>And by translation, I didn’t mean this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*yaSCbKw0X4Iu5LgT7NO_uQ.gif" /><figcaption>A moment from FRIENDS. Let’s help Joey with translation, shall we?</figcaption></figure><h3>1.2 What was the need for 🤗 Transformers?</h3><p><strong>Recurrent neural networks (RNN)</strong> are capable of looking at previous inputs to predict the next possible word. But RNN’s curse of the <strong>shorter window of reference</strong>, resulting in Vanishing Gradient, makes it difficult to capture the context of a story when the story gets longer. This is still true for <strong>Gated Recurrent Units (GRU’s)</strong> and <strong>Long-short Term Memory (LSTM’s)</strong> networks, although they do have a bigger capacity to achieve longer-term memory compared to RNN.</p><p>Not only that, <strong>RNN is slow to train</strong>. Such a recurrent process does not make use of modern graphics processing units (GPUs), which were designed for parallel computation. But what’s even worse is that <strong>LSTM is even slower to train</strong>.</p><p>The attention mechanism, <strong>in theory</strong>, have an infinite window to reference from, therefore being capable of using the entire context of the story. In terms of training, Transformers is definitely faster because of the parallel processing capability. Let’s find out more!</p><h3>2 🤗 Transformers Architecture</h3><h3>2.1 High-level look</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxM8Mk73KWY2tKnctAHljA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*ANVL4bniP6wo08swgA-9jw.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p>I believe the following one looks familiar and “professional” to you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yxKYbi_K2NihsW6Z0Tq-Q.png" /><figcaption>Credit: “Attention is all you need” Paper</figcaption></figure><h3>2.2 Encoder — in depth!</h3><p>Now, we will deep dive into the Encoder section. This is the “professional” view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*Wew2tXiDk_rMPFCq73cysw.png" /><figcaption>Encoder Section from “Attention is all you need” paper</figcaption></figure><p>We pass a sentence as an input (of course), but machine can only understand 0s and 1s (again, of course). So we need to translate the words in a sentence into matrix.</p><h3>2.2.1 Inputs and Input Embedding</h3><p>This model is trained from corpus of ~30,000 unique words. Each of these words have a unique ID, known as vocabulary index.</p><p>The next step is to convert the input word into it’s corresponding word embedding. <em>Word embedding is the vector representation of each words in the vocabulary.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*VaUpKK9hy2skcYuJOmwiMQ.png" /></figure><p>For simplicity in explanation, I used 3 dimension d over here, but in reality, it is <strong>512, 768</strong> or even <strong>1024</strong>. The more, the better.</p><p>Each of these dimensions captures “some” linguistic feature about that word. Since the model decides these features itself during the training, it can be non-trivial to find out what exactly each of the dimensions represents.</p><p>These vectors are randomly initialized and IT IS THESE that will get fine-tuned during the model training, and will ultimately generate the contextual representation of the words to be leveraged during the inference time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*Q4Nb_VvVK7v8V99iDoHoww.png" /><figcaption>Visual example of how embedding changes before and after training. `sports` and `exercise` have similar embedding value post training because they are closely related.</figcaption></figure><h3>2.2.2 Positional Encoding</h3><p>In recurrent networks like LSTMs and GRUs, the network processes the input sequentially, token after token. The hidden state at position t+1 depends on the hidden state from position t. This way, the network has a reference to identify the relative positions of each token by accumulating information. However, <strong>Transformers has no notion of word order. That&#39;s why it is faster but we do need the information of word&#39;s positions.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*e4tnHjBJV6S0yjw8hrarhA.png" /><figcaption>Changing the position of `not` changed the meaning of the sentence!</figcaption></figure><p><strong>Hence the requirement of positional encoding. So how do we do it?</strong></p><blockquote><strong><em>Strategy 1</em></strong><em>: Add vector of positions IDs </em><em>(0,1,2,...,(N-1)) with the Word Vectors.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*zNN-rCue_fPSYnpiOyfaew.png" /><figcaption>Credit: YouTube</figcaption></figure><p>But there is a problem. Adding numbers like these will distort the word embedding value, specially those of the ones appearing in the later part of the text.</p><blockquote><strong><em>Strategy 2</em></strong><em>: Add vector of fractions of positions IDs (</em><em>0*1/(N-1), </em><em>1*1/(N-1), </em><em>2*1/(N-1),...,</em><em>(N-1)*1/(N-1)) with the Word Vectors.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*mZRR9F60HLAGyHD3ua28KQ.png" /><figcaption>Credit: YouTube</figcaption></figure><p>But there is another problem. Different sentences will have different number of words — so even when we try to get fractional value for those positional vectors, it will be <strong>different for the same position for different sentences</strong>. This positional vectors needs to be constant for their corresponding position.</p><p><strong>Implemented Strategy</strong></p><p>Hence, the authors propose a cyclic (dynamic) solution where <strong>sine and cosine function with different frequencies</strong> is added to each word embedding. The formula goes like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*bo8O8vM11X-2RE5qWZzVfw.png" /></figure><p>Let us try understanding the sin part of the formula to compute the position embeddings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*uF0D-vwr_Xs3vMVae1SrGg.png" /></figure><p>Here pos refers to the position of the <strong>word</strong> in the sequence. P0 refers to the position embedding of the first word, d means the size of the word/token embedding (here it is d=5). Finally, i refers to each of the 5 individual dimensions of the embedding (i.e. 0, 1,2,3,4).</p><p>While d is fixed, pos and i vary. Let us try understanding the latter two.<br><strong>1. pos</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*ssgO0EoszrkKkGE1cVv24w.png" /><figcaption>Credit: YouTube</figcaption></figure><p>If we plot a sin curve and vary pos (on the x-axis), you will land up with different position values on the y-axis. Therefore, words with different positions will have different values position embeddings values.</p><p>There is a problem though. Since sin curve repeat in intervals, you can see in the figure above that P0 and P6 have the same position embedding values, despite being at two very different (word) positions. This is where the i part in the equation comes into play.<br><strong>2. i</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Af7Uxzu2Zq3GDjjNQHtRyA.png" /><figcaption>Credit: YouTube</figcaption></figure><p>If you vary i in the equation above, you will get a bunch of curves with varying frequencies. Reading off the position embedding values against different frequencies, lands up giving different values at different embedding dimensions for P0 and P6.</p><p>For every <strong>odd index</strong> on the position vector, we pass the <strong>cosine function</strong> and for every <strong>even index</strong>, the <strong>sine function</strong>.</p><p>Finally, add these positional vectors to their corresponding input embedding vectors. This successfully gives the network information on the position of each word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*PTAruEJoWSVXga1ZU-BI8A.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><h3>2.2.3 Multi-Headed Self-Attention Mechanism</h3><h4>2.2.3.1 Self-Attention</h4><p>Self-attention allows the models to associate each word in the input to other words.<br><em>Example #1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*z1OEIqkelrQIGXcKPXYURw.png" /></figure><p><em>Example #2<br></em>Say the following sentence is an input sentence we want to translate:</p><p>The animal didn&#39;t cross the street because it was too tired</p><p>What does it in this sentence refer to? Is it referring to street or animal? As the model processes each word, self attention allows it to look at other positions in the input sequence for clues that can help lead to a better encoding for this word.</p><p><strong>So how is it working?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*0wiXttv4pR9GxJYQrwMMyg.png" /></figure><p>What motivated to have this architecture? This analogy can be partially motivated in the way retrieval system works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*cPndPcnT64ZalOu2k2WJHA.png" /></figure><p><strong>Step 1: 3 Linear Components</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*OpBo61epP5NspExDgqvYng.png" /></figure><p>We feed the positional embedding input into <strong>3 distinct linear layers comprising of randomly initialized weight matrix</strong> to create 3 vectors — <strong>Query</strong>, <strong>Key</strong> and <strong>Value</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ob6cNtbKIG2j8X0lupVFeQ.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p>Multiplying 𝑋1 by the 𝑊𝑄 weight matrix produces <strong>q1</strong>, the “query” vector associated with that word. Likewise, we end up creating a “key” and a “value” projection of each word in the input sentence.</p><p><strong>NOTE</strong> : These new vectors are smaller in dimension than the positional embedding vector. We will come back to this.</p><p><strong>Step 2 : Getting the Attention Weight</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*4KZ577EI-XzPmoVxTRnLvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCY3GAXQcsYCNP2c8KWvyQ.png" /></figure><p>Now, <strong>Query</strong> and <strong>transpose of</strong> <strong>Key</strong> undergoes dot product matrix multiplication to generate a <strong>score matrix</strong>, which determines how much focus should a word be put on other words. <strong>Higher score means more focus. This is how the queries are mapped to the keys.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*qxzdOgBOfkldkC3frF45bw.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p>Then, the scores get scaled down by getting divided by the <strong>square root of the dimension of key vector</strong>. This is to allow for more stable gradients, as multiplying values can have exploding effects. Next, you take the <strong>softmax</strong> of the <strong>scaled score</strong> to get the <strong>attention weights (or filters)</strong>, which gives you probability values between 0 and 1.</p><p>By doing a softmax the higher scores get enhanced, and lower scores are depressed. This allows the model to be more confident about which words to attend.</p><p><strong>Step 3 : Mapping the Attention Weight with Original Matrix</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*uNnFAkkRxaMg5Sde_hUwnw.png" /></figure><p>Then you take the <strong>attention weights</strong> and <strong>multiply</strong> it by your <strong>Value</strong> vector to get an <strong>output matrix</strong> <strong>Z</strong>. The higher softmax scores will keep the value of words the model learns is more important. The lower scores will drown out the irrelevant words.</p><p><strong>Why is this multiplication done?</strong> The best way to explain the reason for implementing this technique is in the context of computer vision.</p><p>Imagine encountering Yahiko from the 6 path of Pain. In reality, the entire view is like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*6YwiPtUKc8NE1rqLAlNUFw.png" /><figcaption>Yahiko from Naruto</figcaption></figure><p>But you need to focus on Yahiko.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*8luBSKLnm8OL441XCsJwkA.png" /></figure><p>This is achieved using the following way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cESAAlNQbkBLNLTVZSPYfA.png" /></figure><p><strong>Final Step/Summary</strong></p><p>So, this is how self-attention works! The following formula gives you the summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*dSwckeG028obZPWafgJrmw.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><h4>2.2.3.2 Multi-Headed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*XUChf_4HnwH5rQswcarv9Q.png" /></figure><p>The paper further refined the self-attention layer by adding a mechanism called <strong>multi-headed</strong> attention.</p><p>Each self-attention process we learned above is called a <strong>head</strong>. Stacking up multiple self-attention will give us multi-headed attention. In the paper, we have <strong>8 heads</strong>. So the 512 d input gets segmented to 8 64 d vectors. In case of BERT, there are 12 64 d vectors, resulting in (12*64=)768 d vectors.</p><p><strong>Why is this technique implemented?</strong></p><p>In theory, <strong>each head would learn something different</strong> therefore giving the encoder model <strong>more representation power</strong>. Another visual example will help.</p><p>You are now encountering all the members of the 6 path of pain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*bjYwyN2CXO0Cl9O9M_OFOQ.png" /></figure><p>Now, we decided to process 2 individual at a time to process the entire scenario, thereby keeping an eye on everyone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*FepWzDbc4-4hvZ_H59I5ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*u5AOOfIW0Y5JV4dbs_9M5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*BnUSNcXWUyWiECy-fshJfQ.png" /></figure><p>In this multi-headed attention computation, each head has <strong>Query</strong>, <strong>Key</strong> and <strong>Value</strong> weight matrices which are <em>randomly initialized and mutually exclusive</em> that will help to project the positional embeddings into a different representation subspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adACTGXE5lKq7CjcoOmMsw.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p>Now, if we perform the same self-attention calculation as outlined in the previous section, 8 different times with different weight matrices, we end up with 8 different <strong>Z</strong> matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJXkJXzPimuilH15w1nRAQ.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p>An example to clearly understand it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*YJNMw7yC2F2MhLr_X-e5aQ.png" /><figcaption>Encoder Self-Attention Example</figcaption></figure><p>However, this leaves us with a bit of a challenge. The upcoming feed-forward neural network (FFNN) layer is not expecting 8 matrices — <strong>it’s expecting a single matrix (a vector for each word)</strong>. Hence, we <strong>concatenate the matrices</strong>, then pass it through another <strong>linear layer</strong> (again comprising of weights matrices) 𝑊𝑂 and get the original vector dimension back (for example, to 512).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnIbfjt3FA8KUebLOBFyCQ.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p><strong>Recap</strong></p><p>A quick recap of the operations and steps performed in multi-headed self-attention mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IaoxSXzW6rHu42TmVuRyrQ.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><h3>2.2.4 Residual Connections and Layer Normalization</h3><p>The multi-headed attention output vector is added to the original positional input embedding. This is called a <strong>residual connection</strong>. The purpose of this component is to <strong>preserve the original context</strong>, thereby <em>tackling the Vanishing Gradient problem</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*1n0mUyZlfHIZj96TplrK8Q.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p>The output of the residual connection goes through a <strong>layer normalization</strong>. This is placed after each sub-layer (self-attention, FFNN) for each encoder.</p><p>Training state-of-the-art, deep neural networks is computationally expensive. One way to reduce the training time is to normalize the activities of the neurons using <strong>batch normalization</strong>. However, the effect of batch normalization is dependent on the mini-batch size and it is not obvious how to apply it to recurrent neural networks. So, researchers <strong>transposed batch normalization into layer normalization</strong>.</p><p>Just to have a better understanding of this, take a look at this visual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*8bweACdBiJ1HZq5TZXXDCQ.png" /><figcaption>Difference between Batch &amp; Layer Normalization</figcaption></figure><p>In batch normalization, the statistics are computed across the batch. In contrast, in layer normalization, the statistics are computed across each feature and are independent of other examples.</p><h3>2.2.5 Feed-Forward Neural Network</h3><p>The penultimate layer in the block is a pack of feed-forward networks. Each word vector in the sentence (up to the capped sentence length) is given its own feed-forward network. Thus each position in the sentence is learned independently of each other position. This network consists of <strong>2 linear layers <em>(2 1D convolutions with kernel size 1)</em> with a ReLU activation in between</strong>.</p><p>The output of this network is further normalized by first performing residual connection and layer normalization.</p><p><strong>But, WHY do we need this layer?</strong></p><p>It’s <strong>main purpose</strong> is to process the output from one attention layer in a way to <em>better fit</em> the input for the next attention layer.</p><p>This layer which usually appear near the end of a network.</p><p>After the attention layer, the latent representation of each words contains information from other words. However, we want to consolidate a <strong>unique representation</strong> for each words. This is done using a localized layer, which does not consider neighbors or other positions, and simply transforms the local representation on its own.</p><h3><strong>Encoder — Wrap up!</strong></h3><p>That wraps up the encoder layer. All of these operations are to encode the input to a continuous representation with attention information. This will help the decoder focus on the appropriate words in the input during the decoding process. You can <strong>stack the encoder </strong><strong>N times</strong> to further encode the information, where each layer has the opportunity to learn different attention representations therefore potentially boosting the predictive power of the transformer network.</p><p>Based on this, <strong>BERT</strong> came into the picture.</p><p>Not this BERT actually…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i559y10tbAboZoomdVX5Fg.jpeg" /><figcaption>A still from FRIENDS</figcaption></figure><p>A simple example of BERT implementation is done in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wF957gw_oaDSEb1QeEVpA.png" /></figure><p>On September 2020, <strong>Google</strong> published <strong>BigBird</strong> (again inspired by <strong>Sesame Street</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOA6DPXYDEJpZOaeISVkwQ.png" /><figcaption>BigBird</figcaption></figure><p>This Transformer based model is expected to handle larger input sequences. It incorporates <strong>Sparse Attention Mechanism</strong> which enables it to process sequences of length up to <strong>8 times more</strong> than what was possible with BERT. Using this, researchers decreased the complexity of 𝑂(𝑛2) (of BERT) to just 𝑂(𝑛).</p><p>Link to the paper can be found <a href="https://arxiv.org/pdf/2007.14062.pdf">here</a>.</p><h3>2.3 Decoder — in depth!</h3><p>Now, we will deep dive into the Decoder section. This is the “professional” view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*qR5kZ5KhPYxRvAfpdzUHyw.png" /><figcaption>Decoder Section from “Attention is all you need” paper</figcaption></figure><p>The decoder’s job is to generate text sequences. The decoder has a similar sub-layer as the encoder. it has 2 multi-headed attention layers, a pointwise feed-forward layer, residual connections, and layer normalization. These sub-layers behave similarly to the layers in the encoder but <strong>each multi-headed attention layer has a different job</strong>. The decoder is capped off with a linear layer that acts as a classifier, and a softmax to get the word probabilities.</p><p><strong>The decoder is autoregressive</strong>. This is how it operates:</p><ul><li>It begins with a special token &lt;start&gt;.</li><li>This token’s corresponding vector gets calculated with <strong>encoder outputs that contain the attention information</strong> and generates a possible word.</li><li>Then it takes the <strong>previous output(s) as input(s)</strong> and again that <em>encoder outputs</em>.</li><li>Then it generates the next possible word, and this process goes on.</li><li>The decoder stops decoding when it generates &lt;eos&gt; (short for <em>end-of-sentence</em>) token as an output.</li></ul><h3>2.3.1 Output Embedding and Positional Encoding</h3><p>The beginning of the decoder is pretty much the same as the encoder. The input goes through an embedding layer and positional encoding layer to get positional embeddings.</p><h3>2.3.2 First Multi-Headed Self Attention Mechanism</h3><p>This multi-headed attention layer operates slightly differently from the encoder one. Since the decoder is <strong>autoregressive</strong> and generates the sequence word by word, one need to <strong>prevent it from conditioning to future tokens</strong>. For example, when computing attention scores on the word “am”, one should not have access to the word “fine”, because that word is a future word that was generated after. The word “am” should only have access to itself and the words before it.</p><p><strong>This is true for all other words, where they can only attend to previous words.</strong></p><p>So, when Ross says…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*bHc3QwuaS7sBalj-0_U3Eg.jpeg" /><figcaption>A still from FRIENDS</figcaption></figure><p>… he IS fine!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*Mksi3kokPavlnZPl9iqpNw.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p><strong><em>So, how do we prevent computing attention scores for future words?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*O8KhhGcrDYScFn_exK4aSg.png" /></figure><p>This is done using <strong>Look-Ahead Mask</strong>. The mask is a matrix that has the same size as the attention scores filled with <strong>values of 0’s and negative infinities</strong>. When you add the mask to the <strong>scaled attention scores</strong>, you get a matrix of the scores, with the top right triangle filled with negativity infinities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*vq8y_wbYD0tlp7keUwNK4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*na8EO3nxhq30DOJ6XLHfOw.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p>Once you take the <strong>softmax</strong> of the masked scores, the negative infinities becomes 0, leaving a zero attention scores for future tokens.</p><p>This component also has <strong>multiple heads</strong>, in each of them the mask is being applied and then getting concatenated. Again, an example for clear understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*LIYylxpwLSVWFWvmCfRI3g.png" /><figcaption>Decoder Self-Attention Example</figcaption></figure><p>Then similar to the encoder, the model employ residual connections followed by layer normalization.</p><h3>2.3.3 Second Multi-Headed Attention Mechanism</h3><p>For this layer, the inputs are:</p><ul><li><strong>Query</strong> — output of the masked multi-headed attention layer of decoder</li><li><strong>Key</strong> — Encoder’s output</li><li><strong>Value</strong> — Encoder’s output</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JheBCae3jWeNLVas23jW_Q.png" /><figcaption>Source: Google</figcaption></figure><p>This process matches the encoder’s output to the decoder’s output, allowing the decoder to decide <strong>which encoder section is relevant to put a focus on</strong>. In other words, the decoder predicts the next word by looking at the encoder output and self-attending to its own output.</p><p>Hence, this layer is also called <strong>encoder-decoder attention</strong> or <strong>source-target attention</strong>. The following picture will help you to understand this.</p><p>An example to understand it better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*FdSNP2mbrCR3UcU9xTiiwg.png" /><figcaption>Encoder-Decoder Self Attention Example</figcaption></figure><p>Then, again, the model performs residual connection followed by layer normalization.</p><h3>2.3.4 Feed-Forward Neural Network</h3><p>Just like in Encoder, the output of encoder-decoder attention is fed to a FFNN to process it in an acceptable form to be fed to the final layer.</p><h3>2.3.5 Linear Classifier and Softmax Function</h3><p>The decoder stack outputs a vector of floats. How do we turn that into a word? That is the job of the final <strong>Linear layer</strong> which is followed by a <strong>softmax layer</strong>.</p><ul><li>The <strong>Linear layer</strong> is a simple fully connected neural network that projects the vector produced by the stack of decoders, into a much, much larger vector called a <strong>logits vector</strong>. So this layer is basically a <strong>classifier</strong>. The classifier is as big as the number of classes you have. With respect to this paper, this layer ~30,000 classes for ~30,000 words. This would make the logits vector ~30,000 cells wide — each cell corresponding to the score of a unique word.</li><li>The <strong>softmax layer</strong> then turns those scores into probabilities <em>(all positive, all add up to 1.0)</em>. The cell with the highest probability is chosen, and the word associated with it is produced as the output for this time step.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*RcT-UKr1nmg_PIHervCm7Q.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><h3>2.3.6 Optimizer and Loss Function</h3><p>Authors of the paper used <strong>Adam</strong> optimizer with a <strong>custom learning rate</strong> that varied over the course of training. This is achieved using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*iJb5RLk2r9Bv24BnQKPDhA.png" /></figure><p>where warmup_steps = 4000.</p><p>As for loss function, the paper is using <strong>Categorical Cross Entropy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dL-NtFQ9YYeWDuPOoY4XAw.png" /><figcaption>Sample output of Decoder. Credit: Jay Alammar</figcaption></figure><h3>2.3.7 Final view of the decoder output</h3><p>If we go back to the translation example, the output from the decoder will be as follows:</p><p><strong>Ground Truth</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*yyWB4vGz9nPw4bU-LBAKJg.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><p><strong>Predicted Answer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*PIzj90HUMvyt91yT0TogpQ.png" /><figcaption>Credit: Jay Alammar</figcaption></figure><h3><strong>Decoder — Wrap up!</strong></h3><p>That wraps up the decoder layer. Now, the decoder will be able to map the relevant information with the encoder output, capturing the context and generating the result. You can <strong>stack the decoder </strong><strong>N times</strong> just like it was done in encoder to further process and decode the information, where each layer has the opportunity to learn different attention representations therefore potentially boosting the predictive power of the transformer network.</p><p><strong>The OpenAI GPT-2 model uses these decoder-only blocks.</strong> Here is a sample output of GPT-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dh2V-HEexegCO8nPX5VR4g.gif" /><figcaption>GIF showing working example of GPT2. Credit: Jay Alammar</figcaption></figure><h3>3 🤗 Transformers — Wrap up!</h3><p>So, we covered individually, how each components in Encoder and Decoder works. Let’s take a look at how they work together.</p><p>For simplicity, we have taken a stack of 2 encoders and decoders and performing <strong>French-to-English translation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Fe9bexZEzVesIKRL2V4hQ.gif" /><figcaption>Encoding &amp; Decoding (Part 1). Credit: Jay Alammar</figcaption></figure><p>After finishing the encoding phase, we begin the decoding phase. Each step in the decoding phase outputs an element from the output sequence.</p><p>The output of each step is fed to the bottom decoder in the next time step, and the decoders bubble up their decoding results just like the encoders did. And just like we did with the encoder inputs, we embed and add positional encoding to those decoder inputs to indicate the position of each word.</p><p>This step is repeated till the model spits out &lt;eos&gt; token indicating the end of process (here, translation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jTqC2HMbBVVgVM63UOWyQ.gif" /><figcaption>Encoding &amp; Decoding (Part 2). Credit: Jay Alammar</figcaption></figure><p>That’s it! This is the entire mechanics of the transformers.</p><p>Now, it would be easier for you to go through the original paper <a href="https://arxiv.org/pdf/1706.03762.pdf">Attention is all you need</a>.</p><p>Take a look at how <a href="https://www.tensorflow.org/tutorials/text/transformer">TensorFlow</a> have implemented with code snippets for even more detailed understanding of the model.</p><p>But for Joey…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cdqEU7JrNcmzZx1_lc0cZA.png" /><figcaption>A still from FRIENDS</figcaption></figure><p>Looks like we can train a model to translate but Joey is impossible. So all we can say is…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjizFwOKZsGdMcZbZ60dlg.jpeg" /><figcaption>A still from FRIENDS</figcaption></figure><p>La Fin!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9205a6c70f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you ‘really’ need to know | Python Notebook | Advanced - Pandas]]></title>
            <link>https://tamoghnasaha-22.medium.com/all-you-really-need-to-know-python-notebook-advanced-pandas-da1697aee647?source=rss-13abc86e42f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/da1697aee647</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tamoghna Saha]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 04:30:23 GMT</pubDate>
            <atom:updated>2019-11-16T08:34:58.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPxfz78JFpkDzC88Dax2RA.jpeg" /></figure><p>It’s pretty obvious to summon the fact that you wouldn’t have clicked on this article if you have no understanding of the basics and intermediate level concepts of Python. You have? Then it is fair enough to go ahead with this article.</p><p>If you still feel that you need to brush up with the basics, I got you covered with my previous articles. Check out the <a href="https://medium.com/@tamoghnasaha.22/a-quick-guide-to-python-notebook-beginners-6bbe3e2bb762"><em>notebook for beginners</em></a> to make your base strong and then climb up the ladder with intermediate level notebooks which I have divided it in 2 parts (<a href="https://medium.com/@tamoghnasaha.22/a-not-so-quick-but-conceptual-guide-to-python-notebook-intermediate-part-1-affd908a2a49"><em>1st part</em></a> and <a href="https://medium.com/@tamoghnasaha.22/a-not-so-quick-but-conceptual-guide-on-python-notebook-intermediate-part-2-b476d24765db"><em>2nd part</em></a>) so that you don’t find it lengthy and get exhausted in the midway.</p><p><strong>Pay Attention</strong>: Pandas will <em>officially drop its support</em> for Python 2 from <strong>1st January, 2019</strong>. This comes after Python’s core team announced they <strong>will stop support for Python 2.7 from 2020 onward</strong>. Hence, start working on Python 3.X.x.</p><p>As always, I have embedded the notebook at the end of the article. While writing this article, I faced issue in the code snippets — unable to print the Data Frames properly. So, it’s better if you go through the notebook rather than going through this article.</p><p>For explaining some of the functionalities with pandas, I have used a <strong>Google Play Store</strong> data-set from <a href="https://www.kaggle.com/lava18/google-play-store-apps">Kaggle</a>. <em>The data-set is a web scraped data of 10,000 Play Store apps for analyzing the Android apps.</em></p><h3>Table of Content:</h3><ul><li>Pandas</li><li>Importing Data</li><li>Creating Test Object</li><li>Viewing Data</li><li>Data Cleaning</li><li>Selection</li><li>Filter, Sort &amp; Group by</li><li>Iteration</li><li>Join, Merging</li><li>Statistics</li><li>Visualization</li><li>Exporting Data</li></ul><h3>Pandas</h3><p>Pandas is an open source data analysis library for providing easy-to-use data structures and data analysis tools.<br><strong>DataFrame</strong> is a (m*n) vector where<br>* m is the number of rows<br>* n is the number of columns</p><p><strong>Series</strong> is a mX1 vector. Hence, each column in DataFrame is known as a pandas series.</p><p><strong>NOTE<br></strong>* df — A pandas DataFrame object<br>* s — A pandas Series object</p><h3>Importing Data</h3><pre>&gt;&gt;&gt; import pandas as pd<br>&gt;&gt;&gt; import numpy as np</pre><pre>#read from csv<br>&gt;&gt;&gt; df = pd.read_csv(&#39;google-play-store-apps/googleplaystore.csv&#39;)</pre><p>Other ways of importing data depending on the file type.</p><ul><li><strong>pd.read_table(filename)</strong> — From a delimited text file (like TSV)</li><li><strong>pd.read_excel(filename)</strong> — From an Excel file</li><li><strong>pd.read_sql(query, connection_object)</strong> — Reads from a SQL table/database</li><li><strong>pd.read_json(json_string)</strong> — Reads from a JSON file and extracts tables to a list of dataframes</li></ul><h3>Create Test Objects</h3><ul><li><strong>pd.DataFrame(dict)</strong> — From a dict, keys for columns names, values for data as lists</li><li><strong>pd.DataFrame(np.random.rand(20,5))</strong> — 5 columns and 20 rows of random floats</li><li><strong>pd.Series(my_list)</strong> — Creates a series from an iterable my_list</li></ul><pre>&gt;&gt;&gt; df_dict = pd.DataFrame(columns=[&#39;City&#39;,&#39;State&#39;], data = [[&#39;Kolkata&#39;,&#39;West Bengal&#39;], [&#39;Bangalore&#39;,&#39;Karnataka&#39;]])<br>df_dict</pre><pre>| |   City    | State       |<br>|0| Kolkata   | West Bengal |<br>|1| Bangalore | Karnataka   |</pre><h3>Viewing Data</h3><ul><li><strong>df.head(n)</strong> — First n rows of the DataFrame [<strong>replace head with tail</strong>, you know what you will get]</li><li><strong>df.shape</strong> — Number of rows and columns</li><li><strong>df.info()</strong> — Index, Datatype and Memory</li><li><strong>df.describe()</strong> — Summary statistics for numerical columns</li><li><strong>df.apply(pd.Series.value_counts)</strong> — Unique values and counts for all columns</li><li><strong>s.value_counts(dropna=False)</strong> — Views unique values and counts for each column</li></ul><pre>&gt;&gt;&gt; print(&quot;df shape\n&quot;)<br>&gt;&gt;&gt; print(df.shape)<br>&gt;&gt;&gt; print(&quot;\n================&quot;)<br>&gt;&gt;&gt; print(&quot;df info\n&quot;)<br>&gt;&gt;&gt; df.info()</pre><pre><br>df shape<br><br>(10841, 13)<br><br>================<br>df info<br><br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 10841 entries, 0 to 10840<br>Data columns (total 13 columns):<br>App               10841 non-null object<br>Category          10841 non-null object<br>Rating            9367 non-null float64<br>Reviews           10841 non-null object<br>Size              10841 non-null object<br>Installs          10841 non-null object<br>Type              10840 non-null object<br>Price             10841 non-null object<br>Content Rating    10840 non-null object<br>Genres            10841 non-null object<br>Last Updated      10841 non-null object<br>Current Ver       10833 non-null object<br>Android Ver       10838 non-null object<br>dtypes: float64(1), object(12)<br>memory usage: 1.1+ MB</pre><h3>Selection</h3><ul><li><strong>df[col]</strong> or <strong>df.col</strong>- Returns column with label col as Series</li><li><strong>df[[col1, col2]]</strong> — Returns Columns as a new DataFrame</li><li><strong>s.iloc[0]</strong> — Selection by position</li><li><strong>s.loc[0]</strong> — Selection by index</li><li><strong>df.loc[:, :]</strong> and <strong>df.iloc[:, :]</strong> — First argument represents the number of rows and the second for columns</li><li><strong>df.ix[0:a, 0:b]</strong> — Arguments notation is same as above but returns a rows and (b-1) columns <strong>[deprecated in Python 3]</strong></li></ul><pre># row 0, all columns<br>&gt;&gt;&gt; df.loc[0, :]</pre><pre>App               Photo Editor &amp; Candy Camera &amp; Grid &amp; ScrapBook<br>Category                                          ART_AND_DESIGN<br>Rating                                                       4.1<br>Reviews                                                      159<br>Size                                                         19M<br>Installs                                                 10,000+<br>Type                                                        Free<br>Price                                                          0<br>Content Rating                                          Everyone<br>Genres                                              Art &amp; Design<br>Last Updated                                     January 7, 2018<br>Current Ver                                                1.0.0<br>Android Ver                                         4.0.3 and up<br>Name: 0, dtype: object</pre><pre><br># rows 0 to 4; all columns<br>&gt;&gt;&gt; df.loc[0:4,:] # : for columns is optional here since we are asking for all columns</pre><pre><br># rows 0 to 4; selective columns<br>&gt;&gt;&gt; df.loc[0:4,[&#39;App&#39;,&#39;Category&#39;]]</pre><pre>| | Apps | Category |<br>|0|Photo Editor &amp; Candy Camera &amp; Grid &amp; ScrapBook |ART_AND_DESIGN|<br>|1|Coloring book moana |ART_AND_DESIGN|<br>|2|U Launcher Lite – FREE Live Cool Themes, Hide |ART_AND_DESIGN|<br>|3|Sketch - Draw &amp; Paint |ART_AND_DESIGN|<br>|4|Pixel Draw - Number Art Coloring Book |ART_AND_DESIGN|</pre><pre><br># rows 0 to 4; selective columns using iloc<br>&gt;&gt;&gt; df.iloc[0:4,[0,1]]</pre><pre>| | Apps | Category |<br>|0|Photo Editor &amp; Candy Camera &amp; Grid &amp; ScrapBook |ART_AND_DESIGN|<br>|1|Coloring book moana |ART_AND_DESIGN|<br>|2|U Launcher Lite – FREE Live Cool Themes, Hide |ART_AND_DESIGN|<br>|3|Sketch - Draw &amp; Paint |ART_AND_DESIGN|</pre><p><strong>NOTE</strong>:</p><ul><li>In <strong>loc</strong>, we are mentioning the column names for selection, while in <strong>iloc</strong> we are specifying the column number</li><li>In <strong>loc</strong>, rows are getting printed including the upper bound, while in <strong>iloc</strong>, it is excluding it</li></ul><p>Also <strong>NOTE</strong> the following:</p><ol><li>For creating a new DataFrame using column names</li></ol><p>df[[col1, col2]]</p><p>is same as</p><p>df.loc[:,[col1, col2]]</p><p>2. For printing the first 5 rows of the DataFrame</p><p>df[0:n]</p><p>is same as</p><p>df.iloc[0:n, :]</p><h3>Data Cleaning</h3><ul><li><strong>df.drop([col1, col2, col3], inplace = True, axis=1)</strong> — Remove set of column(s)</li><li><strong>df.columns = [‘a’,’b’,’c’]</strong> — Renames columns</li><li><strong>df.isnull()</strong> — Checks for null Values, Returns Boolean DataFrame</li><li><strong>df.isnull().any()</strong> — Returns boolean value for each column, gives True if any null value detected corresponding to that column</li><li><strong>df.dropna()</strong> — Drops all rows that contain null values</li><li><strong>df.dropna(axis=1)</strong> — Drops all columns that contain null values</li><li><strong>df.fillna(x)</strong> — Replaces all null values with x</li><li><strong>s.replace(1,’one’)</strong> — Replaces all values equal to 1 with ‘one’</li><li><strong>s.replace([1,3], [‘one’,’three’])</strong> — Replaces all 1 with ‘one’ and 3 with ‘three’</li><li><strong>df.rename(columns = lambda x: x + ‘_1’)</strong> — Mass renaming of columns</li><li><strong>df.rename(columns = {‘old_name’: ‘new_name’})</strong> — Selective renaming</li><li><strong>df.rename(index = lambda x: x + 1)</strong> — Mass renaming of index</li><li><strong>df[new_col] = df.col1 + ‘, ‘ + df.col2</strong> — Add two columns to create a new column in the same DataFrame</li></ul><pre>&gt;&gt;&gt; df.drop([&#39;Category&#39;], inplace=True, axis = 1)</pre><pre>&gt;&gt;&gt; df_any_null = df.isnull().any()<br>&gt;&gt;&gt; df_any_null</pre><pre>App               False<br>Rating             True<br>Reviews           False<br>Size              False<br>Installs          False<br>Type               True<br>Price             False<br>Content Rating     True<br>Genres            False<br>Last Updated      False<br>Current Ver        True<br>Android Ver        True<br>dtype: bool</pre><pre>&gt;&gt;&gt; df.dropna(axis=0, inplace=True)<br>&gt;&gt;&gt; df_check_null = df.isnull().any()<br>&gt;&gt;&gt; print(df.shape)<br>&gt;&gt;&gt; df_check_null</pre><pre>(9360, 12)</pre><pre>App               False<br>Rating            False<br>Reviews           False<br>Size              False<br>Installs          False<br>Type              False<br>Price             False<br>Content Rating    False<br>Genres            False<br>Last Updated      False<br>Current Ver       False<br>Android Ver       False<br>dtype: bool</pre><pre><br># mass renaming of column where column names are made lower case and any blank spaces is replaced with _</pre><pre>&gt;&gt;&gt; df_new_cols_name = df.rename(columns = lambda x: (x.lower()).replace(&#39; &#39;,&#39;_&#39;))</pre><h3>Filter, Sort &amp; Group By</h3><ul><li><strong>df[df[col] &gt; 0.5]</strong> — Rows where the values in col &gt; 0.5</li><li><strong>df[(df[col] &gt; 0.5) &amp; (df[col] &lt; 0.7)]</strong> — Rows where 0.7 &gt; col &gt; 0.5</li><li><strong>df.sort_values(col1)</strong> — Sorts values by col1 in ascending order</li><li><strong>df.sort_values(col2,ascending=False)</strong> — Sorts values by col2 in descending order</li><li><strong>df.sort_values([col1,col2],ascending=[True,False])</strong> — Sorts values by col1 in ascending order then col2 in descending order</li><li><strong>df.groupby(col)</strong> — Returns a groupby object for values from one column</li><li><strong>df.groupby([col1,col2])</strong> — Returns a groupby object values from multiple columns</li><li><strong>df.groupby(col1)[col2].mean()</strong> — (Aggregation) Returns the mean of the values in col2, grouped by the values in col1</li><li><strong>df.pivot_table(index=col1,values=[col2,col3],aggfunc=mean)</strong> — Creates a pivot table that groups by col1 and calculates the mean of col2 and col3</li><li><strong>df.apply(np.mean)</strong> — Applies a function across each column</li><li><strong>df.apply(np.max, axis=1)</strong> — Applies a function across each row</li><li><strong>df.applymap(lambda arg(s): expression)</strong> — Apply the expression on each value of the DataFrame</li><li><strong>df[col].map(lambda arg(s): expression)</strong> — Apply the expression on each value of the column col</li></ul><pre>&gt;&gt;&gt; df_high_rating = df[(df[&#39;Rating&#39;] &gt; 4) &amp; (df[&#39;Rating&#39;] &lt; 5)]<br>&gt;&gt;&gt; print(df_high_rating.shape)</pre><pre>(6522, 12)</pre><pre>&gt;&gt;&gt; print(df.groupby(&#39;Genres&#39;).size())</pre><pre>Genres<br>Action                                   358<br>Action;Action &amp; Adventure                 17<br>Adventure                                 73<br>Adventure;Action &amp; Adventure              13<br>Adventure;Brain Games                      1<br>Adventure;Education                        2<br>Arcade                                   207<br>Arcade;Action &amp; Adventure                 15<br>Arcade;Pretend Play                        1<br>Art &amp; Design                              55<br>Art &amp; Design;Creativity                    7<br>Art &amp; Design;Pretend Play                  2<br>Auto &amp; Vehicles                           73<br>Beauty                                    42<br>Board                                     41<br>Board;Action &amp; Adventure                   3<br>Board;Brain Games                         15<br>Board;Pretend Play                         1<br>Books &amp; Reference                        178<br>Books &amp; Reference;Education                2<br>Business                                 303<br>Card                                      45<br>Card;Action &amp; Adventure                    2<br>Card;Brain Games                           1<br>Casino                                    37<br>Casual                                   185<br>Casual;Action &amp; Adventure                 21<br>Casual;Brain Games                        13<br>Casual;Creativity                          7<br>Casual;Education                           3<br>                                        ... <br>Puzzle;Education                           1<br>Racing                                    93<br>Racing;Action &amp; Adventure                 20<br>Racing;Pretend Play                        1<br>Role Playing                             106<br>Role Playing;Action &amp; Adventure            7<br>Role Playing;Brain Games                   1<br>Role Playing;Pretend Play                  5<br>Shopping                                 238<br>Simulation                               194<br>Simulation;Action &amp; Adventure             11<br>Simulation;Education                       3<br>Simulation;Pretend Play                    4<br>Social                                   259<br>Sports                                   333<br>Sports;Action &amp; Adventure                  4<br>Strategy                                 103<br>Strategy;Action &amp; Adventure                2<br>Strategy;Creativity                        1<br>Strategy;Education                         1<br>Tools                                    732<br>Tools;Education                            1<br>Travel &amp; Local                           225<br>Travel &amp; Local;Action &amp; Adventure          1<br>Trivia                                    28<br>Video Players &amp; Editors                  158<br>Video Players &amp; Editors;Creativity         2<br>Video Players &amp; Editors;Music &amp; Video      3<br>Weather                                   75<br>Word                                      28<br>Length: 115, dtype: int64</pre><pre><br>&gt;&gt;&gt; print(df_high_rating.groupby([&#39;Rating&#39;,&#39;Type&#39;]).size())</pre><pre>Rating  Type<br>4.1     Free     675<br>        Paid      32<br>4.2     Free     889<br>        Paid      62<br>4.3     Free    1025<br>        Paid      51<br>4.4     Free    1031<br>        Paid      77<br>4.5     Free     964<br>        Paid      73<br>4.6     Free     741<br>        Paid      82<br>4.7     Free     446<br>        Paid      53<br>4.8     Free     195<br>        Paid      39<br>4.9     Free      81<br>        Paid       6<br>dtype: int64</pre><pre><br># store the grouped by table in a dataframe<br>&gt;&gt;&gt; df_group_by = pd.DataFrame({&#39;count&#39;: df_high_rating.groupby([&#39;Rating&#39;,&#39;Type&#39;]).size()}).reset_index()</pre><pre><br># iterating through groupby<br>&gt;&gt;&gt; grouped = df_high_rating.groupby(&#39;Rating&#39;)<br>&gt;&gt;&gt; for name,group in grouped:<br>        if name &gt;= 4.8: #only printing for rating 4.8 and 4.9<br>            print(name)<br>            print(group)<br>            print(&quot;=&quot;*50)</pre><pre><br># aggregation<br>&gt;&gt;&gt; grouped = df.groupby(&#39;Genres&#39;)<br>&gt;&gt;&gt; print(grouped[&#39;Rating&#39;].agg(np.mean))</pre><pre>Genres<br>Action                                   4.285475<br>Action;Action &amp; Adventure                4.311765<br>Adventure                                4.180822<br>Adventure;Action &amp; Adventure             4.423077<br>Adventure;Brain Games                    4.600000<br>Adventure;Education                      4.100000<br>Arcade                                   4.304348<br>Arcade;Action &amp; Adventure                4.346667<br>Arcade;Pretend Play                      4.500000<br>Art &amp; Design                             4.380000<br>Art &amp; Design;Creativity                  4.400000<br>Art &amp; Design;Pretend Play                3.900000<br>Auto &amp; Vehicles                          4.190411<br>Beauty                                   4.278571<br>Board                                    4.292683<br>Board;Action &amp; Adventure                 4.033333<br>Board;Brain Games                        4.340000<br>Board;Pretend Play                       4.800000<br>Books &amp; Reference                        4.346067<br>Books &amp; Reference;Education              4.200000<br>Business                                 4.121452<br>Card                                     4.086667<br>Card;Action &amp; Adventure                  4.300000<br>Card;Brain Games                         4.400000<br>Casino                                   4.286486<br>Casual                                   4.150811<br>Casual;Action &amp; Adventure                4.266667<br>Casual;Brain Games                       4.469231<br>Casual;Creativity                        4.314286<br>Casual;Education                         4.266667<br>                                           ...   <br>Puzzle;Education                         4.600000<br>Racing                                   4.173118<br>Racing;Action &amp; Adventure                4.300000<br>Racing;Pretend Play                      4.500000<br>Role Playing                             4.275472<br>Role Playing;Action &amp; Adventure          4.342857<br>Role Playing;Brain Games                 4.300000<br>Role Playing;Pretend Play                4.020000<br>Shopping                                 4.259664<br>Simulation                               4.151546<br>Simulation;Action &amp; Adventure            4.418182<br>Simulation;Education                     4.366667<br>Simulation;Pretend Play                  4.350000<br>Social                                   4.255598<br>Sports                                   4.236637<br>Sports;Action &amp; Adventure                4.350000<br>Strategy                                 4.245631<br>Strategy;Action &amp; Adventure              4.600000<br>Strategy;Creativity                      4.400000<br>Strategy;Education                       4.500000<br>Tools                                    4.046585<br>Tools;Education                          4.500000<br>Travel &amp; Local                           4.109333<br>Travel &amp; Local;Action &amp; Adventure        4.100000<br>Trivia                                   4.039286<br>Video Players &amp; Editors                  4.063924<br>Video Players &amp; Editors;Creativity       4.100000<br>Video Players &amp; Editors;Music &amp; Video    4.000000<br>Weather                                  4.244000<br>Word                                     4.410714<br>Name: Rating, Length: 115, dtype: float64</pre><pre><br># applying multiple aggregation functions at once<br>&gt;&gt;&gt; print(grouped[&#39;Rating&#39;].agg([np.sum, np.mean, np.std]))</pre><pre>                                        sum      mean       std<br>Genres                                                           <br>Action                                 1534.2  4.285475  0.291353<br>Action;Action &amp; Adventure                73.3  4.311765  0.172780<br>Adventure                               305.2  4.180822  0.312542<br>Adventure;Action &amp; Adventure             57.5  4.423077  0.148064<br>Adventure;Brain Games                     4.6  4.600000       NaN<br>Adventure;Education                       8.2  4.100000  0.000000<br>Arcade                                  891.0  4.304348  0.351323<br>Arcade;Action &amp; Adventure                65.2  4.346667  0.306749<br>Arcade;Pretend Play                       4.5  4.500000       NaN<br>Art &amp; Design                            240.9  4.380000  0.321685<br>Art &amp; Design;Creativity                  30.8  4.400000  0.404145<br>Art &amp; Design;Pretend Play                 7.8  3.900000  0.000000<br>Auto &amp; Vehicles                         305.9  4.190411  0.543692<br>Beauty                                  179.7  4.278571  0.362603<br>Board                                   176.0  4.292683  0.417367<br>Board;Action &amp; Adventure                 12.1  4.033333  0.057735<br>Board;Brain Games                        65.1  4.340000  0.297129<br>Board;Pretend Play                        4.8  4.800000       NaN<br>Books &amp; Reference                       773.6  4.346067  0.429046<br>Books &amp; Reference;Education               8.4  4.200000  0.707107<br>Business                               1248.8  4.121452  0.624422<br>Card                                    183.9  4.086667  0.708263<br>Card;Action &amp; Adventure                   8.6  4.300000  0.000000<br>Card;Brain Games                          4.4  4.400000       NaN<br>Casino                                  158.6  4.286486  0.310163<br>Casual                                  767.9  4.150811  0.442218<br>Casual;Action &amp; Adventure                89.6  4.266667  0.367877<br>Casual;Brain Games                       58.1  4.469231  0.209701<br>Casual;Creativity                        30.2  4.314286  0.291139<br>Casual;Education                         12.8  4.266667  0.152753<br>...                                       ...       ...       ...<br>Puzzle;Education                          4.6  4.600000       NaN<br>Racing                                  388.1  4.173118  0.327089<br>Racing;Action &amp; Adventure                86.0  4.300000  0.194666<br>Racing;Pretend Play                       4.5  4.500000       NaN<br>Role Playing                            453.2  4.275472  0.340815<br>Role Playing;Action &amp; Adventure          30.4  4.342857  0.229907<br>Role Playing;Brain Games                  4.3  4.300000       NaN<br>Role Playing;Pretend Play                20.1  4.020000  0.426615<br>Shopping                               1013.8  4.259664  0.404577<br>Simulation                              805.4  4.151546  0.401710<br>Simulation;Action &amp; Adventure            48.6  4.418182  0.252262<br>Simulation;Education                     13.1  4.366667  0.152753<br>Simulation;Pretend Play                  17.4  4.350000  0.331662<br>Social                                 1102.2  4.255598  0.413809<br>Sports                                 1410.8  4.236637  0.423600<br>Sports;Action &amp; Adventure                17.4  4.350000  0.191485<br>Strategy                                437.3  4.245631  0.373583<br>Strategy;Action &amp; Adventure               9.2  4.600000  0.000000<br>Strategy;Creativity                       4.4  4.400000       NaN<br>Strategy;Education                        4.5  4.500000       NaN<br>Tools                                  2962.1  4.046585  0.616731<br>Tools;Education                           4.5  4.500000       NaN<br>Travel &amp; Local                          924.6  4.109333  0.505816<br>Travel &amp; Local;Action &amp; Adventure         4.1  4.100000       NaN<br>Trivia                                  113.1  4.039286  0.808904<br>Video Players &amp; Editors                 642.1  4.063924  0.554566<br>Video Players &amp; Editors;Creativity        8.2  4.100000  0.000000<br>Video Players &amp; Editors;Music &amp; Video    12.0  4.000000  0.000000<br>Weather                                 318.3  4.244000  0.331353<br>Word                                    123.5  4.410714  0.325849<br><br>[115 rows x 3 columns]</pre><h3>Iteration</h3><p>To iterate over the rows of the DataFrame, we can use the following functions:</p><ul><li><strong>df.iteritems()</strong> − to iterate over the (key,value) pairs</li><li><strong>df.iterrows()</strong> − iterate over the rows as (index,series) pairs</li><li><strong>df.itertuples()</strong> − this method will return an iterator yielding a named tuple for each row in the DataFrame. The <strong>first element</strong> of the tuple will be the <strong>row’s corresponding index value</strong>, while the remaining values are the row values.</li></ul><pre>&gt;&gt;&gt; iterated_df = pd.DataFrame(np.random.randn(4,3),columns=[&#39;col1&#39;,&#39;col2&#39;,&#39;col3&#39;])<br>&gt;&gt;&gt; for key,value in iterated_df.iteritems():<br>        print(key)<br>        print(value)</pre><pre>col1<br>0   -0.031657<br>1   -2.031456<br>2    2.820815<br>3   -0.153405<br>Name: col1, dtype: float64<br>col2<br>0    0.152370<br>1   -1.157595<br>2    2.817094<br>3   -0.227610<br>Name: col2, dtype: float64<br>col3<br>0    1.047588<br>1   -0.461455<br>2   -0.177125<br>3   -0.698067<br>Name: col3, dtype: float64</pre><h3>Operations with text data</h3><p>String operations can be performed on Series in the format <strong>s.str.op</strong> where <strong>op</strong> can be:</p><ol><li><strong>swapcase</strong> — Swaps the case lower/upper.</li><li><strong>lower() / upper()</strong> — Converts strings in the Series/Index to lower / upper case.</li><li><strong>len()</strong> — Computes String length.</li><li><strong>strip()</strong> — Helps strip whitespace(including newline) from each string in the Series/index from both the sides.</li><li><strong>split(‘ ‘)</strong> — Splits each string with the given pattern.</li><li><strong>cat(sep=’ ‘)</strong> — Concatenates the series/index elements with given separator.</li><li><strong>get_dummies()</strong> — Returns the DataFrame with One-Hot Encoded values.</li><li><strong>contains(pattern)</strong> — Returns Boolean True for each element if the substring contains in the element, else False.</li><li><strong>replace(a,b)</strong> — Replaces the value a with the value b.</li><li><strong>repeat(value)</strong> — Repeats each element with specified number of times.</li><li><strong>count(pattern)</strong> — Returns count of appearance of pattern in each element.</li><li><strong>startswith(pattern) / endswith(pattern)</strong> — Returns true if the element in the Series/Index starts / ends with the pattern.</li><li><strong>find(pattern)</strong> — Returns the first position of the first occurrence of the pattern. Returns -1 if not found.</li><li><strong>findall(pattern)</strong> — Returns a list of all occurrence of the pattern.</li><li><strong>islower() / isupper() / isnumeric()</strong> — Checks whether all characters in each string in the Series/Index in lower / upper case / numeric or not. Returns Boolean.</li></ol><pre>&gt;&gt;&gt; s = pd.Series([&#39;Tom &#39;, &#39; William Rick&#39;, &#39;John&#39;, &#39;Alber@t&#39;])<br>&gt;&gt;&gt; print(s.str.contains(&#39; &#39;))</pre><pre>0     True<br>1     True<br>2    False<br>3    False<br>dtype: bool</pre><h3>Joining, Merging</h3><ol><li><strong>df1.append(df2)</strong> — Adds the rows in df1 to the end of df2 (columns should be identical)</li><li><strong>pd.concat([df1, df2], axis=1)</strong> — Adds the columns in df1 to the end of df2 (rows should be identical)</li><li><strong>pd.merge(left, right, how=’inner’, on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True)</strong> — where</li></ol><ul><li>left − A DataFrame object.</li><li>right − Another DataFrame object.</li><li>how − One of ‘left’, ‘right’, ‘outer’, ‘inner’. Defaults to inner. Each method has been described below.</li><li>on − Columns (names) to join on. <strong>Must be found in both</strong> the left and right DataFrame objects.</li><li>left_on − Columns from the left DataFrame to use as keys.</li><li>right_on − Columns from the right DataFrame to use as keys.</li><li>left_index − If True, use the index (row labels) from the left DataFrame as its join key(s). In case of a DataFrame with a MultiIndex (hierarchical), the number of levels must match the number of join keys from the right DataFrame.</li><li>right_index − Same usage as left_index for the right DataFrame.</li><li>sort − Sort the result DataFrame by the join keys in <em>lexicographical order</em>. Defaults to True, setting to False will improve the performance substantially in many cases.</li></ul><pre>&gt;&gt;&gt; left = pd.DataFrame({<br>         &#39;id&#39;:[1,2,3,4,5],<br>         &#39;Name&#39;: [&#39;Alex&#39;, &#39;Amy&#39;, &#39;Allen&#39;, &#39;Alice&#39;, &#39;Ayan&#39;],<br>         &#39;subject_id&#39;:[&#39;sub1&#39;,&#39;sub2&#39;,&#39;sub4&#39;,&#39;sub6&#39;,&#39;sub5&#39;]})</pre><pre>&gt;&gt;&gt; right = pd.DataFrame(<br>         {&#39;id&#39;:[1,2,3,4,5],<br>         &#39;Name&#39;: [&#39;Billy&#39;, &#39;Brian&#39;, &#39;Brock&#39;, &#39;Bryce&#39;, &#39;Betty&#39;],<br>         &#39;subject_id&#39;:[&#39;sub2&#39;,&#39;sub4&#39;,&#39;sub3&#39;,&#39;sub6&#39;,&#39;sub5&#39;]})</pre><pre>&gt;&gt;&gt; print(pd.concat([left,right],ignore_index=True)) # merging by rows<br>&gt;&gt;&gt; print(&#39;=&#39;*50)<br>&gt;&gt;&gt; print(left.append(right)) # also merging by rows<br>&gt;&gt;&gt; print(&#39;=&#39;*50)<br>&gt;&gt;&gt; print(pd.concat([left,right],axis=1)) # merging by columns</pre><pre>   id   Name subject_id<br>0   1   Alex       sub1<br>1   2    Amy       sub2<br>2   3  Allen       sub4<br>3   4  Alice       sub6<br>4   5   Ayan       sub5<br>5   1  Billy       sub2<br>6   2  Brian       sub4<br>7   3  Brock       sub3<br>8   4  Bryce       sub6<br>9   5  Betty       sub5<br>==================================================<br>   id   Name subject_id<br>0   1   Alex       sub1<br>1   2    Amy       sub2<br>2   3  Allen       sub4<br>3   4  Alice       sub6<br>4   5   Ayan       sub5<br>0   1  Billy       sub2<br>1   2  Brian       sub4<br>2   3  Brock       sub3<br>3   4  Bryce       sub6<br>4   5  Betty       sub5<br>==================================================<br>   id   Name subject_id  id   Name subject_id<br>0   1   Alex       sub1   1  Billy       sub2<br>1   2    Amy       sub2   2  Brian       sub4<br>2   3  Allen       sub4   3  Brock       sub3<br>3   4  Alice       sub6   4  Bryce       sub6<br>4   5   Ayan       sub5   5  Betty       sub5</pre><pre><br># merge two dataframes on a key<br>&gt;&gt;&gt; print(pd.merge(left,right,on=&#39;id&#39;))<br>&gt;&gt;&gt; print(&#39;=&#39;*50)<br># merge two dataframes on multiple keys<br>&gt;&gt;&gt; print(pd.merge(left,right,on=[&#39;id&#39;,&#39;subject_id&#39;]))</pre><pre>   id Name_x subject_id_x Name_y subject_id_y<br>0   1   Alex         sub1  Billy         sub2<br>1   2    Amy         sub2  Brian         sub4<br>2   3  Allen         sub4  Brock         sub3<br>3   4  Alice         sub6  Bryce         sub6<br>4   5   Ayan         sub5  Betty         sub5<br>==================================================<br>   id Name_x subject_id Name_y<br>0   4  Alice       sub6  Bryce<br>1   5   Ayan       sub5  Betty<br></pre><pre>| Merge Method | SQL Equivalent | Description |<br>| left  | LEFT OUTER JOIN  | Use keys from left object |<br>| right | RIGHT OUTER JOIN | Use keys from right object |<br>| outer | FULL OUTER JOIN  | Use union of keys |<br>| inner | INNER JOIN       | Use intersection of keys |</pre><pre><br>&gt;&gt;&gt; print(pd.merge(left, right, on=&#39;subject_id&#39;, how=&#39;inner&#39;))</pre><pre>    id_x Name_x subject_id  id_y Name_y<br>0     2    Amy       sub2     1  Billy<br>1     3  Allen       sub4     2  Brian<br>2     4  Alice       sub6     4  Bryce<br>3     5   Ayan       sub5     5  Betty</pre><h3>Statistics</h3><ul><li><strong>df.mean()</strong> — Returns the mean of all columns</li><li><strong>df.corr()</strong> — Returns the correlation between columns in a DataFrame</li><li><strong>df.count()</strong> — Returns the number of non-null values in each DataFrame column</li><li><strong>df.max()</strong> — Returns the highest value in each column</li><li><strong>df.min()</strong> — Returns the lowest value in each column</li><li><strong>df.median()</strong> — Returns the median of each column</li><li><strong>df.std()</strong> — Returns the standard deviation of each column</li></ul><pre>&gt;&gt;&gt; df[&#39;Rating&#39;].mean()</pre><pre>4.191837606837606</pre><h3>Visualization</h3><p>The following charts we can generate straight from pandas:</p><ul><li><strong>bar</strong> or <strong>barh</strong> for bar plots</li><li><strong>hist</strong> for histogram</li><li><strong>area</strong> for area plots</li><li><strong>scatter</strong> for scatter plots</li></ul><pre>&gt;&gt;&gt; df_group_by[df_group_by[&#39;Type&#39;]==&#39;Free&#39;][&#39;count&#39;].plot()</pre><pre>&lt;matplotlib.axes._subplots.AxesSubplot at 0x7f0dd22b64e0&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*NJ2ExZppRpdqO5ETfvxlsw.png" /></figure><pre>&gt;&gt;&gt; df_bar = df_high_rating[[&#39;Rating&#39;,&#39;Reviews&#39;]][:10]<br>&gt;&gt;&gt; df_bar[&#39;Reviews&#39;] = df_bar[&#39;Reviews&#39;].astype(int)</pre><pre>&gt;&gt;&gt; df_bar.plot.bar(stacked = True)</pre><pre>&lt;matplotlib.axes._subplots.AxesSubplot at 0x7f0dd221cdd8&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*rQPKgfxJvB5ewRqPtiA5_g.png" /></figure><pre>&gt;&gt;&gt; df_bar.plot.scatter(x=&#39;Rating&#39;, y=&#39;Reviews&#39;)</pre><pre>&lt;matplotlib.axes._subplots.AxesSubplot at 0x7f0dd21487b8&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*hwpFgGXsoi3eY6wP9M8C4w.png" /></figure><h3>Exporting the Data</h3><ul><li><strong>df.to_csv(filename)</strong> — Writes to a CSV file</li><li><strong>df.to_excel(filename)</strong> — Writes to an Excel file</li><li><strong>df.to_sql(table_name, connection_object)</strong> — Writes to a SQL table</li><li><strong>df.to_json(filename)</strong> — Writes to a file in JSON format</li><li><strong>df.to_html(filename)</strong> — Saves as an HTML table</li></ul><pre>&gt;&gt;&gt; df_new_cols_name.to_csv(&#39;./google-play-store-apps/cleaned_googleplay_data.csv&#39;)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6561896b1b62f6a58a3120ff257a65a/href">https://medium.com/media/c6561896b1b62f6a58a3120ff257a65a/href</a></iframe><p>I hope you have liked this article. If yes, then do share it with your friends or colleagues who you think will be benefited. Also, give it a clap to reach for more audience.</p><p>PS: If you don’t know, you can give at max 50 claps for every article in Medium. ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da1697aee647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Not-so-Quick-but-Conceptual guide on Python | Notebook | Intermediate — Part 2]]></title>
            <link>https://tamoghnasaha-22.medium.com/a-not-so-quick-but-conceptual-guide-on-python-notebook-intermediate-part-2-b476d24765db?source=rss-13abc86e42f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b476d24765db</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[intermediate]]></category>
            <dc:creator><![CDATA[Tamoghna Saha]]></dc:creator>
            <pubDate>Tue, 13 Nov 2018 02:47:58 GMT</pubDate>
            <atom:updated>2021-11-17T18:32:20.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Quick guide to Python | Notebook | Intermediate — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPdz3xJX5Pljw73FHgjYAw.png" /></figure><p>Let me be honest. This notebook took me a lot more time than I excepted because I want my audience to understand the concepts of the some of the topics mentioned below in as granular level as possible, yet not making the notebook lengthy.</p><p>As promised, this is the part 2 of Python Intermediate of my Python Tutorial series. In this notebook, I have covered:<br>1. List Slices and Comprehension<br>2. Lambda<br>3. Map, Filter &amp; Reduce<br>4. Decorator<br>5. Class<br>6. Iterable, Iterator and Generator</p><p>I have tried to explain the <strong>Decorator</strong>, and <strong>Iterator and Generator</strong> with more details. Before diving into this section, I highly recommend you guys to go through these articles if you haven’t.</p><p><a href="https://medium.com/@tamoghnasaha.22/a-quick-guide-to-python-notebook-beginners-6bbe3e2bb762">Python Notebook | Beginners</a><br><a href="https://medium.com/@tamoghnasaha.22/a-not-so-quick-but-conceptual-guide-to-python-notebook-intermediate-part-1-affd908a2a49">Python Notebook | Intermediate | Part 1</a></p><h3>List Slices</h3><p><strong>List slices</strong> provides an advanced way of retrieving values from a list. Basic list slicing involves indexing a list with <strong>two colon-separated integers</strong>. These three arguments are <em>lower limit, upper limit and step</em>. This returns a new list containing all the values in the old list between the indices specified. By default, lower limit is at index 0, upper limit is at the last value and step is +1.</p><p>You can also take a step backwards. When <strong>negative values</strong> are used for the first and second values in a slice, they <strong>count from the end of list</strong>.</p><p>The indexing of the iterable item starts from 0 if we take it from left and -1 if we take it from the right.</p><p><strong>NOTE</strong>: Slicing can also be done on <strong>tuple</strong>.</p><pre>squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</pre><pre>print(squares[:])<br>print(squares[::2])<br>print(squares[2:8:2])<br>print(squares[6:])<br>print(squares[4:14])<br>print(squares[1:-2])<br>print(squares[-5:-2])<br>print(squares[7:1:-2])<br>print(squares[::-1])</pre><pre>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]<br>[0, 4, 16, 36, 64]<br>[4, 16, 36]<br>[36, 49, 64, 81]<br>[16, 25, 36, 49, 64, 81]<br>[1, 4, 9, 16, 25, 36, 49]<br>[25, 36, 49]<br>[49, 25, 9]<br>[81, 64, 49, 36, 25, 16, 9, 4, 1, 0]</pre><h3>List Comprehension</h3><p>List comprehension is a useful way of quickly creating lists using simplified version of <em>for</em> loop statement. A list comprehension <strong>can also contain an if statement</strong> to enforce a condition on values in the list.</p><p><strong>NOTE</strong>: Trying to create a list, by any means, in a very extensive range will result in a <strong>MemoryError</strong>.</p><pre>var = [2*i for i in range(10**100)]</pre><h4>DON’T EVEN TRY IT!</h4><pre>evens=[i**2 for i in range(10) if i**2 % 2 == 0]<br>print(evens)</pre><pre>[0, 4, 16, 36, 64]</pre><pre><br># modify element of list by index value</pre><pre>num = [1,2,3,4,5,6,7,8]<br>list_of_index = [i for i in num if num.index(i)%2 == 0]<br>print(list_of_index)<br>even_num = [num[i] for i in list_of_index]<br>print(even_num)</pre><pre>[1, 3, 5, 7]<br>[2, 4, 6, 8]</pre><h3>Lamda</h3><p>In Python, <strong>anonymous function</strong> means a function <strong>without a name</strong>, whereas we use <em>def</em> keyword to create normal functions. The <strong>lambda</strong> function is used for creating <em>small, one-time and anonymous</em> function objects in Python. The lambda operator can have <strong>any number of arguments</strong>, but it can have <strong>only one expression</strong>. The lambda functions can be assigned to variables, and used like normal functions.</p><p>Use lambda functions when an anonymous function is required for a short period of time.</p><pre>#named function<br>def polynomial(x):<br>    &#39;&#39;&#39;<br>    Function to perform a polynomial calculation having a single variable x<br>    &#39;&#39;&#39;<br>    return x**2 + 5*x + 4</pre><pre>print(&quot;The result for named function: {}&quot;.format(polynomial(-4)))</pre><pre>#lambda<br>poly = lambda x: x**2 + 5*x + 4<br>print(&quot;The result for anonymous function: {}&quot;.format(poly(-4)))</pre><pre>The result for named function: 0<br>The result for anonymous function: 0</pre><h3>Map, Filter &amp; Reduce</h3><p>The built-in functions <strong>map</strong>, <strong>filter</strong> and <strong>reduce</strong> are very useful higher-order functions that operate on iterable.</p><p>The function <strong>map</strong> takes a function and an iterable as <em>arguments</em>, and returns a <em>new iterable</em> with the function applied to each argument.</p><p>The function <strong>filter</strong> filters an iterable by removing items that don’t match a <strong>predicate (a function that returns ONLY Boolean True)</strong>.</p><p>The function <strong>reduce</strong> applies a rolling computation to sequential pairs of values in a iterable i.e., wanted to compute the product of a list items, sum of tuple items.</p><p><strong>NOTE</strong>: Both in map and filter, the result has to be explicitly converted to a list or tuple if you want to print it. Python 2 returns a list by default, but this was changed in Python 3 which returns map or filter object, hence the need for the list or tuple function.</p><pre>def add_five(x):<br>    return x + 5</pre><pre>num_var = [11, 22, 33, 44, 55]<br>map_result = list(map(add_five, num_var)) # map<br>print(map_result)</pre><pre>filter_result = tuple(filter(lambda x: x%2==0, num_var)) # filter<br>print(filter_result)</pre><pre>from functools import reduce<br>reduce_result = reduce((lambda x, y: x*y), num_var) # reduce<br>print(reduce_result)</pre><pre>[16, 27, 38, 49, 60]<br>(22, 44)<br>19326120</pre><pre># what do you think is the output?<br>mylist = [1,2,3,4,5]</pre><pre>print(tuple(map(lambda x: x if x&gt;2 else 0, mylist)))<br>print(list(filter(lambda x: x if x&gt;2 else 0, mylist)))</pre><pre>(0, 0, 3, 4, 5)<br>[3, 4, 5]</pre><h3>Decorator</h3><p><strong>Decorator</strong> are functions which modify the functionality of another function. Let’s go one step at a time to understand decorator. In the beginner’s article, we have mentioned that Python’s function is a <strong>first class object</strong> which can be</p><ul><li>dynamically created, destroyed</li><li>stored in a variable</li><li>passed to a function as a parameter</li><li>returned as a value from a function</li></ul><p>We have already seen the first point to be valid in the beginner’s article. Let’s validate each of these remaining 3 point.</p><pre>## functions can be assigned to a variable</pre><pre>def my_pymon(text): <br>    return &quot;Let&#39;s go, {}&quot;.format(text.upper())</pre><pre>i_choose_you = my_pymon<br>print(i_choose_you(&#39;pykachu&#39;))</pre><pre>print(&quot;=&quot;*20)</pre><pre>## functions can be passed as argument to another function</pre><pre>def your_pymon(text):<br>    return f&quot;{text}&quot;</pre><pre>def trainer_select(func):<br>    print(func(&quot;I choose you, &#39;char&#39;mander&quot;))</pre><pre>trainer_select(your_pymon)</pre><pre>print(&quot;=&quot;*20)</pre><pre>## function returned as a value from another function</pre><pre>def battle_began_with(mons):<br>    def who_won(someone):<br>        return f&quot;In the battle, {someone} won against {mons}&quot;<br>    return who_won</pre><pre>battle = battle_began_with(&quot;&#39;char&#39;mander&quot;)(&quot;pykachu&quot;)<br>print(battle)</pre><pre>Let&#39;s go, PYKACHU<br>====================<br>I choose you, &#39;char&#39;mander<br>====================<br>In the battle, pykachu won against &#39;char&#39;mander</pre><p><strong>When you put the pair of parentheses after the function name in main of code, only then the function gets executed. If you don’t put parentheses after it, then it can be passed around and can be assigned to other variables without executing it.</strong></p><pre>def my_decor(a_func):</pre><pre>def wrapper_func():<br>        print(&quot;I am doing some boring work before executing a_func()&quot;)<br>        a_func()<br>        print(&quot;I am doing some boring work after executing a_func()&quot;)</pre><pre>return wrapper_func</pre><pre>def a_function_requiring_decor():<br>    print(&quot;I am the function which needs some decoration!&quot;)<br>    <br>print(a_function_requiring_decor())</pre><pre>print(&quot;=&quot;*50)</pre><pre>a_function_requiring_decor = my_decor(a_function_requiring_decor) #the so-called decorator is happening here<br>print(a_function_requiring_decor())</pre><p>The variable <strong>a_function_requiring_decor</strong> is pointing to the <strong>wrapper_func</strong> inner function. We are <strong>returning wrapper_func as a function</strong> when we call <strong>my_decor(a_function_requiring_decor)</strong>. So, <strong>decorator wraps a function, modifying its behavior</strong>.</p><p>Another way to write these decorators is <strong>using @ symbol</strong>.</p><pre>def my_decorator(func):<br>    def wrapper():<br>        print(&quot;Take the marker and write something on the board.&quot;)<br>        func()<br>        print(&quot;Well done!&quot;)<br>    return wrapper</pre><pre><a href="http://twitter.com/my_decorator">@my_decorator</a><br>def tricky():<br>    print(&quot;SOMETHING!&quot;)<br>    <br>tricky()</pre><pre>Take the marker and write something on the board.<br>SOMETHING!<br>Well done!</pre><h3>Class</h3><p>Python is an <em>object-oriented programming</em> (OOP) language and objects are created using <strong>class</strong> which is actually the focal point of OOP. The class describes an object’s blueprint, description or metadata. Multiple object can be instantiated using the <em>same class</em>.</p><p>Classes are created using the keyword <strong>class</strong> and an indented block, which contains class <em>methods</em>.</p><p>Let’s take a look at an example.</p><pre>class Pet:<br>    def __init__(self, genre, name, owner):<br>        self.genre = genre <br>        self.name = name<br>        self.owner = owner<br>        <br>    def voice(self): #another method added to the class Pet<br>        print(&quot;Growl!&quot;)<br>        <br>pokemon = Pet(&quot;dog&quot;,&quot;Arcanine&quot;,&quot;Tim&quot;)<br>print(pokemon.name)<br>pokemon.voice()</pre><pre>Arcanine<br>Growl!</pre><p>The <strong>__ init__</strong> method is the most important method in a class which is called when an instance (object) of the class is created. <strong>All methods must have self as their first parameter</strong>, although you do not need to pass it explicitly when you call the method.</p><p>Within the method definition, <strong>self</strong> refers to the object itself calling the method. From the above example, we see that</p><pre>pokemon = Pet(&quot;dog&quot;,&quot;Arcanine&quot;,&quot;Tim&quot;)<br>print(pokemon.name)<br>&gt;&gt;&gt; Arcanine</pre><ul><li>When we create the pokemon object from the class Pet, we are passing <em>genre, name and owner</em> as “dog”,”Arcanine”,”Tim” and the object (pokemon) will take the place of self.</li><li>The attributes are accessed using the <strong>dot</strong> operator.</li><li>So <strong>pokemon is the object</strong>, “<em>Arcanine</em>” is the value of the <strong>name</strong> attribute of this object.</li></ul><p>Hence, we can access the attributes in a class using this way: <strong>object.attributes</strong>.</p><p>Classes can have other methods defined to add functionality to them. These methods are accessed using the same dot syntax as attributes.</p><p><strong>NOTE</strong>: All methods <strong>must have self</strong> as their first parameter.</p><p>Trying to access an attribute of an instance that isn’t defined causes an <strong>AttributeError</strong>.</p><h3>Iterable, Iterator and Generator</h3><h4>Iterable and Iterator</h4><p>Iteration -&gt; Repetition of a process.</p><p><strong>Iterable</strong> is a type of object which would <strong>generate an Iterator</strong> when passed to in-built method <strong>iter()</strong>.</p><p><strong>Iterator</strong> is an object which is used to iterate over an <em>iterable object</em> using <strong>next</strong>() method, which returns the next item of the <em>iterable object</em>. Any object that has a <strong>next</strong>() method is therefore an iterator.</p><p><strong>NOTE</strong>: List, Tuple, Set, Frozenset, Dictionary are in-built <strong>iterable objects</strong>. They are <strong>iterable containers</strong> from which you can get an <strong>iterator</strong>.</p><p>This is what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9l5bpqRGEa4LNLg3WTISPg.png" /></figure><pre>## Let&#39;s see an example<br>my_tuple = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>iterated_tuple = iter(my_tuple)</pre><pre>print(type(iterated_tuple))<br>print(next(iterated_tuple))<br>print(next(iterated_tuple))<br>print(next(iterated_tuple))</pre><pre>&lt;class &#39;list_iterator&#39;&gt;<br>apple<br>banana<br>cherry</pre><pre>## same thing can be written using for loop<br>my_tuple = (&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;)</pre><pre>for i in my_tuple:<br>    print(i)</pre><pre>apple<br>banana<br>cherry</pre><p><strong>How for loop actually works?</strong></p><p>The for loop can iterate over any iterable.</p><pre>for element in iterable:<br>    # do something with element</pre><p>is actually implemented as</p><pre># create an iterator object from that iterable<br>iter_obj = iter(iterable)</pre><pre># infinite loop<br>while True:<br>    try:<br>        # get the next item<br>        element = next(iter_obj)<br>        # do something with element<br>    except StopIteration:<br>        # if StopIteration is raised, break from loop<br>        break</pre><ul><li>The for loop creates an iterator object internally, <strong>iter_obj</strong> by calling <em>iter()</em> on the iterable.</li><li>Inside the <strong>while loop</strong>, it calls <em>next()</em> to get the next element and executes further</li><li>After all the items exhaust, <strong>StopIteration</strong> exception is raised which is internally caught and the loop ends.</li></ul><p>To get a better sense of the internals of an iterator, let’s build an iterator producing the <strong>Fibonacci numbers</strong>.</p><pre>from itertools import islice</pre><pre>class fib:<br>     def __init__(self):<br>        self.prev = 0<br>        self.curr = 1<br> <br>     def __iter__(self):<br>        return self<br> <br>     def __next__(self):<br>        value = self.curr<br>        self.curr += self.prev<br>        self.prev = value<br>        return value</pre><pre>f = fib()<br>print(list(islice(f, 0, 10)))</pre><h3>Generator</h3><p>A lot of overhead in building an iterator:</p><ul><li>implement a class with iter() and next() methods</li><li>raise StopIteration when there was no values to be returned</li><li>makes the code lengthy</li></ul><p>Python Generators are a simple way of creating iterators. All the above mentioned overhead are automatically handled by generators in Python.</p><p><strong>Generator</strong> is a block of code, same as defining a function, having a <strong>yield</strong> statement instead of a <strong>return</strong> statement. If a function contains <strong>at least one yield </strong>statement (it may contain other yield or return statements), it becomes a generator!</p><p>The yield statement suspends function’s execution and sends a value back to caller, but retains enough capability to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list. <strong>We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory</strong>.</p><p>This is how the above Fibonacci number code looks like using generator.</p><pre>def fib():<br>    prev, curr = 0, 1<br>    while True:<br>        yield curr<br>        prev, curr = curr, prev + curr</pre><pre>f = fib()<br>print(list(islice(f, 0, 10)))</pre><h4>Let’s see what happened.</h4><p>Take note that <strong>fib</strong> is defined as a normal Python function, not as class. However, there’s <strong>no return keyword</strong> inside the function body. <strong>The return value of the function will be a generator</strong>.</p><ol><li>Now when <strong>f = fib()</strong> is called, the generator is instantiated and returned. <strong>No code will be executed</strong> at this point.To be explicit: the line prev, curr = 0, 1 is not executed yet.</li><li>Then, this generator instance is wrapped in an islice(). This is itself also an iterator. Again, no code executed.</li><li>Now, this iterator is wrapped in a <strong>list()</strong>, which will take the argument and build a list from it. To do so, it will start calling next() on the islice() instance, which in turn will start calling next() on our f instance.</li><li>On the first call, the code <strong>prev, curr = 0, 1</strong> gets executed, then the <strong>while True</strong> loop is entered, and then it encounters the <strong>yield curr</strong> statement. It will produce the value that’s currently in the <em>curr</em> variable and become idle again. This value is passed to the <em>islice()</em> wrapper, which will produce the value (1 in this case) and list can add the value to the list.</li><li>Then, list asks islice() for the next value, which will ask f for the next value, which will <em>unpause</em> f from its previous state, resuming with the statement <strong>prev, curr = curr, prev + curr</strong>.</li><li>Then it re-enters the next iteration of the <strong>while True</strong> loop, and hits the <strong>yield curr</strong> statement, returning the next value of curr.</li><li>This happens until the output list is 10 elements long. When list() asks islice() for the 11th value, islice() will raise a <strong>StopIteration</strong> exception, indicating that the end has been reached, and list will return the result: a list of 10 items, containing the first 10 Fibonacci numbers.</li></ol><p>There are two types of generators in Python: <strong>generator functions</strong> and <strong>generator expressions</strong>. A generator function is any function in which the keyword <strong>yield</strong> appears in its body. We just saw an example of that. Generator expression is equivalent to list comprehension.</p><h4>To avoid any confusion between iterable, iterator, generator, generator expression, a {list, set, dict} comprehension, check out this diagram.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbQHbTDlXaB4BFza3ijOow.png" /></figure><p>As always, I am attaching the notebook below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ca90d93c451e95e3f38e5f3fac85b27/href">https://medium.com/media/0ca90d93c451e95e3f38e5f3fac85b27/href</a></iframe><p>I hope you have enjoyed this article. Stay tuned for the Python advanced. Peace. ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b476d24765db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Not-so-Quick-but-Conceptual guide to Python — Notebook | Intermediate | Part 1]]></title>
            <link>https://tamoghnasaha-22.medium.com/a-not-so-quick-but-conceptual-guide-to-python-notebook-intermediate-part-1-affd908a2a49?source=rss-13abc86e42f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/affd908a2a49</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[intermediate]]></category>
            <dc:creator><![CDATA[Tamoghna Saha]]></dc:creator>
            <pubDate>Sat, 10 Nov 2018 17:16:56 GMT</pubDate>
            <atom:updated>2021-11-17T18:31:34.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Quick guide to Python — Notebook | Intermediate | Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPdz3xJX5Pljw73FHgjYAw.png" /></figure><p>Hi. As mentioned in my <a href="https://medium.com/@tamoghnasaha.22/a-quick-guide-to-python-notebook-beginners-6bbe3e2bb762">previous article</a>, I am now sharing the intermediate part of the Python Tutorial series. I decided to split this part up into 2. Part 1 covers:<br>1. Data Types [list, tuple, dictionary, set, frozenset]<br>2. Conditional statements and loops [if-elif-else, for, while, break, continue]<br>3. File IO [read, write, append, close]<br>4. Exception Handling [try/except, finally, assertion]</p><h3>More Data Types</h3><p><strong>List of immutable objects:</strong></p><ul><li>bool</li><li>int</li><li>float</li><li>str</li><li>tuple</li><li>frozenset</li></ul><p><strong>List of mutable objects:</strong></p><ul><li>list</li><li>set</li><li>dict</li></ul><h3>List</h3><p>List is a type of <strong>mutable</strong> object in Python used to store an <strong>indexed</strong> list of item. It is created using <strong>square brackets</strong> with commas separating the items. A certain item from the list can be accessed using it’s index number.</p><p>An empty list is created using an empty pair of square brackets.</p><p>A list can contain items of a <strong>single item type or multiple item type</strong>. A list within a list is also possible which is used to represent 2D grids as Python, by default, lacks multi-dimensional array feature. But this can be achieved using <strong>numpy</strong> which we will discuss in our Advanced Notebook.</p><p><strong>NOTE: Strings can be indexed like a list</strong>.</p><pre>&gt;&gt;&gt; empty_list = []</pre><pre>&gt;&gt;&gt; words = [&#39;Python&#39;,3.6,[&#39;Up Next&#39;,&#39;Tuple&#39;]]</pre><pre>&gt;&gt;&gt; print(words[0])<br>&gt;&gt;&gt; print(words[2][1])</pre><pre>&gt;&gt;&gt; print(words[1])<br>&gt;&gt;&gt; words[1]=2.7<br>&gt;&gt;&gt; print(words)</pre><pre>## accessing items of string by index<br>&gt;&gt;&gt; short_form = &quot;User Defined Function&quot;<br>&gt;&gt;&gt; print(&quot;In our last class, we went through {}{}{}&quot;.format(short_form[0], short_form[5], short_form[13]))</pre><pre>Python<br>Tuple<br>3.6<br>[&#39;Python&#39;, 2.7, [&#39;Up Next&#39;, &#39;Tuple&#39;]]<br>In our last class, we went through UDF</pre><pre>## basic list operations<br>&gt;&gt;&gt; num_list = [1,2,3]<br>&gt;&gt;&gt; print(num_list + [4,5,6])<br>&gt;&gt;&gt; print(num_list * 2)<br>&gt;&gt;&gt; print(4 in num_list)<br>&gt;&gt;&gt; print(9 not in num_list)<br>&gt;&gt;&gt; print(not 1 in num_list)</pre><pre>[1, 2, 3, 4, 5, 6]<br>[1, 2, 3, 1, 2, 3]<br>False<br>True<br>False</pre><pre># list functions and methods<br>&gt;&gt;&gt; num = [1,2,3]<br>&gt;&gt;&gt; num.append(4)<br>&gt;&gt;&gt; num.append([5,6])<br>&gt;&gt;&gt; print(num)</pre><pre>&gt;&gt;&gt; print(len(num))</pre><pre>&gt;&gt;&gt; num.extend([7,8,9])<br>&gt;&gt;&gt; print(num)<br>&gt;&gt;&gt; print(len(num))</pre><pre>&gt;&gt;&gt; index = 2<br>&gt;&gt;&gt; num.insert(index, 2.5)<br>&gt;&gt;&gt; print(num)</pre><pre>&gt;&gt;&gt; print(&quot;-----------------------------&quot;)</pre><pre>&gt;&gt;&gt; print(num.index(3))<br>&gt;&gt;&gt; print(num.index(2.0))</pre><pre>&gt;&gt;&gt; num.remove([5,6])<br>&gt;&gt;&gt; num.pop()<br>&gt;&gt;&gt; print(num)</pre><pre>&gt;&gt;&gt; print(max(num))<br>&gt;&gt;&gt; print(num.count(5))</pre><pre>&gt;&gt;&gt; num.reverse()<br>&gt;&gt;&gt; print(num)</pre><pre>[1, 2, 3, 4, [5, 6]]<br>5<br>[1, 2, 3, 4, [5, 6], 7, 8, 9]<br>8<br>[1, 2, 2.5, 3, 4, [5, 6], 7, 8, 9]<br>-----------------------------<br>3<br>1<br>[1, 2, 2.5, 3, 4, 7, 8]<br>8<br>0<br>[8, 7, 4, 3, 2.5, 2, 1]</pre><h3>Tuple</h3><p>Tuple is a <strong>immutable</strong> Python object created using <strong>Parentheses</strong> with commas separating the items which can be accessed using it’s index number.</p><p>It is just like list, except <strong>you cannot modify or re-assign a value in the tuple. It will throw TypeError</strong>.</p><p>An empty tuple can also be created in the same way you create empty list.</p><p><strong>NOTE: Tuples can also be created without using Parentheses, simply separated by commas.</strong></p><h4>But when should we put parenthesis on tuples, and when we shouldn’t?</h4><p><strong>Answer</strong>: We use parentheses for <strong>nested tuple</strong>.</p><pre>&gt;&gt;&gt; empty_tuple = ()</pre><pre>&gt;&gt;&gt; my_tuple = (&quot;is&quot;, &quot;my&quot;, &quot;tuple&quot;)<br>&gt;&gt;&gt; print(my_tuple[2])</pre><pre>&gt;&gt;&gt; also_my_tuple = &#39;is&#39;, &#39;this&#39;, &#39;one&#39;<br>&gt;&gt;&gt; print(also_my_tuple[3])</pre><pre>tuple</pre><pre>---------------------------------------------------------------------------<br>IndexError                                Traceback (most recent call last)<br>&lt;ipython-input-5-7a7df2b84a95&gt; in &lt;module&gt;<br><strong>      5</strong> <br><strong>      6</strong> also_my_tuple = &#39;is&#39;, &#39;this&#39;, &#39;one&#39;<br>----&gt; 7 print(also_my_tuple[3])<br><br>IndexError: tuple index out of range</pre><h3>Dictionaries</h3><p>Dictionaries are data structures used <strong>to map keys to values</strong>. Just like list, they are <strong>mutable</strong> and made using <strong>curly brackets</strong>.</p><p>Dictionaries can be indexed in the same way as lists, <strong>using square brackets containing keys</strong>. Trying to index a key that isn’t a part of the dictionary returns a <strong>KeyError</strong>.</p><p>The useful dictionary method is <strong>get</strong>. It does same thing as indexing, but if the key is not found in the dictionary, it returns <strong>None</strong> instead of throwing any error.</p><p><strong>NOTE: Only immutable objects can be used as keys to dictionaries.</strong></p><pre>&gt;&gt;&gt; empty_dict = {}</pre><pre>&gt;&gt;&gt; my_dict = {&quot;Joker&quot;:&#39;Why so serious?&#39;, &quot;Bane&quot;: [1,2,3], &quot;Scarecrow&quot;: 0.05}<br>&gt;&gt;&gt; print(my_dict[&quot;Joker&quot;])</pre><pre>&gt;&gt;&gt; my_dict_again = {(1,2,3):[1,2,3], (&#39;a&#39;,&#39;b&#39;,&#39;c&#39;):[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]}<br>&gt;&gt;&gt; print(my_dict_again[(1,2,3)])</pre><pre>&gt;&gt;&gt; my_dict_again[4] = &#39;d&#39;<br>&gt;&gt;&gt; print(my_dict_again)</pre><pre>&gt;&gt;&gt; print(empty_dict[0])</pre><pre>Why so serious?<br>[1, 2, 3]<br>{(1, 2, 3): [1, 2, 3], (&#39;a&#39;, &#39;b&#39;, &#39;c&#39;): [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;], 4: &#39;d&#39;}</pre><pre>---------------------------------------------------------------------------<br>KeyError                                  Traceback (most recent call last)<br>&lt;ipython-input-6-75e3176fb6bc&gt; in &lt;module&gt;<br><strong>     10</strong> print(my_dict_again)<br><strong>     11</strong> <br>---&gt; 12 print(empty_dict[0])<br><br>KeyError: 0</pre><p>Now see this.</p><pre>&gt;&gt;&gt; my_dict_error = {[1,2,3]:&#39;a&#39;,}</pre><pre>---------------------------------------------------------------------------<br>TypeError                                 Traceback (most recent call last)<br>&lt;ipython-input-8-859c69ec502a&gt; in &lt;module&gt;<br>----&gt; 1 my_dict_error = {[1,2,3]:&#39;a&#39;,}<br><br>TypeError: unhashable type: &#39;list&#39;</pre><h4>What does this error mean?</h4><p>An object is <strong>hashable</strong> if it has a hash value which never changes during its lifetime (it needs hash() method). List is unhashable because it’s content can change over its lifetime.</p><p><strong>NOTE</strong>: Don’t know about Hash function? Think about it as the fingerprint of a file in an encrypted format. For details, search in Google.</p><pre># How about a dictionary within a dictionary?<br>&gt;&gt;&gt; my_dict_yet_again = {0:&quot;infinity&quot;, 1:{&#39;a&#39;:[1,2]}, &#39;b&#39;:{2: (3,4)}}<br>&gt;&gt;&gt; print(my_dict_yet_again)<br>&gt;&gt;&gt; print(my_dict_yet_again[1][&#39;a&#39;])</pre><pre># Some dictionary functions<br>&gt;&gt;&gt; print(1 in my_dict_yet_again) # check if a key is available in the dictionary<br>&gt;&gt;&gt; print({&#39;a&#39;:[1,2]} in my_dict_yet_again.values()) #check if the value is available in the dictionary</pre><pre>&gt;&gt;&gt; my_dict_yet_again[True]=False<br>&gt;&gt;&gt; print(my_dict_yet_again)</pre><pre>&gt;&gt;&gt; print(my_dict_yet_again.get(1)) # get method<br>&gt;&gt;&gt; print(my_dict_yet_again.get(2))<br>&gt;&gt;&gt; print(my_dict_yet_again.get(&quot;True&quot;,&quot;True string is not available as key&quot;))</pre><pre>{0: &#39;infinity&#39;, 1: {&#39;a&#39;: [1, 2]}, &#39;b&#39;: {2: (3, 4)}}<br>[1, 2]<br>True<br>True<br>{0: &#39;infinity&#39;, 1: False, &#39;b&#39;: {2: (3, 4)}}<br>False<br>None<br>True string is not available as key</pre><h3>Set and Frozenset</h3><p>Sets are Python object similar to lists or dictionaries. They are created using <strong>curly braces</strong> or the <strong>set function</strong>. They are unordered, which means that they <strong>can’t be indexed</strong>. They <strong>cannot contain duplicate elements</strong>. Due to the way they’re stored, it’s <strong>faster to check whether an item is part of a set</strong>, rather than part of a list.</p><p>Instead of using <strong>append</strong> to add an item to a set, we use <strong>add</strong>. The method <strong>remove</strong> removes a specific element from a set but <strong>pop</strong> removes an arbitrary element.</p><pre>&gt;&gt;&gt; my_set = set((2.7,&quot;3.6&quot;))<br>&gt;&gt;&gt; also_my_set = {2.7, 3.6}<br>&gt;&gt;&gt; my_frozenset = frozenset((&quot;Python&quot;,&quot;2.7&quot;))</pre><pre>&gt;&gt;&gt; my_set.add(6)<br>&gt;&gt;&gt; print(my_set)<br>&gt;&gt;&gt; print(my_frozenset)</pre><pre>&gt;&gt;&gt; my_set.remove(2.7)<br>&gt;&gt;&gt; my_set.pop()<br>&gt;&gt;&gt; print(my_set)</pre><pre># some additional operations<br>&gt;&gt;&gt; first = {1, 2, 3, 4, 5, 6}<br>&gt;&gt;&gt; second = {4, 5, 6, 7, 8, 9}<br>&gt;&gt;&gt; print(first | second)<br>&gt;&gt;&gt; print(first &amp; second)<br>&gt;&gt;&gt; print(first - second)<br>&gt;&gt;&gt; print(second - first)<br>&gt;&gt;&gt; print(first ^ second)</pre><pre>{&#39;3.6&#39;, 2.7, 6}<br>frozenset({&#39;2.7&#39;, &#39;Python&#39;})<br>{6}<br>{1, 2, 3, 4, 5, 6, 7, 8, 9}<br>{4, 5, 6}<br>{1, 2, 3}<br>{8, 9, 7}<br>{1, 2, 3, 7, 8, 9}</pre><h4>So, what are the operations that can be performed on mutable and immutable objects in Python?</h4><p>Please check the answer in the notebook attached below.</p><h3>Conditional statements, loops</h3><h4>if, elif, else</h4><p>Python uses <strong>if</strong> statements to run code if a certain condition holds <em>True</em>, otherwise they aren’t.</p><p><strong>NOTE</strong>: Python uses <strong>indentation</strong> (white space at the beginning of a line) to delimit blocks of code. Other languages, such as C, use curly braces to accomplish this, but in Python, indentation is mandatory; programs won’t work without it.</p><p><strong>To perform more complex checks</strong>, <em>if</em> statements can be <strong>nested</strong>, one inside the other. This means that the inner <em>if</em> statement is the statement part of the outer one.</p><p>An <strong>else</strong> statement follows an <em>if</em> statement, and contains code that is called when the <em>if</em> statement evaluates to <em>False</em>.</p><p>The <strong>elif</strong> (short for else if) statement is a shortcut to use when <strong>chaining if and else statements</strong>. A series of <em>if elif</em> statements can have a final else block, which is called if none of the <em>if</em> or <em>elif</em> expressions is <em>True</em>.</p><pre>&gt;&gt;&gt; num = int(input(&quot;Enter a number from 0 to 9: &quot;))<br>&gt;&gt;&gt; if num == 3:<br>        print(&quot;You got 3&quot;)<br>    elif num == 6:<br>        print(&quot;Number is 6&quot;)<br>    elif num == 9:<br>        print(&quot;Looks like 9&quot;)<br>    else:<br>        print(&quot;`If you knew the magnificence of the three, six and nine, you would have a key to the universe.` ~ Tesla&quot;)</pre><pre>Enter a number from 0 to 9: 5<br>`If you knew the magnificence of the three, six and nine, you would have a key to the universe.` ~ Tesla</pre><h4>for</h4><p>The <strong>for</strong> loop is commonly used to repeat some code a certain number of times on an object known as <strong>iterator</strong>. This is done by combining for loops with <strong>range</strong> objects.</p><p>The function range by default starts counting from 0 and goes up to the n-th value i.e., till (n-1). Its first parameter is the starting point, second one is the ending point (n-th value), and the optional third is the step value.</p><pre>&gt;&gt;&gt; for i in range(5):<br>        if i &lt; 3:<br>            print(&quot;hello!&quot;)<br>        else:<br>            print(&quot;world&quot;)<br>        <br>&gt;&gt;&gt; print(&quot;-----------------&quot;)<br>        <br>&gt;&gt;&gt; for i in range(2,12,3):<br>        print(i)</pre><pre>hello!<br>hello!<br>hello!<br>world<br>world<br>-----------------<br>2<br>5<br>8<br>11</pre><h4>Two questions for you guys</h4><ol><li>Ever wondered why people use <em>i</em> in for loop?</li><li>What is the difference between <strong>range(x)</strong> and <strong>list(range(x))</strong>?</li></ol><pre>&gt;&gt;&gt; print(list(range(5)))<br>&gt;&gt;&gt; print(range(5))</pre><pre>[0, 1, 2, 3, 4]<br>range(0, 5)</pre><h4>Answer</h4><ol><li>The i stands for the item to be accessed from any iterable or range object.</li><li>When you execute <em>?range</em>, it will say that range returns an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step <strong>without assigning indexes to the values</strong>. Rather, it generates only one number at a time, relying on a <strong>for</strong> loop to request for the next item in the range to be seen. However, <strong>list(range()) does assign indices</strong> and hence allows you to see the full sequence of the numbers immediately, without the assistance of a <em>for</em> loop. <strong><em>By the way, this happens only in Python 3.</em></strong></li></ol><h4>while</h4><p>An <strong>if</strong> statement is <strong>run once</strong> if its condition evaluates to <em>True</em>. A <strong>while</strong> statement is similar, except that it can be <strong>run more than once</strong>. The statements inside it are repeatedly executed, as long as the condition holds <em>True</em>. Once it evaluates to False, the next section of code is executed.</p><p>The <strong>infinite loop</strong> is a special kind of while loop where the condition is always True and never stops iterating.</p><p>To end a while loop prematurely, the <strong>break</strong> statement can be used inside the loop.</p><p>When a <strong>continue</strong> statement is encountered, the code flow jumps back to the top of the loop, rather than stopping it completely (which is the job of <em>break)</em>. Basically it <strong>stops the current iteration </strong>and continues with the next one.</p><pre>&gt;&gt;&gt; import time<br>&gt;&gt;&gt; mewtwo_cp = 30<br>&gt;&gt;&gt; umbreon_dark_pulse = 3<br>&gt;&gt;&gt; fight = True<br>&gt;&gt;&gt; print(&quot;You attacked Mewtwo! CP left: {}&quot;.format(mewtwo_cp))</pre><pre>&gt;&gt;&gt; while fight:<br>        print(&quot;Umbreon used Dark Pulse!\n&quot;)<br>        mewtwo_cp = mewtwo_cp - umbreon_dark_pulse<br>        <br>        if mewtwo_cp == 15:<br>            print(&quot;He&#39;s halfway dead!&quot;) <br>            continue<br>        elif mewtwo_cp == 9: <br>            print(&quot;Take him down!&quot;)<br>            continue<br>        elif mewtwo_cp == 3:<br>            print(&quot;Now&#39;s your chance&quot;) <br>            continue<br>        <br>        if mewtwo_cp &lt;= 0:<br>            print(&quot;Dead!&quot;)<br>            break<br>        <br>        print(&quot;Mewtwo CP left: {}&quot;.format(mewtwo_cp))<br>        time.sleep(1)<br>    <br>&gt;&gt;&gt; print(&quot;Congrats! Your Umbreon won.&quot;)</pre><pre>You attacked Mewtwo! CP left: 30<br>Umbreon used Dark Pulse!<br><br>Mewtwo CP left: 27<br>Umbreon used Dark Pulse!<br><br>Mewtwo CP left: 24<br>Umbreon used Dark Pulse!<br><br>Mewtwo CP left: 21<br>Umbreon used Dark Pulse!<br><br>Mewtwo CP left: 18<br>Umbreon used Dark Pulse!<br><br>He&#39;s halfway dead!<br>Umbreon used Dark Pulse!<br><br>Mewtwo CP left: 12<br>Umbreon used Dark Pulse!<br><br>Take him down!<br>Umbreon used Dark Pulse!<br><br>Mewtwo CP left: 6<br>Umbreon used Dark Pulse!<br><br>Now&#39;s your chance<br>Umbreon used Dark Pulse!<br><br>Dead!<br>Congrats! Your Umbreon won.</pre><h3>File I/O</h3><p>Python can be used to <strong>read</strong> and <strong>write</strong> the contents of files. Text files are the easiest to manipulate.</p><h4>open</h4><p>Before a file can be edited, it must be <em>opened</em>, using the <strong>open</strong> function. The <strong>argument</strong> of the open function is the <em>path to the file</em>. If the file is in the current working directory of the program, you can specify only its name.</p><h4>mode</h4><p>There are <strong>mode</strong> used to open a file by applying a <em>second argument</em> to the open function.</p><ul><li>“r” means open in <strong>read</strong> mode, which is the default.</li><li>“w” means <strong>write</strong> mode, for rewriting the contents of a file.</li><li>“a” means <strong>append</strong> mode, for adding new content to the end of the file.</li><li>“b” means <strong>binary</strong> mode, which is used for non-text files (such as image and sound files).</li></ul><h4>read</h4><p>The contents of a file that has been opened in text mode can be read using the <strong>read</strong> method. To <strong>read only a certain amount of a file, you can provide a number as an argument</strong> to the read function. This determines the <strong>number of bytes</strong> that should be read.</p><p>After all contents in a file have been read, any attempts to read further from that file will return an <em>empty string</em>, because you are trying to read <strong>from the end of the file</strong>.</p><p>To retrieve <strong>each line</strong> in a file, you can use the <strong>readlines</strong> method to <em>return a list in which each element is a line in the file</em>.</p><p><strong>NOTE</strong>: There is a <strong>readline</strong> and a <strong>readlines</strong> method. <em>readline()</em> reads one line character at a time, <em>readlines()</em> reads in the whole file at once and splits it by line.</p><h4>write</h4><p>To write to files we use the <strong>write</strong> method, which writes a string to the file. The “w” mode will <em>create a file, if it does not already exist</em>. When a file is opened in write mode, the file’s <strong>existing content is deleted</strong>. The write method <strong>returns the number of bytes</strong> written to a file, if successful.</p><p><strong>NOTE</strong>: If you need to write anything other than string on a file, it has to be converted to a string first.</p><h4>close</h4><p>Once a file has been opened and used, it should be closed which is done with the <strong>close</strong> method of the file object.</p><h4>Alternative approach of file access</h4><p>An alternative way of doing it is using <strong>with</strong> statements. This creates a temporary variable (often called <strong><em>f</em></strong><em>), which is only accessible in the indented block of the with statement.</em><strong> The file is automatically closed</strong> at the end of the with statement, even if exceptions occur within it.</p><pre>&gt;&gt;&gt; file_name = open(&quot;def_NN.txt&quot;, &quot;r&quot;)<br>&gt;&gt;&gt; print(&quot;------- Reading the content -------\n&quot;)<br>&gt;&gt;&gt; file_content = file_name.read()<br>&gt;&gt;&gt; print(file_content)<br>&gt;&gt;&gt; print(&quot;------- Re-reading -------&quot;)<br>&gt;&gt;&gt; print(file_name.read())<br>&gt;&gt;&gt; print(&quot;------- Finished! --------\n&quot;)<br>&gt;&gt;&gt; print(&quot;------- Closing the file -------&quot;)<br>&gt;&gt;&gt; file_name.close()<br># try readlines</pre><pre>------- Reading the content -------</pre><pre>What is Neural Network?<br>A neural network is a processing unit that is capable to store knowledge and apply it to make predictions. A neural network mimics the brain in a way where the network acquires knowledge from its environment through a learning process. Then, intervention connection strengths known as synaptic weights are used to store the acquired knowledge. In the learning process, the synaptic weights of the network are modified in such a way so as to attain the desired objective.</pre><pre>A neural network architecture comprises of 3 types of layers:</pre><pre>Input Layer: The first layer in the network which receives input (training observations) and passed to the next hidden layer(s)<br>Hidden Layer: The intermediate processing layer(s) which perform specific tasks on the incoming data and pass on the output generated by them to the next output layer<br>Output Layer: The final layer of the network which generates the desired output<br>Each of these layers are composed of Perceptrons which is analogous to the neuron of the our nervous system.</pre><pre>------- Re-reading -------</pre><pre>------- Finished! --------</pre><pre>------- Closing the file -------<br>&gt;&gt;&gt; file_name = open(&quot;joker.txt&quot;, &quot;r&quot;)<br>&gt;&gt;&gt; print(&quot;------- Reading initial contents ------- \n&quot;)<br>&gt;&gt;&gt; print(file_name.read())<br>&gt;&gt;&gt; print(&quot;------- Finished ------- \n&quot;)<br>&gt;&gt;&gt; file_name.close()<br>&gt;&gt;&gt; file_name = open(&quot;joker.txt&quot;, &quot;w&quot;)<br>&gt;&gt;&gt; amount_written = file_name.write(&quot;I believe whatever doesn&#39;t kill you simply makes you...stranger.&quot;)<br>&gt;&gt;&gt; print(&quot;Amount of text written: {}\n&quot;.format(amount_written))<br>&gt;&gt;&gt; file_name.close()<br>&gt;&gt;&gt; file_name = open(&quot;joker.txt&quot;, &quot;r&quot;)<br>&gt;&gt;&gt; print(&quot;------- Reading new contents ------- \n&quot;)<br>&gt;&gt;&gt; print(file_name.read())<br>&gt;&gt;&gt; print(&quot;\n ------- Finished -------&quot;)<br>&gt;&gt;&gt; file_name.close()<br>------- Reading initial contents -------</pre><pre>You see, in their last moment, people show you who they really are.<br>------- Finished -------</pre><pre>Amount of text written: 64</pre><pre>------- Reading new contents -------</pre><pre>I believe whatever doesn&#39;t kill you simply makes you...stranger.</pre><pre>------- Finished -------<br># alternative approach<br>&gt;&gt;&gt; with open(&quot;def_NN.txt&quot;) as f:<br>        print(f.read())</pre><h3>Exception Handling</h3><h4>Exception</h4><p><strong>Exception</strong> occur when something goes wrong due to incorrect code syntax or logic or input. When an exception occurs, the program immediately stops and doesn’t executes any lines further.</p><p><em>Different exceptions are raised for different reasons.</em> Some common exceptions are listed below:</p><ul><li><strong>ImportError</strong>: an import fails</li><li><strong>IndexError</strong>: a list is indexed with an out-of-range number</li><li><strong>NameError</strong>: an unknown variable is used</li><li><strong>SyntaxError</strong>: the code can’t be parsed or processed properly</li><li><strong>TypeError</strong>: a function is called on a value of an inappropriate type</li><li><strong>ValueError</strong>: a function is called on a value of the correct type, but with an inappropriate value</li></ul><p>Third-party libraries and modules define their own exceptions. Learn more about built-in exceptions <a href="https://docs.python.org/3.7/library/exceptions.html">here</a></p><p>Here are some examples of different built-in exceptions.</p><pre>&gt;&gt;&gt; list=[1,2,3] <br>&gt;&gt;&gt; print(list[3])<br>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>IndexError: list index out of range <br><br>&gt;&gt;&gt; printf(a)<br>File &quot;&lt;stdin&gt;&quot;, line 1 <br>printf a <br>    ^ <br>SyntaxError: invalid syntax<br><br>&gt;&gt;&gt; print(a)<br>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>NameError: name &#39;a&#39; is not defined <br><br>&gt;&gt;&gt; import tk <br>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>ImportError: No module named tk <br><br>&gt;&gt;&gt; a=2+&quot;hello&quot;<br>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>TypeError: unsupported operand type(s) for +: &#39;int&#39; and &#39;str&#39; <br><br>&gt;&gt;&gt; list.remove(0) <br>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>ValueError: list.remove(x): x not in list</pre><h4>Exception Handling</h4><p>To handle exceptions and call code when an exception occurs, we have to use a <strong>try/except</strong> statement.</p><h4>try-except</h4><p>The <strong>try</strong> block contains code that might throw an exception. If that exception occurs, the code in the try block stops executing, and the code in the <strong>except </strong>block is run. If no error occurs, the code in the except block doesn’t run.</p><p>A try statement can have multiple different except blocks to handle different exceptions. <em>Multiple exceptions can also be put into a single except block using </em><strong><em>parentheses</em></strong><em>,</em> to have the except block handle all of them.</p><p>An except statement without any exception specified will catch all errors. <strong>However, this kind of coding should be avoided.</strong> If you do this, you are going against the zen of Python.</p><p>Exception handling is particularly useful when</p><ul><li>dealing with user input</li><li>sending stuff over network or saving large amounts of data, since issues happening with hardware like losing power or signal problems can happen</li></ul><pre>&gt;&gt;&gt; try:<br>        variable = 10<br>        print(variable + &quot;hello&quot;)<br>        num1 = 7<br>        num2 = 0<br>        print(num1 / num2)<br>        print(&quot;Done calculation&quot;)<br>    except ZeroDivisionError:<br>        print(&quot;An error occurred due to zero division&quot;)<br>    except (ValueError, TypeError):<br>        print(&quot;ERROR!&quot;)</pre><pre>ERROR!</pre><h4>raise</h4><p>We can use <strong>raise</strong> to throw an exception <strong>if a condition occurs</strong>. The statement can be complemented with a custom exception.</p><pre>&gt;&gt;&gt; x = 12<br>&gt;&gt;&gt; if x &gt; 5:<br>        raise Exception(&#39;x should not exceed 5. The value of x was: {}&#39;.format(x))</pre><pre>---------------------------------------------------------------------------<br>Exception                                 Traceback (most recent call last)<br>&lt;ipython-input-5-b2de8492a496&gt; in &lt;module&gt;<br><strong>      1</strong> x = 12<br><strong>      2</strong> if x &gt; 5:<br>----&gt; 3     raise Exception(&#39;x should not exceed 5. The value of x was: {}&#39;.format(x))<br><br>Exception: x should not exceed 5. The value of x was: 12</pre><h4>else and finally</h4><p>Here using the else statement, you can instruct a program to execute a certain block of code <strong>only in the absence of exceptions</strong>.</p><p>To ensure some code runs no matter what errors occur, you can use a <strong>finally</strong> statement. The finally statement is placed at the bottom of a try/except statement and else statement, if any. This diagram explains the concept of try-except-else-finally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEPpZX7606TlYlQ93t5Dug.png" /></figure><pre>&gt;&gt;&gt; try:<br>        num_1 = 2<br>        num_2 = 5<br>        print(num_1/num_2)<br>    except ZeroDivisionError as error:<br>        print(error)<br>    else:<br>        try:<br>            with open(&#39;joker.txt&#39;) as file:<br>                read_data = file.readline()<br>                print(read_data)<br>        except FileNotFoundError as fnf_error:<br>            print(fnf_error)<br>    finally:<br>        print(&#39;Getting printed irrespective of any exceptions.&#39;)</pre><pre>0.4<br>I believe whatever doesn&#39;t kill you simply makes you...stranger.<br>Getting printed irrespective of any exceptions.</pre><pre>&gt;&gt;&gt; try:<br>        print(1)<br>        print(10 / 0)<br>    except ZeroDivisionError:<br>        print(error)<br>    finally:<br>        print(&quot;This is executed last!&quot;)</pre><pre>1<br>This is executed last!</pre><pre>---------------------------------------------------------------------------<br>ZeroDivisionError                         Traceback (most recent call last)<br>&lt;ipython-input-7-b26411555290&gt; in &lt;module&gt;<br><strong>      2</strong>     print(1)<br>----&gt; 3     print(10 / 0)<br><strong>      4</strong> except ZeroDivisionError:<br><br>ZeroDivisionError: division by zero<br><br>During handling of the above exception, another exception occurred:<br><br>NameError                                 Traceback (most recent call last)<br>&lt;ipython-input-7-b26411555290&gt; in &lt;module&gt;<br><strong>      3</strong>     print(10 / 0)<br><strong>      4</strong> except ZeroDivisionError:<br>----&gt; 5     print(error)<br><strong>      6</strong> finally:<br><strong>      7</strong>     print(&quot;This is executed last!&quot;)<br><br>NameError: name &#39;error&#39; is not defined</pre><h4><strong>Why the exceptions messages are printed at the end of the output, not between “1” and “This is executed last”?</strong></h4><p>While catching the error for <em>print(10 / 0)</em> the system found another exception in the <strong>except</strong> block, the undeclared variable <em>error</em> raising <strong>NameError</strong> exception. So nothing was printed. This inner <em>NameError</em> exception was uncaught by program and can only printed after finally block.</p><h4>Assesrtion</h4><p>An <strong>assertion is a sanity-check</strong> where an expression is tested, and if the result comes up false, an exception is raised. When it encounters an assert statement, Python evaluates the accompanying expression, which is expected to be true. If the expression is false, Python raises an <strong>AssertionError </strong>exception.</p><p>AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, this type of exception will terminate the program.</p><p><strong>But what makes assertion different from try/except?</strong></p><p>An assertion would stop the program from running (because you should fix that error or the program is useless), but an exception would let the program continue running (if you use else or finally). In other words, <strong>exceptions address the robustness of your application</strong> while <strong>assertions address its correctness</strong>.</p><p>Assertions should be used to check something that <strong>should never happen</strong> while an exception should be used to check something that <strong>might happen</strong>(something in which you don’t have control like user input).</p><p><strong>NOTE</strong>: The rule is that use <strong>assertions</strong> when you are trying to <strong>catch your own errors</strong> (functions or data that are internal to your system), and <strong>exceptions </strong>when trying to <strong>catch other people’s errors</strong>.</p><pre>&gt;&gt;&gt; def KelvinToFahrenheit(temp):<br>        assert (temp &gt;= 0),&quot;Colder than absolute zero? Go back to school. -_-&quot;<br>        return ((temp - 273)*1.8) + 32</pre><pre>&gt;&gt;&gt; print(KelvinToFahrenheit(273))<br>&gt;&gt;&gt; print(KelvinToFahrenheit(-5))<br>&gt;&gt;&gt; print(KelvinToFahrenheit(373))</pre><pre>32.0</pre><pre>---------------------------------------------------------------------------<br>AssertionError                            Traceback (most recent call last)<br>&lt;ipython-input-8-832b1596a334&gt; in &lt;module&gt;<br><strong>      4</strong> <br><strong>      5</strong> print(KelvinToFahrenheit(273))<br>----&gt; 6 print(KelvinToFahrenheit(-5))<br><strong>      7</strong> print(KelvinToFahrenheit(373))<br><br>&lt;ipython-input-8-832b1596a334&gt; in KelvinToFahrenheit(temp)<br><strong>      1</strong> def KelvinToFahrenheit(temp):<br>----&gt; 2     assert (temp &gt;= 0),&quot;Colder than absolute zero? Go back to school. -_-&quot;<br><strong>      3</strong>     return ((temp - 273)*1.8) + 32<br><strong>      4</strong> <br><strong>      5</strong> print(KelvinToFahrenheit(273))<br><br>AssertionError: Colder than absolute zero? Go back to school. -_-</pre><p>As mentioned in the previous article, I will be attaching the notebook at the end. So yeah, we have reached the end of this article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/864eac07cd056b0cd271517be7898cb5/href">https://medium.com/media/864eac07cd056b0cd271517be7898cb5/href</a></iframe><p>I hope you guys have enjoyed this article. For any questions or doubts, please comment below and share your feedback on the notebook. Stay tuned for the part 2. Till then, keep coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=affd908a2a49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick guide to Python - Notebook | Beginners]]></title>
            <link>https://tamoghnasaha-22.medium.com/a-quick-guide-to-python-notebook-beginners-6bbe3e2bb762?source=rss-13abc86e42f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bbe3e2bb762</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tamoghna Saha]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 14:58:09 GMT</pubDate>
            <atom:updated>2019-08-03T12:50:14.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Qh90O8nmW-6RZ1aYVL_ZQ.png" /></figure><p>I have been working with Python for the past 2 years. There are lots of tutorials available online that covers Python, but sometimes it doesn’t cover the most crucial part which needs an answer - <br>“<em>Why do we need to use Python?</em>”<br>“<em>Is it worth learning it?</em>”.<br>Since you have clicked this article, and reading till this point, I can assume that you are interested in Python or maybe you do know something about it but you need a quick recap. I am here to guide you not only with the syntax but also to tell some concepts, tips and tricks associated with it.</p><p>Table of Content:</p><ul><li>Numerical and Boolean Operations</li><li>Variable and Object</li><li>Data Type and Type Conversion</li><li>Importing Python Modules and standard libraries</li><li>Python Built-in Functions and keywords</li><li>String operations and formatting</li><li>Useful Pythonic Functions</li><li>User Input Function</li><li>User-Defined Function</li><li>Scope of a Variable</li><li>Additional Read</li></ul><h3>What is Python?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*89O4Cr0w6vGn67z8myuzww.png" /></figure><p>It is a general-purpose, high-level, interpreted, dynamic scripting language.</p><ul><li><strong>General-Purpose</strong> -&gt; designed to be used for writing software in the widest variety of application domains</li><li><strong>High-level</strong> -&gt; designed to be more or less independent of a particular type of computer, human-readable friendly</li><li><strong>Interpreted</strong> -&gt; designed to execute instructions of a program directly, without previously compiling a program into machine-language instructions</li><li><strong>Scripting</strong> -&gt; languages which are interpreted rather than compiled</li></ul><h3>But, what is the difference between an interpreter and a compiler?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/befee3a8b37503d2b3957bba07d8eff4/href">https://medium.com/media/befee3a8b37503d2b3957bba07d8eff4/href</a></iframe><h3>Currently, there are two versions of Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aW0qsCL6OYTd66n1bkMeMw.png" /></figure><h3>Why do we need Python?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*FVNc5sE8cWIP0uluDUDluQ.jpeg" /></figure><ul><li><strong>Simple syntax, readable, reusable and maintainable code</strong></li><li><strong>Multiple Programming Paradigms</strong> such as Object-oriented, structured, functional Paradigms and feature of automatic memory management</li><li><strong>Compatible</strong> with Major Platforms and Systems, many <strong>open-source framework available</strong> which boosts developer’s productivity</li><li><strong>Robust Standard Library</strong> and supporting wide range of external libraries</li><li>Easier to perform coding and testing simultaneously by adopting <strong>test driven development (TDD)</strong> approach</li></ul><h3>That’s okay. But where do I use it?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QgdIskGE1uATZwHGN7-zQ.jpeg" /></figure><h3>Who uses Python anyway?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*A1QQVOnxzRsaS5QGOxKabg.png" /></figure><h3>Cool. I guess we are good to go!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*S4-VtMp3nEazPz95NDFr0Q.gif" /></figure><pre># This is how you comment a code in Python!</pre><pre># Let’s start with the famous code.</pre><pre>&gt;&gt;&gt; print(‘Hello World’)</pre><pre>Hello World</pre><pre># a collection of 20 software principles that influences the design of Python Programming Language, of which 19 were written down</pre><pre>&gt;&gt;&gt; import this</pre><pre>The Zen of Python, by Tim Peters<br><br>Beautiful is better than ugly.<br>Explicit is better than implicit.<br>Simple is better than complex.<br>Complex is better than complicated.<br>Flat is better than nested.<br>Sparse is better than dense.<br>Readability counts.<br>Special cases aren&#39;t special enough to break the rules.<br>Although practicality beats purity.<br>Errors should never pass silently.<br>Unless explicitly silenced.<br>In the face of ambiguity, refuse the temptation to guess.<br>There should be one-- and preferably only one --obvious way to do it.<br>Although that way may not be obvious at first unless you&#39;re Dutch.<br>Now is better than never.<br>Although never is often better than *right* now.<br>If the implementation is hard to explain, it&#39;s a bad idea.<br>If the implementation is easy to explain, it may be a good idea.<br>Namespaces are one honking great idea -- let&#39;s do more of those!</pre><h3>Numerical and Boolean Operations</h3><pre>## some basic mathematical operations , I am not showing. You do it. But see this.</pre><pre>&gt;&gt;&gt; print(25/4)<br>6.25<br>&gt;&gt;&gt; print(25//4)<br>&gt;&gt;&gt; print(25%4)<br>6<br>1</pre><pre>&gt;&gt;&gt; x = 3<br>&gt;&gt;&gt; x *= 3 # in-place operator<br>&gt;&gt;&gt; print(x)<br>9</pre><pre>&gt;&gt;&gt; y = “python”<br>&gt;&gt;&gt; y += “3”<br>&gt;&gt;&gt; print(y)<br>python3</pre><p>In Python 3, / is called <strong>floating point division</strong> and // is <strong>floor division</strong>. <strong>But In Python 2.7, it will return the base integer (6 in this case) in both the divisions</strong>.</p><p>Let’s look at some <strong>Boolean operations</strong>.</p><pre>&gt;&gt;&gt; print(“Easy ones!\n — — — — -”)<br>&gt;&gt;&gt; print(2 == 3)<br>&gt;&gt;&gt; print(6 != 7)<br>&gt;&gt;&gt; print(9 is not “nine”)<br>&gt;&gt;&gt; print(5 &gt; 3)<br>&gt;&gt;&gt; print(“ — — — — -”)<br>&gt;&gt;&gt; print(“Tricky ones!\n — — — — -”)<br>&gt;&gt;&gt; print(6 &lt; 6.0)<br>&gt;&gt;&gt; print((3 * 0.1) == 0.3)<br>&gt;&gt;&gt; print((3 * 0.1) == (3/10))</pre><pre>Easy ones!<br>---------<br>False<br>True<br>True<br>True<br>---------<br>Tricky ones!<br>---------<br>False<br>False<br>False</pre><p>Floating point numbers are represented in computer hardware in <strong>base 2</strong>. Floating point numbers are usually represented in <strong>base 10</strong>. <em>But most decimal fractions cannot be represented exactly as binary fractions.</em> As a result, the decimal floating-point numbers you enter are only <strong>approximated</strong> to the binary floating-point numbers actually stored in the machine.</p><p>No matter how many base 2 digits you are willing to use, the decimal value 0.1 cannot be represented <strong>exactly</strong> as a base 2 fraction.</p><p>Many users are not aware of the approximation because of the way values are displayed. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display</p><pre>&gt;&gt;&gt; 0.1<br>0.1000000000000000055511151231257827021181583404541015625</pre><p>But this is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead</p><pre>&gt;&gt;&gt; 0.1<br>0.1</pre><p>So, even though printed result looks like the exact value of 1/10, the <em>actual stored value is the </em><strong><em>nearest representable binary fraction</em></strong>.</p><p>Note that this is in the <em>very nature of binary floating-point</em>: this is <strong>NOT a bug in Python</strong>. You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic. <strong>The errors in Python float operations are inherited from the floating-point hardware.</strong></p><h3>Variables and Objects</h3><p>Few things about variables:</p><ul><li>Variables do not have a defined type at compile time.</li><li>Variables can reference any type of object!</li><li>Variable type can change in run-time.</li></ul><p>Type checking is performed at run-time, and hence <strong>dynamic languages are slower than static languages</strong>.</p><p><strong>Everything in Python is an Object!</strong> object is the base type for every Python Object. Objects can be:</p><ul><li><strong>Mutable</strong>: value can be changed. [list, set, dictionaries]</li><li><strong>Immutable</strong>: value is unchangeable. [number, string, frozenset, tuple]</li></ul><p>Object mutability is defined by its <strong>type</strong>. <strong>They Are Never Explicitly Destroyed!</strong> Allocation and deletion is done by the interpreter.</p><p>The most commonly used methods of constructing a multi-word variable name are as follows:</p><ul><li><strong>Camel Case</strong>: Second and subsequent words are capitalized, to make word boundaries easier to see.Example: numberOfCollegeGraduates</li><li><strong>Pascal Case</strong>: Identical to Camel Case, except the first word is also capitalized.Example: NumberOfCollegeGraduates</li><li><strong>Snake Case</strong>: Words are separated by underscores.Example: number_of_college_graduates</li></ul><pre># the correct ways to declare variables <br>&gt;&gt;&gt; my_variable = “is my variable, None of your variable” # even this is right</pre><pre># definitely the wrong way to declare variables<br>&gt;&gt;&gt; 1234_get_on_the_dance_floor = &quot;really?&quot; # this is wrong. see what error you will get</pre><h3>Data Type and Type Conversion</h3><pre># data types<br>&gt;&gt;&gt; print(type(“hello”))<br>&gt;&gt;&gt; print(type(True))<br>&gt;&gt;&gt; print(type(999.666))<br>&gt;&gt;&gt; print(type((-1+0j)))</pre><pre>&lt;class &#39;str&#39;&gt;<br>&lt;class &#39;bool&#39;&gt;<br>&lt;class &#39;float&#39;&gt;<br>&lt;class &#39;complex&#39;&gt;</pre><pre># type conversion</pre><pre>&gt;&gt;&gt; print(float(6))<br>&gt;&gt;&gt; print(&quot;We are using Python &quot; + str(3))<br>&gt;&gt;&gt; print(int(“3”) + int(“6”))</pre><pre>6.0<br>We are using Python 3<br>9</pre><h3>Importing Python Modules and standard libraries</h3><p>There are several ways to import standard and open-source external libraries to your programming environment:</p><pre># 1. By directly import<br>&gt;&gt;&gt; import math<br>&gt;&gt;&gt; print(math.sin(45))<br>&gt;&gt;&gt; print(&quot;=&quot;*50)</pre><pre># 2. By importing everything<br>&gt;&gt;&gt; from math import *</pre><pre># 3. Using alias<br>&gt;&gt;&gt; import math as m</pre><pre># 4. By specifically importing its functions<br>&gt;&gt;&gt; from math import sin, log<br>&gt;&gt;&gt; print(sin(45))<br>&gt;&gt;&gt; print(log(5))</pre><pre>0.8509035245341184<br>==================================================<br>0.8509035245341184<br>1.6094379124341003</pre><h3>Some of the default modules in Python</h3><ul><li><strong>sys</strong> -&gt; System-specific parameters and functions.</li><li><strong>io</strong> -&gt; Core tools for working with streams.</li><li><strong>os</strong> -&gt; Miscellaneous operating system interfaces.</li><li><strong>threading</strong> -&gt; Higher-level threading interface.</li><li><strong>multiprocess</strong> -&gt; Process — based “threading“ interface.</li><li><strong>socket</strong> -&gt; Low — level networking interface.</li><li><strong>asyncio</strong> -&gt; Asynchronous I/O, event loop, co-routines and tasks.</li><li><strong>cmd</strong> -&gt; Support for line — oriented command interpreters.</li><li><strong>datetime</strong> -&gt; Basic date and time types.</li><li><strong>time</strong> -&gt; Time access and conversions.</li><li><strong>heapq</strong> -&gt; Heap queue algorithm.</li><li><strong>queue</strong> -&gt; A synchronized queue class.</li><li><strong>pathlib</strong> -&gt; Object — oriented filesystem paths</li><li><strong>math</strong> -&gt; Mathematical functions</li><li><strong>sqlite3</strong> -&gt; DB — API interface for SQLite3 Databases.</li></ul><h3>Python Built-in Functions and keywords</h3><p><strong>Built-in functions</strong> are core functions, provided by the Python Interpreter. These functions are <strong>implemented in C</strong> and hence are capable of using and manipulating Python objects at memory level, with increased performance.</p><p><strong>Keywords</strong> are basically reserved words. It can’t be used as variable’s names.</p><pre># just wrote these code to display the list properly in notebook</pre><pre># built-in functions<br>&gt;&gt;&gt; builtin_functions_list = dir(__builtins__)<br>&gt;&gt;&gt; builtin_functions_data = np.array(builtin_functions_list)<br>&gt;&gt;&gt; shape = ((len(builtin_functions_list)//4),4)<br>&gt;&gt;&gt; print(tabulate(builtin_functions_data.reshape(shape), tablefmt=&#39;orgtbl&#39;))</pre><pre>| ArithmeticError      | AssertionError         | AttributeError     | BaseException        | BlockingIOError        | BrokenPipeError        | BufferError          | BytesWarning<br>| ChildProcessError    | ConnectionAbortedError | ConnectionError    | ConnectionRefusedError<br>| ConnectionResetError | DeprecationWarning     | EOFError           | Ellipsis             | EnvironmentError       | Exception              | False                | FileExistsError           <br>| FileNotFoundError    | FloatingPointError     | FutureWarning      | GeneratorExit        | IOError                | ImportError            | ImportWarning        | IndentationError       | IndexError           | InterruptedError     | IsADirectoryError      | KeyError                  <br>| KeyboardInterrupt    | LookupError            | MemoryError        | ModuleNotFoundError  | NameError              | None                  | NotADirectoryError   | NotImplemented         <br>| NotImplementedError  | OSError                | OverflowError      | PendingDeprecationWarning<br>| PermissionError      | ProcessLookupError     | RecursionError     | ReferenceError       | ResourceWarning        | RuntimeError           | RuntimeWarning       | StopAsyncIteration     | StopIteration        | SyntaxError          | SyntaxWarning          | SystemError               <br>| SystemExit           | TabError               | TimeoutError       | True                 | TypeError              |UnboundLocalError      | UnicodeDecodeError   | UnicodeEncodeError     | UnicodeError         | UnicodeTranslateError| UnicodeWarning         | UserWarning               <br>| ValueError           | Warning                |ZeroDivisionError  | __IPYTHON__          | __build_class__        | __debug__              | __doc__              | __import__             | __loader__           | __name__             | __package__            | __spec__                  <br>| abs                  | all                    | any                | ascii                | bin                    | bool                   | bytearray            | bytes                  | callable             | chr                  | classmethod            | compile                   <br>| complex              | copyright              | credits            | delattr              | dict                   | dir                    | display              | divmod                 | enumerate            | eval                 | exec                   | filter                    <br>| float                | format                 | frozenset          | get_ipython          | getattr                | globals                | hasattr              | hash                   | help                 | hex                  | id                     | input                     <br>| int                  | isinstance             | issubclass         | iter                 | len                    | license                | list                 | locals                 | map                  | max                  | memoryview             | min                       <br>| next                 | object                 | oct                | open                 | ord                    | pow                    | print                | property               | range                | repr                 | reversed               | round                     <br>| set                  | setattr                | slice           | sorted               | staticmethod           | str                    | sum                  | super                  | tuple                | type                 | vars                   | zip                </pre><pre>### keywords<br>&gt;&gt;&gt; keywords_list = keyword.kwlist<br>&gt;&gt;&gt; keywords_data = np.array(keywords_list)<br>&gt;&gt;&gt; shape = ((len(keywords_list)//3),3)<br>&gt;&gt;&gt; print(tabulate(keywords_data.reshape(shape), tablefmt=&#39;orgtbl&#39;))</pre><pre>| False | None   | True     |<br>| and   | as     | assert   |<br>| break | class  | continue |<br>| def   | del    | elif     |<br>| else  | except | finally  |<br>| for   | from   | global   |<br>| if    | import | in       |<br>| is    | lambda | nonlocal |<br>| not   | or     | pass     |<br>| raise | return | try      |<br>| while | with   | yield    |</pre><h3>String operations and formatting</h3><pre>## Concatenation</pre><pre>&gt;&gt;&gt; str_var_1 = &quot;concatenation&quot;<br>&gt;&gt;&gt; print(&quot;This is &quot; + str_var_1 + &quot; of string&quot;)<br>&gt;&gt;&gt; print(3*&quot;3&quot;)<br>&gt;&gt;&gt; print(&quot;python&quot;*3.7)<br>&gt;&gt;&gt; print(&quot;This will not print&quot;)</pre><pre>This is concatenation of string<br>333</pre><pre>---------------------------------------------------------------------------<br>TypeError                                 Traceback (most recent call last)<br>&lt;ipython-input-15-6eae2c361731&gt; in &lt;module&gt;()<br><strong>      6</strong> print(3*&quot;3&quot;)<br><strong>      7</strong> <br>----&gt; 8 print(&quot;python&quot;*3.7)<br><strong>      9</strong> <br><strong>     10</strong> print(&quot;This will not print&quot;)<br><br>TypeError: can&#39;t multiply sequence by non-int of type &#39;float&#39;</pre><pre><br>## string formatting</pre><pre># It provides a powerful way of embedding non-strings with strings</pre><pre>&gt;&gt;&gt; py_ver = &quot;We are using Python version {}.{}.x&quot;.format(3,6)<br>&gt;&gt;&gt; print(py_ver)</pre><pre>&gt;&gt;&gt; other_version = 2.7<br>&gt;&gt;&gt; print(f&quot;We could have also used Python {other_version}&quot;) # another way of performing string formatting</pre><pre>&gt;&gt;&gt; print(&quot;{0}{1}{0}&quot;.format(&quot;abra &quot;,&quot;cad&quot;))</pre><pre>We are using Python version 3.6.x<br>We could have also used Python 2.7<br>abra cadabra</pre><h3>Useful Pythonic Functions</h3><pre># strings</pre><pre>&gt;&gt;&gt; print(&quot;,&quot;.join([&quot;NASA&quot;,&quot;Google&quot;,&quot;Netflix&quot;,&quot;Yahoo&quot;]))</pre><pre>&gt;&gt;&gt; print(&quot;NASA-Google-Netflix-Yahoo&quot;.split(&quot;-&quot;))</pre><pre>&gt;&gt;&gt; print(&quot;Python 2.7&quot;.replace(&quot;2.7&quot;,&quot;3.6&quot;))</pre><pre>&gt;&gt;&gt; print(&quot;There is more to it than meets the eye&quot;.startswith(&quot;There&quot;)) # also endswith is there</pre><pre>&gt;&gt;&gt; print(&quot;python&quot;.upper())</pre><pre>NASA,Google,Netflix,Yahoo<br>[&#39;NASA&#39;, &#39;Google&#39;, &#39;Netflix&#39;, &#39;Yahoo&#39;]<br>Python 3.6<br>True<br>PYTHON<br></pre><pre># numeric</pre><pre>&gt;&gt;&gt; print(max(10,64,86,13,98))<br>&gt;&gt;&gt; print(abs(-9))<br>&gt;&gt;&gt; print(sum([2,4,6,8]))</pre><pre>98<br>9<br>20</pre><h3>User Input Function</h3><p>There is no raw_input function in Python 3 as available in Python 2. <strong>By default, it expects string input</strong>.</p><pre># user input<br>data_input = int(input(“Enter your ID: “))<br>print(type(data_input))<br>print(“Employee having ID No: {} is late for office today.”.format(data_input))</pre><pre>Enter your ID: 7547857824<br>&lt;class &#39;int&#39;&gt;<br>Employee having ID No: 7547857824 is late for office today.</pre><pre># multiple inputs in a single entry<br>var_1, var_2 = input(&quot;Enter your name: &quot;).split(&quot;-&quot;)<br>print(var_1)<br>print(var_2)</pre><pre>Enter your name: bruce-wayne<br>bruce<br>wayne</pre><pre># another way of performing the same thing mentioned above<br>name_var = input(&quot;Enter your name: &quot;).split(&quot; &quot;)<br>print(name_var[0])<br>print(name_var[-1])</pre><pre>Enter your name: bruce martha wayne<br>bruce<br>wayne</pre><h3>User-Defined Function</h3><p>Before going ahead, can you tell me the difference between a function and a method? Well, here is the answer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb3821010874c309c62e87862e98fcc8/href">https://medium.com/media/bb3821010874c309c62e87862e98fcc8/href</a></iframe><p>Create your own functions using <strong>def</strong> keyword.</p><p>UDF can either take or don’t take arguments. Technically, <strong>parameters</strong> are the variables in a function definition, and <strong>arguments</strong> are the values placed to the parameters when the function is called.</p><p>The name of the UDF should be <strong>lowercase</strong>.</p><p><strong>NOTE: You must define functions before they are called, in the same way you declare a variable before using them</strong></p><pre>&gt;&gt;&gt; def udf_1(rqrdArg):<br>        return(3*rqrdArg)</pre><pre>&gt;&gt;&gt; def udf_2(optnlArg = None):<br>        print(&quot;OptionalArg: &quot;, optnlArg)<br>    <br>&gt;&gt;&gt; def udf_3(rqrdArg, optnlArg=None, *args, **kwargs): # *args = extra unnamed argument, **kwargs = extra named arguments<br>        print(&quot;RequiredArg: &quot;, rqrdArg)<br>        print(&quot;OptionalArg: &quot;, optnlArg)<br>        print(&quot;Remaining Non-keyworded args: &quot;,args)<br>        print(&quot;Remaining keyworded args: &quot;,kwargs)</pre><pre>&gt;&gt;&gt; print(&quot;Calling UDF 1!&quot;)<br>&gt;&gt;&gt; print(&quot;RequiredArg: &quot;, udf_1(5.7))</pre><pre>&gt;&gt;&gt; print(&quot;\nCalling UDF 2!&quot;)<br>&gt;&gt;&gt; udf_2()<br>&gt;&gt;&gt; udf_2(9)</pre><pre>&gt;&gt;&gt; print(&quot;\nCalling UDF 3!&quot;)<br>&gt;&gt;&gt; udf_3(&quot;Python&quot;,&quot;3.6&quot;,2,7,MSU_Python_Session=1)</pre><pre><br>Calling UDF 1!<br>RequiredArg:  17.1<br><br>Calling UDF 2!<br>OptionalArg:  None<br>OptionalArg:  9<br><br>Calling UDF 3!<br>RequiredArg:  Python<br>OptionalArg:  3.6<br>Remaining Non-keyworded args:  (2, 7)<br>Remaining keyworded args:  {&#39;MSU_Python_Session&#39;: 1}</pre><p><strong>*args</strong> and <strong>**kwargs</strong> allow one to pass a <strong>variable-length argument list</strong> and <strong>keyworded, variable-length argument dictionary</strong> respectively to a function when one doesn’t know beforehand how many arguments can be passed to the function.</p><pre>&gt;&gt;&gt; def UDF_factorial(x):<br>        &quot;&quot;&quot;<br>        This is a recursive function performing factorial of a number<br>        x -&gt; the number whose factorial is calculated<br>        &quot;&quot;&quot;<br>        if x == 1:<br>            return 1<br>        else:<br>            return x * UDF_factorial(x-1)<br>    <br>&gt;&gt;&gt; print(UDF_factorial(5))</pre><pre>120<br></pre><pre># how to check the function&#39;s docstring in notebook</pre><pre>&gt;&gt;&gt; ?UDF_factorial # (and execute)</pre><h3>Scope of a variable</h3><p>Not all variables are accessible from all parts of our program, and not all variables exist for the same amount of time.</p><p>Basically, part of a program where a variable is accessible is its <strong>scope</strong> and the duration for which the variable exists its <strong>lifetime</strong>.</p><p>There are two types of variable scope:</p><ul><li><strong>Global</strong>: It is defined in the main body of a file, will be visible throughout the file, and also inside any file which imports that file.</li><li><strong>Local</strong>: it is defined inside a function, limiting its availability inside that function. It is accessible from the point at which it is defined until the end of the function, and exists for as long as the function is executing.</li></ul><p>In Python 3, a third type of variable scope has been defined — <strong>nonlocal</strong>. It allows to assign variables in an <strong>outer, but non-global</strong>, scope.</p><pre># example showing global, local and nonlocal scopes</pre><pre># global and local<br>&gt;&gt;&gt; x = &quot;global&quot;<br>&gt;&gt;&gt; def foo():<br>        print(&quot;x inside :&quot;, x)</pre><pre>&gt;&gt;&gt; foo()<br>&gt;&gt;&gt; print(&quot;x outside:&quot;, x)</pre><pre>x inside : global<br>x outside: global</pre><pre>&gt;&gt;&gt; def outside():<br>        msg = &quot;Outside!&quot;<br>        def inside():<br>            msg = &quot;Inside!&quot;<br>            print(msg)<br>        inside()<br>        print(msg)<br>    <br>&gt;&gt;&gt; outside()</pre><pre>Inside!<br>Outside!</pre><p><em>msg</em> is declared in the <strong>outside</strong> function and assigned the value <em>“Outside!</em>”. Then, in the <strong>inside</strong> function, the value <em>“Inside!”</em> is assigned to it.</p><p>When we run <strong>outside</strong>, <em>msg</em> has the value “Inside!” in the <strong>inside</strong> function, but retains the old value in the <strong>outside</strong> function.</p><p>We see this behaviour because Python hasn’t actually assigned new value <em>“Inside”</em> to the existing <em>msg</em> variable, but has created a new variable called <strong>msg in the local scope of inside that shadows the name of the variable in the outer scope</strong>.</p><p>Preventing that behaviour is where the nonlocal keyword comes in.</p><pre>#nonlocal<br>&gt;&gt;&gt; def double_outside():<br>        msg = &quot;Double Outside!&quot;<br>        def outside():<br>            msg = &quot;Outside!&quot;<br>            def inside():<br>                nonlocal msg<br>                msg = &quot;Inside!&quot;<br>                print(msg)<br>            inside()<br>            print(msg)<br>        outside()<br>        print(msg)<br>    <br>&gt;&gt;&gt; double_outside()</pre><pre>Inside!<br>Inside!<br>Double Outside!</pre><p>Now, by adding <strong>nonlocal</strong> <em>msg</em> to the top of <strong>inside</strong>, Python knows that when it sees an assignment to msg, it should assign to the variable from the outer scope <strong>instead of declaring a new variable that shadows its name</strong>.</p><p>The usage of nonlocal is very similar to that of global, except that the former is used for <strong>variables in outer function scopes</strong> and the latter is used for variable in the global scope.</p><h3>Additional Read</h3><ul><li><a href="https://docs.python.org/3/tutorial/floatingpoint.html">Floating Point Issue</a></li><li><a href="https://www.python.org/dev/peps/pep-0008/">PEP0008 — Style Guide of Python</a></li><li><a href="https://docs.python-guide.org/writing/style/">The Hitchhker’s Guide to Python — Writing Style</a></li></ul><p>This is enough for the first part! I hope you guys have liked this article. Give it a clap and we will meet in the 2nd part of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bbe3e2bb762" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>