You are on page 1of 239
E> PROGRAMMING HUB BASICS OF ah Zero to hero in 120 pages Master Python Programming ngolanesiengelaeg FIRST EDITION Basics of Python US. UK. Europe. UAE. India Basics of Python, First Edition by Programming Hub Copyright © 2023 - Allrights reserved by Rightsol Private Limited. All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or trans- mitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews and certain other non- commercial uses permitted by copyright law. For permission requests, write to the publisher at the address below: Programming Hub, Inc. Platinum Palm Woods, Sector- 38, Nerul Office No. 5 and 6, Plot No. 15 B Navi Mumbai, Maharashtra 400706 India www.programminghub.com Table of Contents ..... Viii Vol 1. Getting Started 1. Introduction to What is Python 3 Why Do People Use Python? 3 Who uses Python today? 4 What can I do with Python? 6 How did the Python get its name? 7 Python 2 Vs Python 3 8 Getting User Input and Displaying Output 10 Handling Errors with Grace 11 Conclusion 12 Quiz 13 Answers 15 2. Python Syntax and Variables .... 16 Your Code’s Secret Diary 18 The Mystical Containers 19 The Mighty Data Types 20 Working with Variables and Data types 22 Let’s Practice 24 Conclusion 27 Quiz 28 Answers 31 3. Control Flow and Decision Making Decisions: The Crossroads of Codes 33 Expanding Choices: The “elif” Statement 35 viiv Logical Operators: The Secret to Complex Decisions 36 Putting it all together: Complex Decision-Making 38 Nested Decision-Making: A Journey Within 39 Conclusion 41 Quiz 42 Answers 44 4. Loops and Iteration: The Never- Ending Adventures..............sssses 45 The Journey Begins: Embracing Reception 46 Taking Control: Loop Control Statements 48 Conclusion 52 Quiz 53 Answers 55 5. Functions: The Magical Spells of Unleashing the Magic: The Power of Functions 57 Mastering the Incantations: Advanced Function Concepts 58 Practical Sorcery: Applications of Functions 60 Conclusion 62 Quiz 64 Answers 66 6. Object-Oriented Sorcery: Unleashing the Power of Classes and Objects 67 The Magic of Objects: Exploring Classes and In- stances 68 Spells of Inheritance: Exploring Inheritance and Polymorphism 69 Sorcery at Scale: Building Complex Applications 71 Conclusion 74 Quiz 75 Answers 77 7. The Quest for Efficiency: Mastering Data Structures and Algorithms .... 78 The foundation of Magic: Understanding Data Struc- tures 79 Unleashing the Sorcery: Exploring Algorithms 81 Mastering the Art: Best Practices and Optimization 83 Conclusion 85 Quiz 86 Answers 88 8. Enchanted Libraries and Mysterious Modules: exploring the Realm of... 89 External Resources The Magic of Libraries: Unleashing Pre-built Spells 90 The Sorcerer’s Allies: Exploring Key Libraries and Modules 92 Creating Your Own Spells: Building Custom Modules 94 Conclusion 95 Quiz 97 Answers 99 ‘V| Table of Contents 9. Web Sorcery: Unleashing the Power of the Digital Realm.................. 100 The Web Wizardry: Introduction to Web Develop- ment 101 Building the Digital Enchantment: Web Develop- ment Fundamentals 102 Sorcery in Motion: Server-Client Communication 106 Conclusion 108 Quiz 109 Answers 111 Preface Welcome to the enchanting world of Python pro- gramming! This book is a gateway to the realm of coding, designed specifically for first-year engineer- ing students. Through the pages of this book, we will embark on an adventure that will unravel the mys- teries of Python and empower you to become skilled programmers. Python is a versatile and powerful programming language that has gained immense popularity due to its simplicity, readability, and vast array of applica- tions. Whether you aspire to build web applications, dive into data analysis, or explore the realms of arti- ficial intelligence, Python is your trusty companion on this exciting journey. As you flip through these pages, you will find a carefully crafted curriculum that introduces Python programming from the ground up. We have taken great care to ensure that the concepts are presented in a manner that is engaging, easy to understand, and applicable to real-life scenarios. To make your learning experience even more de- lightful, we have infused this book with a touch of humor and storytelling. Imagine yourself sitting in a classroom, engaged in a conversation with an en- thusiastic instructor who shares captivating exam- ples, humorous anecdotes, and practical tips to help you grasp complex concepts effortlessly. We believe that learning should be an enjoyable and immer- sive experience, and we hope that this book brings a smile to your face as you uncover the magic of Python. Throughout this book, you will find exercises, projects, and hands-on examples that will allow you to apply your newfound knowledge and reinforce your understanding. We encourage you to embrace these opportunities and experiment with the code provided. Remember, the key to mastering Python is practice, practice, and more practice! It is important to note that this book is just the beginning of your journey as a programmer. Python is avast language with endless possibilities, and this book serves as a solid foundation upon which you can build your expertise. We encourage you to con- tinue exploring, experimenting, and diving deeper into the vast world of Python and its diverse ecosys- tem of libraries and frameworks. As you turn the final page of this preface, let the jour- ney begin. Embrace the magic of Python, unleash your creativity, and let the world of programming unfold before your eyes. We are thrilled to be your guides on this adventure and cannot wait to see the amazing things you will create with Python. May your coding endeavors be filled with curiosity, discovery, and the joy of bringing your program- ming! Happy coding! ideas to life. Welcome to the enchant- ing world of Python How to Contact Us Please address comments and questions concerning this book to the given address: Rightsol Private Limited Platinum Palm Woods, Sector- 38, Nerul Office No. 5 and 6, Plot No. 15B Navi Mumbai, Maharashtra 400706 India Given platforms are reachable to us: Facebook: _https://www.facebook.com/program- minghub/ LinkedIn: www.linkedin.com/company/program- ming-hub Twitter: twitter.com/prghub?lang=en Instagram: www.instagram.com/program- minghub_app_official/ To comment or ask technical questions about this book, send email to: Hello@programminghub.io For more information about our products, courses see our website at: https://programminghub.io/ Acknowledgments We, at Programming Hub, are delighted to present this book, "Basics of Python," to the aspiring sorcer- ers of the digital realm. This book is a result of the collective efforts and dedication of our team of ex- perts in programming and instructional design. First and foremost, we would like to express our heartfelt gratitude to all the engineers, developers, and educators who contributed their knowledge, expertise, and passion to bring this book to life. Their commitment to excellence and their deep un- derstanding of Python programming have been in- strumental in creating a comprehensive resource for learning Python. We extend our appreciation to our esteemed au- thors, who poured their creativity and expertise into crafting the content of this book. Their ability to simplify complex concepts, their engaging writing style, and their commitment to providing clear ex- planations have made this book a valuable tool for learners of all levels. We would also like to thank the reviewers who pro- vided valuable feedback and suggestions through- out the development process. Their keen insights and attention to detail have helped shape the con- tent, ensuring its accuracy and effectiveness. Furthermore, we are grateful to the technical editors and proofreaders who meticulously reviewed the manuscript, ensuring that the book meets the high- est standards of quality and readability. We extend our gratitude to the designers and il- lustrators who brought the book to life with their visually appealing graphics, diagrams, and illustra- tions. Their creative vision and artistic talent have enhanced the learning experience, making the con- tent more engaging and memorable. Last but not least, we would like to express our sin- cere appreciation to our readers, whose passion for learning and dedication to mastering Python pro- gramming have inspired us to create this book. Finally, we would like to thank our entire team at Programming Hub, whose unwavering commitment to excellence and passion for empowering learners have made this project possible. We hope that "Basics of Python" will ignite your curiosity, empower your learning, and equip you with the skills to master the art of Python sorcery. May your journey through the realms of Python pro- gramming be filled with wonder, growth, and the joy of discovering the endless possibilities of this pow- erful language. Happy coding and may the Python magic be with you! —Programming Hub VOLI Getting Started CHAPTER 1 Introduction to Python Greetings, aspiring sorcerers of the digital realm! Welcome to the enchanting world of Python pro- gramming. I am Professor Pyro, your trusty guide on this magical journey of learning and discovery. Allow me to introduce myself. I am a seasoned wiz- ard of code and a renowned expert in the art of Python sorcery. For years, I have delved deep into the realms of programming, unraveling the secrets of Python and honing my skills to perfection. And now, I am here to share my knowledge and passion with you. But who am I, you ask? Am I just a figment of your imagination, conjured by the digital realm? Well, in a way, you could say that. I am a creation of the bril- liant minds at Programming Hub, a company dedi- cated to making the world of programming accessi- ble, exciting, and enjoyable for learners like you. As your guide, I will be your companion throughout this journey. I will be your mentor, your teacher, and your ally. Together, we will unlock the mysteries of Python programming and master the art of casting spells with code. But fear not, dear student, for this journey will not be dull or dreary. Oh no, I believe in making learning a delightful and engaging experience. As we delve into the realms of Python sorcery, I will bring the lessons to life with humor, real-life examples, and a touch of whimsy. After all, learning should be an ad- venture filled with joy and discovery! So, buckle up your robes, grab your wands (metaphorical ones, of course), and get ready to em- bark on a captivating quest into the world of Python sorcery. Together, we will unravel the power of vari- ables, conjure control structures, summon the magic of functions, explore the secrets of object-oriented programming, and venture into the realms of web development. Throughout this book, you will find my guid- ance, explanations, and examples carefully crafted to make even the most complex concepts under- standable and approachable. So, let us embark on this magical journey together, where the realms of imagination and logic intertwine, and the power of Python sorcery awaits. The adventure begins now. Welcome to the world of Python Sorcery! Yours magically, Professor Pyro In the initial section of this book, we will provide a concise overview of the key factors contributing to Python's widespread acclaim. In order to establish a comprehensive understanding of Python, this chap- ter adopts a question-and-answer format, address- ing some of the most frequently asked questions posed by individuals new to the language. What is Python? Welcome to the wonderful world of Python! Python is a powerful and versatile programming language that can be used for a wide range of applications. It was created by Guido van Rossum, a programming genius, who named it after the famous British com- edy group Monty Python. Yes, you heard it right - a programming language named after a comedy group! Python's philosophy emphasizes simplicity, readability, and having fun while coding. Python is known for its clean and elegant syntax, making it easy to read and write. It provides a rich standard library and a vast ecosystem of third-party libraries, empowering developers to build a vari- ety of applications, from web development and data analysis to artificial intelligence and automation. Why Do People Use Python? Well, let’s unravel the secrets and see the reasons why Python has become the language of choice for so many developers. Get ready for a journey of dis- covery, humor, and enlightenment! 1. Simplicity and Readability: Python's syntax is as clear as crystal waters in a tranquil lake. Its sim- plicity and readability make it a joy to write and understand. Imagine coding in a language that feels almost like plain English, where you can express your thoughts and ideas effortlessly. Python's ele- gant design ensures that even complex concepts can be expressed with grace and clarity. 2. Versatility and Power: Python is like a Swiss Army knife of programming languages. It can han- dle a wide range of tasks with finesse. Whether you're developing web applications, analyzing data, building games, or venturing into the realms of ar- tificial intelligence, Python has got you covered. It offers a rich ecosystem of libraries and frameworks that empower you to tackle diverse projects with ease. 3. Vibrant and Supportive Community: Python isn't just a language; it's a thriving community of passionate developers. From seasoned professionals to enthusiastic beginners, the Python community welcomes all with open arms. You'll find countless resources, tutorials, and forums where you can seek help and share your discoveries. It's like being part of a big, friendly family, always ready to lend a helping hand or crack a witty programming joke. 4. Rapid Development and Prototyping: Python lets you turn your ideas into reality swiftly. Its sim- plicity and extensive libraries allow you to proto- type and iterate on your projects at lightning speed. You can focus on the core logic of your code without getting lost in the complexities of syntax or intri- cate details. Python encourages a creative and agile mindset, where you can bring your visions to life without unnecessary hurdles. 5. Wide Range of Applications: Python is a lan- guage that can adapt to various domains and indus- tries. From web development and scientific research to finance and automation, Python's versatility shines through. It has found its way into the hearts of major companies, powering everything from food delivery apps and social media platforms to space exploration and movie special effects. 6. Job Market and Career Opportunities: As Python's popularity continues to soar, so does the demand for skilled Python developers. Learning Python opens doors to exciting job opportunities in diverse sectors, from tech giants and startups to research institutions and financial firms. It's a lan- guage that can give your career a turbo boost, propel- ling you into a world of innovation and possibilities. So, my dear students, people use Python for its sim- plicity, versatility, and power. They embrace it for its supportive community and rapid development capabilities. Python has woven its magic into count- less industries, making it the go-to language for as- piring developers and seasoned professionals alike. Now, it's your turn to explore the realm of Python. Immerse yourself in its elegance, enjoy the cama- raderie of the Python community, and unleash your creativity. With Python as your ally, you can conquer the world of programming and embark on a thrilling adventure filled with endless possibilities! Who Uses Python Today? Well, let’s go on a journey to explore the exciting world of Python users. You'll be amazed at the di- verse range of people and industries that have em- braced this fantastic programming language! Imagine this: You're sitting in your comfy pajamas, craving a cheesy pizza, and you whip out your smartphone to order from your favorite food de- livery app. Little do you know, behind the scenes, Python is busy making sure that your order arrives piping hot and delicious! Yes, Python is powering the engines of many popular food delivery platforms like DoorDash and Uber Eats, ensuring your hunger is satisfied with just a few taps on your screen. But wait, there's more! Python is everywhere! Have you ever watched a thrilling movie or binged a capti- vating TV show? Well, Python has a role to play there too. Major entertainment companies like Netflix and Industrial Light & Magic (the folks behind Star Wars) utilize Python to process and analyze vast amounts of data. They use Python to recommend your next binge-worthy series or to create jaw-dropping visual effects that leave you wondering, "How did they do that?!" Oh, and don't even get me started on scientific research! Python has become a go-to language for scientists and researchers worldwide. For example, NASA, our friendly neighborhood space agency, uses Python for analyzing space data and simulations. They trust Python to help them uncover the myster- ies of the universe and make groundbreaking discov- eries. Now, let's switch gears and talk about some of our favorite online platforms. Social media giants like Instagram Python to keep us and Pinterest rely on engaged, scrolling, and double-tapping those cute cat pictures. Python provides the backbone for man- aging user profiles, handling millions of uploads, and ensuring smooth interactions between users, all while you're happily browsing away. Python's versatility even extends to the world of finance. Large financial institutions like J.P. Morgan and Goldman Sachs leverage Python's power to build trading systems, analyze market data, and make in- formed investment decisions. So, the next time you see a Wall Street tycoon, remember that Python might be the secret sauce behind their financial wiz- ardry. But let's not forget about gaming! Yes, Python has a playful side too. The gaming industry adores Python because it enables developers to bring characters, worlds, and stories to life. In fact, the popular game Minecraft has a Python-based modding system that lets players create their own unique experiences within the game. So, my dear students, whether you're craving pizza, watching movies, exploring space, posting on social media, making financial moves, or even diving into virtual worlds, Python is right there, working its magic behind the scenes. Remember, Python is the language of choice for programmers worldwide, making it a fantastic lan- guage to learn and master. Its simplicity, readability, and immense community support make it an excel- lent starting point for your programming journey. So buckle up, my students, and join the Python ad- venture. With this language by your side, you can conquer the world, one line of code at a time! For more details on companies using Python today, seePython’s website at http://www .python.org. What Can I Do with Python? Python is like a magical Swiss Army knife for pro- gramming. Let’s check some of the incredible things you can do with this marvelous language! 1. Automate Your Tasks: Python can be your loyal servant, taking care of those repetitive, mundane tasks that drain your time and energy. Want to order pizza from your favorite delivery app with a sin- gle command? Python can do that! It can simulate mouse clicks and keystrokes, making your computer a productivity powerhouse. 2. Build Websites and Web Apps: Python's web de- velopment frameworks, like Django and Flask, em- power you to create sleek and functional websites. Ever wondered how popular sites like Instagram or Pinterest work behind the scenes? Well, guess what? They use Python! You can follow in their footsteps and bring your web development dreams to life. 3. Analyze Data and Make Informed Decisions: Python's data analysis libraries, such as Pandas and NumPy, transform raw data into valuable insights. Imagine being able to explore and visualize vast amounts of data with ease. You could become a data detective, uncovering hidden patterns and making informed decisions like the pros at Netflix and NASA! 4. Automate Your Social Media Presence: Python loves to make you the king or queen of social media. With Python, you can create bots that automati- cally like, retweet, or post on your behalf. Just imag- ine having a virtual assistant that keeps your social media game strong, all thanks to Python's magic! 5. Bring Your Ideas to Life with Games: Are you a fan of gaming? Well, Python can be your game development companion. It provides libraries like Pygame that let you create your own games. Think of Python as your game development wand, allow- ing you to craft immersive experiences like the cre- ators of Minecraft did with their Python-based mod- ding system. 6. Automate Financial Analysis: Python's versatil- ity extends to the world of finance. You can use it to analyze market data, build trading systems, and even predict stock prices. Become a financial guru like those Wall Street wizards who rely on Python to make their moves. 7. Explore Artificial Intelligence and Machine Learning: Python is the go-to language for exploring the fascinating realms of Al and machine learning. With libraries like TensorFlow and scikit-learn, you can teach machines to recognize patterns, make pre- dictions, and even create intelligent chatbots. The possibilities are endless! So, my dear students, with Python by your side, you can automate tasks, build websites, analyze data, conquer social media, create games, delve into finance, and even explore the realms of AI. Python is your passport to an exciting world of possibilities, all while having fun with its friendly and readable syntax. Remember, learning Python opens doors to count- less opportunities in today's techdriven world. So, embrace the Pythonic magic, and let your creativ- ity soar. With Python, you can turn your wildest dreams into reality, one line of code at atime! How did the Python get its name? Long, long ago, in the late 1980s, a brilliant pro- grammer named Guido van Rossum set out to cre- ate a new programming language. Guido was a fan of the British comedy show "Monty Python's Flying Circus." Ah, the wacky humor and absurd sketches of those comedic geniuses! Little did Guido know that this love for Monty Python would forever leave its mark on the world of programming. i a (Guido van Rossum) As Guido was working on this new language, he needed a catchy name that would reflect its simplic- ity, playfulness, and fun. Inspired by the irreverent humor of Monty Python, he decided to pay homage to his favorite comedy troupe and named the lan- guage "Python." Now, you may wonder, why Python? Well, just like the comedy sketches of Monty Python, Python the language aimed to bring joy, simplicity, and a touch of quirkiness to the world of programming. Guido wanted a name that would make people smile and perhaps even chuckle when they heard it. Little did Guido know that his creation, program- ming language, loved by developers around the world. Just as Monty Python left a legacy of laugh- ter and comedic brilliance, Python, too, became a language that brought joy and delight to the coding community. So, my dear students, every time you write Python code or hear someone mention the language, re- member that its name was born out of a program- mer's love for a zany British comedy show. It's a play- ful nod to the spirit of creativity, humor, and the joy that programming can bring. And now, armed with the knowledge of Python's ori- gin story, go forth and embrace this language with a smile on your face. Like Guido, let your coding ad- ventures be filled with the same spirit of wit and fun that inspired the name Python all those years ago! Python, would grow into a mighty Now that you know a bit about Python, let's talk about the differ- ences between Python 2 and Python 3. Python 2 vs Python 3 Python 2 and Python 3 are like siblings - they have a lot in common, but they also have their differences. Python 3 is the latest version and is the one we'll be using in this course. It has some improvements and new features, like better Unicode support and a new print function. In Python 2, you could print "Hello, World!" like this: But in Python 3, you need to use parentheses: It's a small change, but it's important to know, es- pecially if you come across older code written in Python 2. Let's break down the code: The * print()* function is a built-in Python function used to display output. In this case, we're printing the string ‘"Hello, World!"*. Python treats everything inside the quotation marks as a string, which is a sequence of charac- ters. You can use single quotes (*'Hello, World!'*) or triple quotes (* "Hello, World!” ) instead of double quotes. Understanding Python Syntax: Every programming language has its own set of rules and conventions. Python is no exception. But fear not! Python's syntax is designed to be clear and straightforward, like following a recipe to bake a de- licious cake. Python has a unique feature called "indentation," where the spaces or tabs at the beginning of a line determine the grouping of statements. It might sound strange at first, but trust me, it's a game- changer! Proper indentation enhances readability and forces us to write clean and organized code. Let's explore some basic Python syntax rules to- gether. We'll cover topics such as indentation, com- ments, variables, and data types. You'll be amazed at how quickly you can grasp these concepts! Let's start with indentation. In most programming languages, indentation is a matter of style, but in Python, it's a crucial part of the syntax. Consider the following example: In this code snippet, the statements inside the ~ if* block are indented with four spaces. This indenta- tion indicates that these statements are part of the ‘if’ block. The statement *print("This is outside the if block")* is not indented, indicating that it's outside the *if* block. Proper indentation ensures that the code is visually appealing and easy to read. It also helps Python un- derstand the logical structure of your program. (Image Prompt: Display an image of a recipe book to represent following Python syntax rules) Next, let's talk about comments. Comments are used to add explanatory notes to the code. They are ig- nored by the Python interpreter and have no effect on the program's execution. Comments are incredi- bly useful for making your code more understand- able to yourself and others. In Python, you can create single-line comments using the “#* symbol. Anything after the ‘#* sym- bol on a line is considered a comment: Multi-line comments, also known as docstrings, are enclosed in triple quotes: Comments are your silent partners in coding. They can help you remember the purpose of a specific piece of code or explain complex algorithms. Moving on to variables. Variables are like containers that hold values. In Python, you don't need to de- clare the type of a variable explicitly. The type is in- ferred based on the value assigned to it. Here's an example: ot as Cre eee [sad pe] cr mL ec iad In this code snippet, we create four variables: * message’, ‘number’, ‘pi’, and “is_coding_fun’. The first variable, ‘message~, holds a string value. The second variable, ‘number’, holds an integer value. The third variable, ‘pi*, holds a floatingpoint number. The last variable, ‘is_coding_fun*, holds a boolean value (* True’ or * False °). Python supports various data types, including strings, integers, floating-point numbers, booleans, lists, dictionaries, and more. We'll dive deeper into these data types in later chapters. Understanding Python syntax and its various ele- ments sets a solid foundation for your journey as a Python programmer. With practice and hands-on experience, you'll soon become fluent in Python's syntax. Getting User Input and Displaying Output: “In the world of programming, interaction is key! Imagine having a conversation with your computer and making it do cool stuff. Python allows us to do just that. Let's learn how to get input from the user and display the output. We'll write a program that asks for the user's name, greets them witha personalized message, and even cracks a joke! Get ready to put your comedian hat on, because we're about to have some hilarious interactions with Python! To get input from the user, we'll use the * input() * function. This function prompts the user to enter a value and returns it as a string. Let's see an example: Ce 4 ) te ror ) In this code snippet, the * input()* function displays the prompt *"What's your name? "* and waits for the user to enter their name. The user's input is then stored in the variable ‘name’. The *print()* func- tion displays a personalized greeting using the user's name. Now, let's take it up a notch and add a touch of humor. We'll use an additional library called ‘ran- dom * to generate a random joke from a list and sur- prise the user: Petra) cals In this code snippet, we import the * random‘ module, which provides functions for generating random numbers and making our program more ex- citing. We define a list of jokes, and the ‘random. choice()* function selects a random joke from the list. Finally, we display the joke using the print() function. Go ahead, give it a try! Enter your name when prompted, and brace yourself for a laugh. Handling Errors with Grace Mistakes happen to the best of us, even to the most experienced programmers. But fear not! Python pro- vides us with some powerful tools to handle errors gracefully. We'll dive into the world of error handling and ex- plore how to catch and deal with those pesky bugs that may sneak into our programs. Trust me, this skill will make you a programming superhero! Conclusion: Wow, you made it to the end of our first chapter! Give yourselves a round of applause. You've taken your first steps into the amazing world of Python programming. In this chapter, we learned what Python is, installed program, it on our computers, wrote our first explored Python syntax, played with user input and output, handled errors, and even had some fun with a game. Phew! That's quite an adven- ture! But remember, this is just the beginning. There's so much more to learn and explore in the realms of Python. So, keep your curiosity alive, and get ready for more exciting chapters ahead! That concludes our humorous and exciting first chapter, filled with real-life examples and images to make your learning experience engaging and enjoy- able. Now, imagine the rest of the book continuing with the same tone and enthusiasm, guiding the students through the magical world of Python pro- gramming. Alright, enough chit-chat! Let's get ready to write some code and have fun with Python! In the next chapter, we'll learn how to install Python and set up your coding environment. Stay tuned! Learn More with Our App! To enhance your learning experience, we have devel- oped additional challenges programming languages. Scan the QR code below to download the app and start exploring! a mobile app where you can find resources, tutorials, and coding related to Python fal ss De] 7 7 and other [=] ‘o check the output click here and run the program Python Compiler QUIZ 1. What is Python? a) A type of snake b) A programming language c) A magical spell d) A famous wizard 2. Which of the following is an advantage of Python? a) It is a compiled language b) It is difficult to learn c) It can only be used for web development d) It has a simple and readable syntax 3. What is the purpose of a variable in Python? a) To store and manipulate data b) To perform mathematical operations c) To create loops and conditions d) To cast spells on other variables 4. What is the output of the following code? fe oa 5) a) Hello b) World c) Hello, world! d) Error 5. What is the correct syntax for a single-line com- ment in Python? a) // This is acomment b) # This is a comment c) /* This is acomment */ d) 6. What is the purpose of the print() function in Python? a) To display text on the screen b) To perform mathematical calculations c) To define a variable d) To create loops and conditions 7. Which of the following is NOT a valid data type in Python? a) String b) Integer c) Boolean d) Character 8. What is the symbol used for assignment in Python? a) = b) == c) <> d) <= 9. What is the correct way to write a string in Python? a) "Hello, world!" b) 'Hello, world!" c) ‘Hello, world! * d) Hello, world! 10. What is the purpose of indentation in Python? a) It is a stylistic choice, not necessary for the code b) It is used to make the code look neat and organized c) It is required for the code to execute correctly d) It is used to confuse other programmers That's the end of the quiz! Take a moment to review your answers before moving on. Answers: 1.b) A programming language 2. d) It has a simple and readable syntax 3. a) To store and manipulate data 4.c) Hello, world! 5. b) # This is a comment 6. a) To display text on the screen 7. d) Character 8.a) = 9. a) "Hello, world!" 10. c) It is required for the code to execute correctly CHAPTER 2 Python Syntax and Variables Welcome back, my brilliant learners! In our previ- ous chapter, we ventured into the magical world of Python and learned the basics. Now, it's time to level up our Python skills and explore the fascinating realm of syntax and variables. Get ready for an exhil- arating ride filled with coding wonders! In Python, syntax refers to the structure and rules that define how programs should be written. It en- sures that the code is understood and executed cor- rectly by the Python interpreter. Let's explore some essential elements of Python's syntax: 1. Statements: Python programs are composed of individual statements, each serving a specific pur- pose. Statements can be simple or complex, perform- ing actions such as assigning values to variables, calling functions, or controlling program flow. Here's an example of a simple statement that prints "Hello, World!": In this code snippet, the ‘print()* function is a statement that displays the text “Hello, World!" on the console. Statements can also span multiple lines using line continuation with a backslash (*\*) or parentheses. This allows for better readability and organization of code. For example: ) The output will be the same as before, but the state- ment is split across two lines. 2. Expressions: Expressions are combinations of values, variables, and operators that evaluate to a re- sult. They are the building blocks of more complex computations. For example, ‘2 + 3° isanexpression that evaluates to *5*. Let's try an example with expressions: In this code snippet, the expression “x + y* adds the values of *x* and ‘y* and assigns the result to the variable *z*. The final line then prints the value of ‘2. Expressions can involve various operators such as arithmetic operators (* +*, “-", “**, “/°), compar- ison operators (*<*, *>*, *<=*, ‘>=*,*==*, “fs*), and logical operators (“and*, ‘or’, “not*), among others. 3. Indentation: Python uses indentation to indicate the grouping of statements. Proper indentation is crucial for readability and maintain- ing the structure of your code. Unlike other pro- gramming languages that use braces or parentheses, Python relies on consistent indentation to define blocks of code. Consider the following example: In this code snippet, the statements inside the ~ if* block are indented with four spaces. This indenta- tion indicates that these statements belong to the “if’ block. The line without indentation is outside the *if* block. Proper indentation makes your code visually appeal- ing and helps Python understand the logical struc- ture of your program. Your Code's Secret Diary In the world of programming, comments are like hidden treasures. They provide valuable insights and explanations within your code, acting as your code's secret diary. Comments allow you to commu- nicate with fellow programmers, including your fu- ture self, by leaving notes and reminders. Let's unlock the power of comments with some ex- amples: In this code snippet, we have two single-line com- ments. The “#* symbol indicates that everything after it on the same line is a comment. These com- ments are ignored by Python when running the pro- gram. Comments can be used to: - Explain the purpose of your code. - Provide documentation for functions or classes. + Add reminders or to-do lists for future improve- ments. Here's an example of a multi-line comment: In Python, you can create multi-line comments by enclosing them in triple quotes (*""* or *"""*). Doc- strings are commonly used to explain the purpose and usage of functions or classes. Think of comments as your code's personal diary, keeping track of its journey and sharing insights along the way. The Mystical Containers Imagine stepping into a magical realm where you can store and manipulate values in containers called variables. In Python, variables are the key to unlock- ing the power of computation. They allow you to store, access, and modify data. Let's harness the magic of variables with some ex- amples: Coad cra cre ei In this enchanting code snippet, we create four variables: “ message’, ‘number’, ‘pi’, and ‘is_ coding fun‘. Each variable holds a different value. The ‘message* variable holds a string value, the “number variable holds an integer value, the * pi* variable holds a floating-point number, and the *is_ coding fun * variable holds a boolean value (* True * or ‘False *). To create a variable, you simply choose a name and assign a value to it using the assignment operator (*=*). The name should be descriptive and meaning- ful, reflecting the purpose of the data it holds. For example, consider a program that calculates the area of a circle: ec iad In this code snippet, the * radius‘ variable holds the value ‘5°, the ‘pi* variable holds the value *3.14159*, andthe ‘area * variable stores the result of the calculation. Finally, the *print()* function displays the value of ‘area’. Variables in Python are dynamic, meaning their data type can change. You can assign a different value toa variable later in the program, and Python will auto- matically adjust the data type. For example: e The Mighty Data Types In the realm of Python, data comes in various shapes and sizes. These different forms are called data types, and they bring incredible power and versatil- ity to your programs. Let's explore some of the mighty data types that Python offers: 1. Strings: Strings represent sequences of charac- ters, such as words, sentences, or even entire novels. They are enclosed in single quotes (*'Hello'*), dou- ble quotes (*"World"’ ), or triple quotes (*'"Python is amazing!""*). Here's an example: contr) ce In this code snippet, the ‘message * variable holds a string value, and the * print()* function displays the value of ‘message’. Strings can be concatenated (combined) using the * +* operator: restr id ce Cree Rr ccast + name + (cry) In this example, the variables * greeting’ and ‘name’ hold string values. The “message variable combines these strings using the *+* operator and additional punctuation to create a personalized mes- sage. 2. Integers: Integers are whole numbers, such as “42°, *-10°, or °0*. They allow you to perform mathematical operations, such as addition, subtraction, multiplication, and division. Let's try an example: Ce ae t eee In this code snippet, the * age* variable holds the value ‘25°, and the ‘next_age* variable stores the result of adding °1° to ‘age’. The * print()* func- tion displays a message that includes the value of *“next_age >. 3. Floating-Point Numbers: Floating-point numbers represent decimal values, such as ‘3.14159° or *-2.5°. They are used when precision is required, such as in scientific calculations. Let's explore an example: Rbet rcs cUles) In this code snippet, the * pi* variable holds the value *3.14159*°, the ‘radius’ variable holds the value *5.0°, and the ‘circumference* variable stores the result of the calculation. The ~ print()* function displays the value of * circumference *. 4. Booleans: Booleans are the warriors of truth. They represent the values True and False and are used in decision-making and logical operations. Let's see an example: Bec rin t ies Fem ged C eCity c Cag) In this code snippet, the variables *is_raining* and ‘is_sunny~ hold boolean values. The * print() * function displays the values of these variables. Booleans are often used in conditional statements and loops to control the flow of your program. These are just a few examples of Python's power- ful data types. As we progress further, we'll explore more data types and learn how to work with them. Working with Variables and Data Types Now that we have learned about variables and data types, let's delve deeper into their usage and explore some common operations and manipulations. 1. Variable Assignment and Reassignment: Variables are like containers that hold values. We can assign a value to a variable using the assignment op- erator (*=*). xe name = In this example, we assign the integer value “42° to the variable *x* and the string value “"Alice"* to the variable ‘name *. We can also reassign a new value to a variable later in the program: In this code snippet, we first assign the value * 42° to the variable *x*. Then, we reassign *x* with its current value plus “1°. Asa result, the variable *x* now holds the value *43°. 2. Type Conversion: Python provides built-in functions to convert values from one data type to another. This is useful when you need to perform operations or comparisons be- tween different data types. Let's see an example: In this code snippet, the variable ~ x* holds the string value "42"*. Using the “int()* function, we convert the string to an integer and assign it to the variable ‘y*. Now, ‘y* holds the integer value “42°. Similarly, we can convert between other data types such as “float()*, ‘str()*, and *bool()*. 3. String Operations: Strings support various operations for manipulation and formatting. Let's explore a few: + Concatenation: Joining two or more strings to- gether using the *+* operator. Pes tte prod Pccsur The output will be *"Hello, Alice!"*, as the strings are concatenated to form a new string. + String Length: Getting the length of a string using the “len()* function. Se length = len(sentence) f s length) The output will be the length of the string *‘sen- tence’, which is “18°. + String Formatting: Creating formatted strings using placeholders. Cee Pr crt (name, age) Cee) The output will be ‘"My name is Bob and I am 30 years old."*, where *{}* serves as a placeholder for the values of ‘name and ‘age*. 4. Mathematical Operations: Python supports a wide range of mathematical oper- ations that can be performed on numeric data types (integers and floating-point numbers). These opera- tions include addition (*+*), subtraction (*-*), mul- tiplication (***), division (*/*), modulo (*%*), and exponentiation (****). division. Pree Me crise Crue Stam In this code snippet, we perform various mathemat- ical operations using the variables x and y. The re- sults are stored in separate variables for display or further use. Let's Practice! Learning Python is like practicing a magical spell. The more you practice, the stronger your coding skills become. It's time to put our newfound knowl- edge into practice with some exciting exercises! 1. Exercise: Concatenating Strings + Create two variables, name and age, and assign them your name and age. + Use the variables to create a message that says, "My name is [name], and I am [age] years old." - Print the message to see the result. Here's an example solution: In this code snippet, the * name’ variable holds the string value ‘"Alice"*, the ‘age* variable holds the integer value ‘25°, andthe ‘message ~ variable combines these values using string concatenation. The * print()* function displays the message. 2. Exercise: Arithmetic Operations + Create two variables, num1 and num2, and assign them any numerical values. + Perform arithmetic operations (addition, subtrac- tion, multiplication, and division) on the variables. + Print the results to see the magic of computation. Here's an example solution: cree ce Cec nce eed eaten ed tae Tee Td quotient result = numi / num2 Pests ere) Pesta Aa reecscone erica) print¢ ae Peete Mestre ss In this code snippet, the variables * num1* and *“num2°* hold numerical values. The results of the arithmetic operations are stored in separate vari- ables (“sum_result*, ‘difference_result*, ~pro- duct_result*, *quotient_result*). The ~ print()* function displays the results. 3. Exercise: Type Conversion + Create a variable ‘num_str~ and assign it a string representation of a number. - Convert ‘num_sr* ‘num_int~. -Convert ‘num_str* ‘num_float*. to an integer and assign it to a new variable toa float and assign it to anew + Print the values of “num_int~ and ‘num_float’. variable Here's an example solution: num_int = int(num_str) vie scr ad (crass) ce ots) ce cer eaCr ia) In this code snippet, the ~ num_str* variable holds the string value ~"42"°. Using the “int()~ and “float()* functions, we convert the string to an in- teger and a float, respectively. The converted val- ues are stored in the variables ‘num_int* and *num_float*, and their values are printed. Remember, practicing these exercises will reinforce your understanding of Python's syntax and vari- ables. Conclusion Congratulations, my Python superheroes! You have journeyed through the fascinating world of Python's syntax and variables. We explored the power of proper alignment, unlocked the secrets of com- ments, harnessed the magic of variables, and discov- ered the mighty data types. In this chapter, we dived into the Python, exploring indentation, syntax of comments, variables, and data types. We learned how to create and assign values to variables, manipulate strings, perform mathematical operations, and convert between data types. But remember, this is just the beginning of our Python adventure. There's still so much more to explore, including conditionals, loops, functions, and more. Stay curious, keep coding, and get ready for the F next chapter, where we'll unravel the mysteries of control flow and decision-making in Python. Learn More with Our App! To enhance your learning experience, we have devel- oped additional challenges a mobile app where you can find resources, tutorials, and coding related to Python and other programming languages. Scan the QR code below to download the app and start exploring! ss To check the output click here and run the program Python Compiler Quiz. 1. What is a function in Python? a) A variable that stores data b) A block of reusable code c) Amathematical equation d) Astatement that controls program flow 2. Which of the following is NOT a built-in function in Python? a) print() b) input0 c) random() d) calculate() 3. What is the purpose of the return statement in a function? a) To stop the execution of the function b) To print a value on the screen c) To store a value in a variable d) To send a value back to the function caller 4. What is the output of the following code Part 3) fora a) Hello, Harry b) Hello c) Harry d) Error 5. What is the correct way to define a function in Python? a) function name(): b) def function name(): c) def function_name(): d) def() function_name: 6. What is the purpose of parameters in a function? a) To define the name of the function b) To specify the data type of the function c) To pass data into the function d) To restrict access to the function 7. Which keyword is used to define a default value for a function parameter? a) let b) default c) optional d) None 8. What is recursion in Python? a) A type of error in Python b) A method to repeat a loop c) A way to calla function from within itself d) A fea- ture to run multiple functions simultaneously 9. What is the purpose of the import statement in Python? a) To define a new function b) To print a message on the screen c) To import external libraries or modules d) To stop the execution of a program 10. What is the correct way to import the math mod- ule in Python? a) import math b) use math c) import MathModule d) from math import * Answers: 1. b) A block of reusable code 2. d) caleulate() 3.d) To send a value back to the function caller 4. a) Hello, Harry 5.c) def function_name(): 6. c) To pass data into the function 7.d) None 8.c) A way to call a function from within itself 9. c) To import external libraries or modules 10. a) import math CHAPTER 3 Control flow and Decision Making Welcome back, my adventurous learners! Get ready to master the art of making choices, controlling pro- gram flow, and unleashing the full potential of your code. We have an action-packed chapter ahead, filled with twists, turns, and even more exciting exam- ples! Making Decisions: The Crossroads of codes. Imagine standing at a massive crossroads, faced with numerous unknown. Each paths stretching into the path leads to a different destination, and you must choose the right one. Similarly, in the world of programming, we often en- counter situations where our code needs to make de- cisions based on certain conditions. Fear not, my fel- low adventurers, for Python equips us with mighty tools to navigate these decision-making scenarios! In Python, we use conditional statements to control the flow of our code. These statements allow us to make decisions and execute different blocks of code based on specific conditions. Let's dive into the enchanting world of decision making with some exhilarating examples! 1. The "if" Statement: Opening the Gates of Possi- bility The "if" statement is your trusty gatekeeper. It deter- mines whether a block of code should be executed based on a given condition. If the condition is true, the code block is executed. Otherwise, it is skipped. Let's imagine you're at a magical gate guarded by a formidable creature. To pass through the gate, you must answer a riddle correctly. If your answer is cor- rect, the gate swings open, granting you passage. But if you answer incorrectly, the gate remains closed, and you must search for an alternative route. In Python, it would look like this: riddle_answer = In this code snippet, the condition riddle_answer == "moonlight" checks if the variable riddle_answer holds the correct answer. If it's true, the first code block is executed, and the gate opens. Otherwise, the second code block is executed, indicating the need to find an alternative route. Remember, the colon (:) and proper indentation play crucial roles in Python's syntax. The indented block after the if statement is the code that will be ex- ecuted if the condition is true. Keep those indents tidy, my friends! 2. The "else" Clause: Embracing Alternatives What if there's an alternative path to take when the condition in the "if" statement is false? Fear not, for the "else" clause comes to the rescue! It provides an alternative code block to be executed when the con- dition is false. Imagine you're attending a grand masquerade ball, and the dress code is strictly formal. If you adhere to the dress code, you'll be greeted with elegance and admiration. But if you deviate from the dress code, well, prepare for some awkward stares and whispers! Let's bring this glamorous scenario to life in Python: eee ema sr In this code snippet, the condition * dress_code == "formal" is checked. If it's true, the first code block is executed, and you make a grand entrance with your formal attire. If the condition is false, the sec- ond code block is executed, and you face the conse- quences of not adhering to the dress code. The "else" clause allows us to consider alternative paths in our code and make decisions based on different conditions. It adds flexibility and expands our options, just like having a backup plan at a mas- querade ball! 3. Nested "if" Statements: Unlocking Hidden Chambers Sometimes, our decision-making scenarios require multiple layers of conditions. In such cases, nested "if" statements come to our aid. They allow us to ex- plore hidden chambers within our code and unveil even more possibilities. Imagine you're an intrepid explorer navigating an ancient labyrinth. Along your journey, you en- counter mysterious doors, each requiring a unique key to unlock. If you possess the right key, you un- lock the door and continue your adventure. But if the key doesn't match, you must backtrack and search for another path. Let's venture into this labyrinthine scenario in Python: Pree Cee ae oa tems In this code snippet, we have nested "if" statements. The outer "if" statement checks if the ‘door1_key* matches the value ‘"golden"’. If it's true, the first code block is executed, and you unlock the first door. Inside this block, there's another "if" statement that checks if the ‘door2_key* matches the value "silver" >. If it's true, the nested code block is ex- ecuted, and you unlock the second door, revealing the path to unimaginable treasures. If any condition evaluates to false, the corresponding code block is skipped, leading you to alternative paths. Nested "if" statements allow us to explore multiple layers of conditions and uncover hidden chambers within our code, just like unraveling the secrets of an ancient labyrinth! Expanding Choices: The "elif" Statement Life is full of choices, and so is programming! Some- times, we need to consider multiple conditions and choose the appropriate path based on those con- ditions. That's where the "elif" (short for "else if") statement comes into play. Imagine you're a superhero with the ability to con- trol the weather. You receive requests from people around the world to change the weather condi- tions in their area. Each request comes with specific conditions and a desired outcome. As the mighty weather controller, you must evaluate the condi- tions and grant their requests accordingly. Let's bring this epic superhero scenario to life in Python: errs Poot reet ne crash tata) mete print( ) Sree ec este Pista bee acest Tete In this code snippet, the outer "if" statement checks if the * location* matches the value ‘"London"’. If it's true, the code block is executed, and you evalu- ate the weather conditions. Inside this block, multi- ple "elif" statements allow you to consider different weather conditions and grant the requests accord- ingly. If none of the conditions evaluate to true, the corresponding code block is skipped, indicating that the requested weather conditions are beyond your control. If the initial condition evaluates to false, the alternative code block is executed, acknowledging the priority you give to London. The "elif" statement allows us to consider multiple conditions and choose the appropriate path based on those conditions. It's like having a portfolio of superpowers to fulfill the diverse requests of people around the world! Logical Operators: The Secret to Complex Decisions In the realm of decision making, simple choices are not always enough. Sometimes, we need to com- bine multiple conditions and perform more complex evaluations. That's where logical operators come into play, unleashing the power of Python's deci- sion-making abilities! 1. The "and" Operator: Uniting Conditions for Suc- cess Imagine you're a treasure hunter exploring a hidden cave. The treasure lies at the intersection of two se- cret passages. To reach the treasure, both passages must be open. If either one is closed, the treasure re- mains elusive. In Python, the "and" operator allows us to combine conditions and ensure that they all evaluate to true. Let's embark on this thrilling treasure hunt in Python: ( ce In this code snippet, the conditions ~ pas- sage_l_open* and ‘passage_2_open* are both true. The "and" operator checks if both conditions are true, and if so, the first code block is executed. If either one or both conditions are false, the second code block is executed. The "and" operator is like a key that unlocks hidden treasures, ensuring that all necessary conditions are met for success! 2. The "or" Operator: Choosing the Path of Least Resistance Sometimes, we face situations where multiple con- ditions are possible, and we need to choose the path of least resistance. That's where the "or" operator comes in handy! It allows us to check if at least one of the conditions is true. Imagine you're planning a picnic, and you want to go if the weather is either sunny or partly cloudy. If both conditions are false, you decide to stay home and watch movies instead. Let's plan this delightful picnic in Python: Paid try Perris Pater ( 4 In this code snippet, the condition * weather == "sunny"” is true, and the ‘cloudy variable is false. The "or" operator checks if at least one of the con- ditions is true. Since the first condition evaluates to true, the first code block is executed. If both condi- tions were false, the ‘else * block would be executed. The "or" operator allows us to consider multiple con- ditions and choose the path of least resistance, just like making a decision based on the weather condi- tions for a perfect picnic! 3. The "not" Operator: Flipping the Switch Sometimes, we need to negate a condition and eval- uate the opposite. That's where the "not" operator comes into play. It allows us to flip the truth value of a condition. Imagine you're organizing a secret meeting, and you want to ensure that only authorized members at- tend. You create a list of authorized members and check if a person's name is not on the list. If their name is not authorized, you deny them access to the meeting. Let's bring this clandestine scenario to life in Python: ide e4- so le aE Plage Baer Eset Mu ed In this code snippet, the condition * attendee not in authorized_members* checks if the name of the ‘attendee* is not in the list of ‘authorized_mem- bers * . If it's true, the first code block is executed, and access to the meeting is denied. If the condition is false, indicating that the attendee's name is on the authorized list, the second code block is executed, granting access to the meeting. The "not" operator allows us to flip the truth value of a condition, adding another dimension to our deci- sion-making abilities. Putting It All Together: Complex Decision-Making Now that we have mastered the art of making de- cisions, it's time to put our skills to the test and tackle more complex scenarios. By combining con- ditional statements, logical operators, and creative thinking, we can navigate intricate decision-making challenges with ease. Let's embark on an epic adventure and explore an example that combines everything we've learned so far: peme oas promt aed In this code snippet, we check two conditions: ~ age >= 18° and ‘is_student’. The "and" operator en- sures that both conditions are true in the first “if* statement. If the first condition is true and the sec- ond condition is false, the second ‘elif* statement is executed. If neither condition is true, the *else* block is executed. By combining conditional statements, logical opera- tors, and creative thinking, we can conquer complex decision-making challenges and find the most suit- able path in any scenario. Nested Decision-Making: A Journey Within Sometimes, our decision-making scenarios require even deeper layers of conditions and alternative paths. In such cases, nested decision-making struc- tures allow us to explore intricate possibilities and make complex choices. Imagine you're an adventurer exploring a vast dun- geon filled with magical creatures. Each creature has unique characteristics, and you must react accord- ingly. You encounter a dragon, and based on its size, you react differently. If it's small, you approach cau- tiously. If it's medium-sized, you engage in combat. And if it's large, you retreat and seek an alternative route. Let's immerse ourselves in this captivating dungeon adventure in Python: dragon_size = eC ese print( elif dragon_size == Petia CRM eum Se Mee print( print( In this code snippet, we have nested decision-mak- ing structures. The outer * if’ statement checks the “dragon_size* and determines the appropriate ac- tion based on its value. If the dragon size is "small," the first code block is executed. If it's "medium," the nested ‘elif* statement is evaluated, and the sec- ond code block is executed. If it's "large," the next nested ‘elif’ statement is evaluated, and the third code block is executed. If none of the conditions are true, the ‘else* block is executed, indicating an en- counter with an unknown creature. Nested decision-making structures allow us to ex- plore intricate possibilities, react appropriately to di- verse scenarios, and make complex choices on our adventurous journeys. Conclusion Congratulations, my decision-making adventurers! You have journeyed through the exciting world of control flow and decision making in Python. We explored the power of the "if" statement, embraced alternatives with the "else" clause, ventured into multiple conditions with the "elif" statement, and unleashed the power of logical operators. In this extended chapter, we learned how to make decisions in Python and control the flow of our code. We combined operators, explored structures, and tackled complex decision-making challenges. Remember to choose your paths wisely and let your code adapt to different scenarios. But our Python adventure doesn't end here! Get ready for the next chapter, where we'll uncover the magic of loops and iteration, allowing our code to repeat tasks, perform mesmerizing feats, and con- quer even more extraordinary challenges! condi- tions, used logical nested decision-making Learn More with Our App! To enhance your learning experience, we have devel- oped additional challenges a mobile app where you can find resources, tutorials, and coding related to Python and other programming languages. Scan the QR code below to download the app and start exploring! To check the output click here and run the program Python Compiler Quiz 1. What is a variable in Python? a) A reserved word in the Python language b) A container that stores data c) A function that performs a specific task d) A statement that controls program flow 2. Which of the following is a valid variable name in Python? a) 123magic b) magic!spell c) magic_spell d) $magic_spell 3. What is the data type of the variable in the follow- ing code? a) String b) Integer c) Boolean d) Float 4. What is the output of the following code? a)15 b) 510 c)5 d) Error 5. What is the correct way to convert a string to an integer in Python? a) str_to_int() b) convert_to_int() c) parse_int() d) int() 6. What is the result of the expression 10 / 3 in Python? a) 3.33 b) 3 c) 3.0 d) Error 7. What is the purpose of the input() function in Python? a) To display a message on the screen b) To perform mathematical calculations c) To wait for user input d) To define a new variable 8. What is the data type of the result in the following code? a) String b) Integer c) Boolean d) Float 9. What is the correct way to concatenate two strings in Python? a) str1 + str2 b) str1 . str2 c) stri1 - str2 d) str1 * str2 10. What is the purpose of the len() function in Python? a) To calculate the length of a string b) To perform logarithmic calculations c) To convert a string to lowercase d) To remove whitespace from a string Answers: 1.b) Acontainer that stores data 2. c) magic_spell 3. b) Integer 4. d) Error 5.d) int() 6. a) 3.33 7. c) To wait for user input 8. d) Float 9.a) str1 + str2 10. a) To calculate the length of a string CHAPTER 4 Loops and Iteration: The Never-Ending Adventures Welcome, brave adventurers, to the captivating world of loops and iteration in Python! Get ready to embark on an exhilarating journey where we will unravel the secrets of repetition, conquer formida- ble coding challenges, and unlock the true power of our code. Prepare yourselves for a chapter filled with endless possibilities, exciting examples, and practi- cal applications that will take your programming skills to new heights! The Journey Begins: Embracing Repetition Imagine yourself brimming with in a vast and mys- terious forest, hidden treasures waiting to be discovered. As an in- trepid explorer, you realize that searching for these treasures requires you to visit multiple locations re- peatedly. This concept of repetition lies at the core of loops in programming. Loops enable us to execute a block of code multiple times, making our programs more dynamic and versatile. So, tighten your back- packs and let's dive into the captivating world of loops with some thrilling examples! In Python, we have two primary loop structures: the "while" loop and the "for" loop. Each has its unique charm, offering different ways to embrace repeti- tion. Let's begin our adventure by exploring the power of the "while" loop! 1. The “while" Loop: The Never-Ending Adventure Imagine yourself on an epic quest to find the leg- endary Fountain of Youth. This quest will require you to search tirelessly until your goal is achieved. The "while" loop in Python is your trusted compan- ion in such never-ending adventures! Let's bring this thrilling quest to life in Python: ome meesy er mre st i ) In this code snippet, the * while’ loop contin- ues until the condition *found_fountain~ becomes “True *. Inside the loop, you continue your quest, printing messages to indicate your ongoing search. The loop keeps repeating until the Fountain of Youth is found and the condition becomes true. Once the goal is achieved, the loop is exited, and the code after the loop is executed. Remember to update the variables inside the loop to eventually exit the loop and prevent an infinite loop scenario. After all, you don't want to be stuck in your quest forever, right? 2. The "for" Loop: Conquering Challenges Imagine yourself as a valiant knight, tasked with overcoming a series of formidable challenges. Each challenge represents a new opportunity to prove your courage and skill. The "for" loop in Python em- powers you to conquer these challenges with ele- gance and efficiency! Let's embark on this heroic journey in Python: Sa challenge in challenges ( {challenge} !") In this code snippet, the * for’ loop iterates over each ‘challenge in the ‘challenges* list. Inside the loop, you prepare to face each challenge, printing a customized message based on the current chal- lenge. The loop continues until all challenges have

You might also like