0% found this document useful (0 votes)
18 views

Python_for_Absolute_Beginners_2024

The document is a comprehensive guide titled 'The Ultimate Beginner's Guide to Learn Python Programming,' aimed at helping absolute beginners learn Python with a focus on data science and web programming. It covers fundamental concepts, advanced topics, and practical applications, providing a clear and engaging learning experience with numerous examples and exercises. The author emphasizes the importance of hands-on practice and offers additional resources for readers to enhance their programming journey.

Uploaded by

khanquility
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
18 views

Python_for_Absolute_Beginners_2024

The document is a comprehensive guide titled 'The Ultimate Beginner's Guide to Learn Python Programming,' aimed at helping absolute beginners learn Python with a focus on data science and web programming. It covers fundamental concepts, advanced topics, and practical applications, providing a clear and engaging learning experience with numerous examples and exercises. The author emphasizes the importance of hands-on practice and offers additional resources for readers to enhance their programming journey.

Uploaded by

khanquility
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 453
Peer o Se uae ‘The Ultimate beginner's guide to Learn Python Programming with extensive Coverage on Data "Science and web Programming BONA AKUBUE Copyright © 2024 NanoEdge International Ltd Copyright © 2024 NanoFdge Intl Ltd. All rights reserved. No part ofthis book may be reproduced in any form or by any electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without permission in writing from the publisher. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented, However, the information contained in this bookis sold without warranty, either express or implied. Neither the author, nor NanoEdge Int'ILtd, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. First published: February, 2024, Published by NanoEdge Int'l Lta Lagos, Nigeria, CONTENTS Copyright Foreword Preface Introduction Chapter 1: PYTHON SYNTAX Chapter 2: DATA TYPES ‘Chapter 3: OPERATIONS IN PYTHON Chapter 4: CONTROL FLOW STATEMENTS Chapter 5: LOOPING STATEMENTS Chapter 6: STRINGS Chapter 7: LISTS Chapter 8: TUP Chapter 9: DICTIONARIES Chapter 10: SETS Chapter 11: FUNCTIONS Chapter 12: MODULES Chapter 13: FILES (Chapter 14: OOP IN PYTHON (Chapter 15: EXCEPTIONS Chapter 16: TESTING Chapter 17: ASYNCHRONOUS PROGRAMMING WITH ASYNCIO Chapter 18: RESUESTS IN PYTHON Chapter 19: WEB SCRAPPING IN PYTHON 1apter 20: LOG 1H Chapter 21: MULTITHREADING IN PYTHON 22: TI DESCRIP Chapter 23: EXPLORING THE POWER OF DATA SCIENCE Chapter 24: BUILDING WEB APPS WITH DJANGO CONCLUSION FOREWORD It is with great pleasure that I introduce you to this comprehensive guide, "Python for Absolute Beginners: The Ultimate Beginner's Guide to Learn Python Programming with Extensive Coverage on Data Science and Web Programming.” In today's digital age, Python stands out as a versatile and accessible language, making it an ideal choice for beginners eager to embark on their coding journey. What sets this book apart is its commitment to demystifying Python programming for absolute beginners, ensuring that the intricacies of coding are presented in an approachable and engaging manner. The author's dedication to providing a solid foundation in Python is evident from the very first pages. From basic syntax to more advanced concepts, each chapter builds upon the last, creating a seamless learning experience. The inclusion of extensive coverage on data science and web programming reflects the practical applications of Python, making it a vahiable resource for those aspiring to explore these dynamic fields. One of the book's strengths lies in its clarity and simplicity. The author has successfully distilled complex programming concepts into digestible and easy-to-understand explanations, ensuring that even those with no prior coding experience can grasp the fundamentals with ease. The inclusion of real-world examples and hands-on exercises further enhances the learning process, allowing readers to apply their newfound knowledge in practical scenarios. Whether you're a student looking to delve into the world of programming, a professional aiming to enhance your skill set, or simply an enthusiast eager to understand the language powering today's technological advancements, this book is your gateway to Python mastery. The step-by-step approach, coupled with a focus on data science and web programming, ensures that readers not only learn the fundamentals but also gain the skills necessary to tackle real- ‘world projects. As you embark on this exciting journey through “Python for Absolute Beginners," I encourage you to embrace the challenges and celebrate the victories. Remember that every line of code you write is a step closer to unlocking the vast possibilities that Python offers. May this book serve as a guiding light, illuminating the path to a rewarding and fulfilling journey in the world of Python programming. Prof. Martin Anikwe Director, International Linkages and Collaborations Enugu State University of Science and Technology, Nigeria PREFACE Learning Python was quite a challenge for me, to be honest. Back in the day, there were two versions to choose from: Python 2 and Python 3, and I struggled with deciding which one to go for. While I was grappling with the version dilemma, | also faced difficulties finding the right learning materials to guide me through the process. Most of the books I came across were either not comprehensive enough or simply hard to comprehend. Some were overly lengthy, filled with unnecessary details, and difficult to follow. Others lacked sufficient examples and exercises for practice. Sure, the official documentation was helpful, but it wasn't comprehensive enough and lacked real-world examples. I scoured countless books, documentation, and online blogs in my pursuit of Python knowledge. Although I stumbled upon a few helpful books, I still felt there was a need for more. I always wished for a single book that would guide a novice like me from start to finish without having to seek additional resources. Today, 1am glad to present to you that book. My goal is to help you reduce your learning curve by giving you a book that is not only easy to understand but beginner- focused. This book is written in a clear and concise style, with plenty of examples and exercises to help you practice your new skills. So many practical tips and tricks were included throughout the book to help you avoid common pitfalls and write clean and efficient code. This book covers all the fundamental concepts of Python programming such as data types, variables, control structures, functions, and modules. Also, more advanced topics like object-oriented programming, file handling and asynchronous programming were also covered. Now, if you're still wondering whether Python is a good choice, especially if you're new to programming, let me assure you that it absolutely is! Python is a powerful and versatile language with a wide range of applications, from web development and data analysis to scientific computing and artificial intelligence. Who Is This Book For? If you've never programmed before and want to start programming in Python, you've made an excellent choice. Whether you're interested in pursuing a career in programming or just want to learn a valuable new skill, this book is the perfect starting point. How To Use This Book The truth is, learning programming can be overwhelming, and many people lose interest along the way. Like any other profession, programming requires a serious level of commitment. To get the most out of this book, my advice is not to skip any part of it. Although the chapters are independent, if you're a complete beginner, I recommend reading them sequentially. However, if you're an experienced programmer looking torefresh your memory, feel free to jump to any chapter that piques your interest. Programming is a practical subject and not something you can memorize or read like the novel. So, code along as you read the book. Many times, you might think you understand something, only to draw a blank when asked to put it into practice. By typing in the code examples on your own computer, you'll solidify your understanding and avoid any false sense of familiarity. So, punch in every code you see or read on your computer. There are lots of examples and exercises that will help you master the topics. I encourage you to try out all the exercises by yourself to enable you build confidence in yourself, I encourage you to tackle all the exercises on your own to build confidence in your abilities. However, if you find yourself struggling with a particular problem, feel free to consult the solutions available on the book's website or GitHub repository. By the time you reach the end of this book, you'll have gained sufficient skills to tackle real-world problems, Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning, Terminal commands follow the UNIX format and the dollar ($) sign is not part of the command: $ python3 --version Ablock of code is set as follows: if num % 2 == 0: print(""This is an even number.”) Important notes and coding tips appear in as follows: ProTi Thisis an important information. Source Codes The source code for this book and solutions for exercises are available at https://bonaakubue.com/downloads. Also, you can find the GitHub repository accompanying this book through this link. Bonus Materials This book comes with free bonus materials and cheats sheets. You can access these resources through https:// bonaakubue.com/downloads. Questions While you're reading this book, if you have any questions, don't hesitate to reach out via email at python-book- questions@bonaakubue.com, I'm here to help, and I'll make sure to respond promptly to your inquiries. Additionally, Tencourage you to sign up for my free newsletter at https://bonaakubue.com/subscribe. By subscribing, you'll gain access to programming tips, insightful articles, and updates on this book. I's a great way to stay connected and further enhance your programming journey. Reader Feedback ‘Your feedbackis incredibly valuable for the ongoing improvement of this book. 1 genuinely want to hear your thoughts, whether it’s about what you enjoyed or any areas you felt could be enhanced. Please don't hesitate to reach out by sending an feedback@bonaakubue.com, and kindly mention the book title in the subject line of your message. Your input will be greatly appreciated as I strive to make this book even better. Errata Great care has been taken to ensure the accuracy of this book. However, if you happen to come across any errors, ‘whether in the text or the code, please help us by notifying us via email at python-book-errata@bonaakubue.com. Your attention to detail and assistance in identifying any mistakes will be highly appreciated. INTRODUCTION “Talk is cheap. Show me the code.” -Linus Torvalds Imagine you work in marketing agency where your weekly responsibility involves sending email summaries to multiple clients, detailing their social media performance. These summaries encompass various metrics such as follower growth, engagement rates, and future strategies or plans. Because you're manually composing and sending these emails, it is not only time-consuming but also stressful. There are occasions when certain clients are overlooked, or vital information is omitted from the summaries. Despite your dedication and determination, you can't seem to overcome these recurring blunders. It seems as if you're simply incompetent for the job. Now, imagine that you have an experience in computer programming! You can leverage on your programming skills to automate the email sending process. By writing a simple computer program, you can instruct the computer to perform these tasks for you. But this requires the knowledge of a programming language and raises the question of which programming language tolearn. Sure, there are many programming languages available today, but Python stands out as a simple, elegant, powerful and. multipurpose programming language that you can use for a wide range of programming tasks. Python Programming Python is a general-purpose programming language originally designed by Guido Van Rossum in the 1980s but released in 1991. It was named after his favourite show, Monty Python's Flying Circus. Itis an open-source programming language and is managed by Python Software Foundation (PSF). As an open-source programming language, you can access, modify, and distribute it, even for commercial purposes. Python is an interpreted language, which means that you do not need to compile your programs before running them. Instead, the Python interpreter reads and executes your code, translating them into machine codes. Also, Python is an object-oriented programming language, meaning you can organize your programs in classes and objects. This way, you can write programs that are not only reusable but easy to maintain and update. Why Python? Python is widely used in different fields of studies and industries for problem-solving and creating innovative software solutions. So many projects have been successfully implemented with Python in the areas of sciences, education, health care, hospitality and entertainment. Surely, there are lots of other programming languages with outstanding features, but Python stands out in the following ways. 1. Simple and easy to learn One of the significant objectives of Python as a language is readability and ease of expressing concepts in fewer lines of code. The syntaxis concise, clear and easy to read. Python is not only easy to read but to learn. This makes it an ideal programming language for beginners. Also, experienced programmers in other languages can easily pick up the language and start writing programs with it almost immediately. Surely, the simplicity of learning Python explains why it is being used to teach children the principles of programming. 2. Versatility One of the reasons behind the popularity of Pythons its versatility. It can be used for a wide range of projects including web development, data visualization and analysis, game development and much more. ‘Many top companies across the world are either using Python or implementing a part of their application using Python. Companies like Google, DropBox, Uber, Netflix, BitLy, Instagram and YouTube have used or are still using Python in their technology stacks. Also, Python scripts can easily be integrated with applications written in other programming languages like Java, C/C+ + and NET languages, making it an excellent tool to glue together large software components. 3. Online Community Python has a vast and supportive online community with lots of experienced developers willing to help as you journey into programming and beyond. There are also tons of educational resources available in form of online documentation, forums, mailing lists and conferences around the world. These communities provide you with opportunities to connect with other programmers, facilitating the exchange of ideas and knowledge. 4. Efficiency Productivity is of the essence to any programmer. Programs written with Python are considerably shorter than the equivalents in programming languages such as Java and C++. Hence, you can write more programs in a lesser period compared to most other programming languages. In other words, it helps you do more with less time. This not only makes you more efficient but also more productive. As an interpreted language, you get an immediate result whenever you make changes in the program. There isno need for compilation and recompilation that is obtainable in compiled languages. This explains why Python is used for rapid application development (RAD) and as a tool for prototyping. 5, Extensive libraries Python has vast libraries and third-party tools that can make things easier. Apart from the numerous standard libraries that come with Python, there are also myriads of powerful and tested third-party tools freely available at your disposal. These are pre-written codes that solve a particular problem and with these libraries, you don't have to reinvent the wheel as you can easily integrate these libraries into your program. Some of the popular libraries in Python include Panda for data analysis, matplotlib for visualization, Sci-kit learn for machine learning and much more. Installing Python Python is free and can be downloaded from its official website - python.org. There are different Python releases for different operating systems, so be sure to download the latest stable version for your operating system. Once you've downloaded the Python installer for your operating system, you should run it to initiate the installation process. Follow the installation wizard carefully, paying attention to any prompts or options provided. ProTip An important step, especially for Windows installation is to select the option that adds Python to your system's PATH. This step ensures that your operating system recognizes Python's location, making it easier to use from the command line or terminal. After completing the successful installation of Python on your computer, you gain access to an interactive environment where you can directly interact with Python and execute commands in real-time. This interactive environment is commonly referred to as a Python interpreter or shell. ‘You can initiate the interactive session by simply typing the word "python" or "Python3" in your terminal or console. This will launch the Python interpreter, allowing you to interactively execute Python code. The version of Python installed on your device will be displayed, followed by the appearance of the chevron symbol (>>) or three arrows, indicating line of input, where you can enter Python code and execute it interactively. However, ifit’s not installed on your device, you will get an error message indicating “command not found.” This interactive session is also known as REPL, which stands for read, evaluate, print, and loop. With REPL you can interact with the Python interpreter. You can directly type Python codes and have them run immediately. Lines that start with triple arrows are for inputs while lines without arrows are for outputs from the interpreter. ‘You can write some codes to perform some simple calculations and immediately after you hit the enter key, the interpreter will run the codes and display the result in the terminal. To exit the interactive session, simply type CTRL Z, aS [MSC v.1937 64 bit (AMD64)] on win: Pe tetist Writing programs with the IDEs IDE stands for Integrated Development Environment. Itis a graphical user interface that allows programmers to write, edit, run and debug and debug programs in one place. IDEs provide a convenient way to write programs and most of the code you will ever write will be done using this tool. Unlike the interactive session where code vanishes upon exiting, IDEs enable the preservation of your programs by saving them into files. There are so many IDEs you can use for programming in Python including Sublime Text, PyCharm, Visual Studio Code and even the IDLE that is shipped with Python Interpreter. However, Visual Studio Code stands out as one of the most popular and widely used IDEs by developers. It runs on Windows, Linux and macOS. You can get this software from the Visual Studio website for free. Simply, download and install it on your computer. Once you have installed Visual Studio Code, create a new file by choosing the "File" ->"New File" option. Type the following code in the text editor in the editor provided by the IDE and save the file with a py extension to indicate that it is a Python script or file. eaters to) Use the "Run" option to execute your Python code in the IDE. ProTip When you install Visual Studio Code (VSCode) for the first time, it comes with basic support for a variety of programming languages and features. However, to enhance the development experience specifically for Python, you need to install the Python extension, To install the Python extension for Visual Studio Code, navigate to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side. Look for the official "Python" extension developed by Microsoft and click the “Install” button. Once the installation is complete, you may need to reload VSCode to activate the extension. After reloading, youll have access to a range of Python-specific features, including intelligent code completion, debugging support, linting, and more. CHAPTER 1: PYTHON SYNTAX “The most disastrous thing that you can ever learn is your first programming language.” -Alan Kay Imagine that you are new to a foreign country with a different language and the only way to communicate with the locals is through their own language. Simply understanding the meanings of individual words is insufficient; you must also comprehend how to combine the words to construct coherent statements. However, if you pay good attention, you will see a pattern. You will discover that there are certain rules to be observed when trying to put the words together into statements. These rules are called syntax. Learning outcome In this chapter, you will learn: + ‘Towrite comments + Touse indentations and white spaces for code blocks and enhance readability + Toassign values to variables Introduction In every language, whether it is a natural language like English, French, or Spanish, or a programming language, there are rules that govern its structure, In natural languages, these rules are referred to as grammatical rules, while in programming languages, they are known as syntax. The syntax is the rules that govern how you write programs in a programming language. Without adhering to these rules, it's impossible to make meaningful statements in any language. Interestingly, the syntax for Python is simple and adhering to proper syntax is crucial in ensuring that the code is valid, readable, and can be executed without errors. Some key aspects of Python syntax include: + Comments + Indentation + Variables + Data Types + Control Flow + Functions Comments Comments are used to document code and provide explanations. They are not executable and are ignored by the interpreter. In Python, any piece of text that is preceded by a hash symbol (#) is considered a comment. To write a single-line comment in Python, simply type a hash symbol (#) followed by the comment text. ‘writing a single line comment ¥my first program ‘To write comments that spans across multiple lines, you can use triple quotes ("") to enclose the comment text. This type of comment is called a multiline comment. This is a multi-line comment Indentations and white spaces In Python, indentations and white spaces are used to indicate the grouping and hierarchy of code blocks. Instead of relying on curly braces ({ }) or other symbols to delimit code blocks, Python employs indentation as the primary ‘method for defining its code structure. Indentation is typically done using four spaces or a tab character and is used to indicate the beginning and end of code blocks, such as loops, conditional statements, and function definitions. #indentations and spaces for num in [1,2,3,4,51 #print num, print(aum) Here, the indentation is used to indicate statements under the for statement should be treated a single unit or a code block. Variables ‘Variables are used to associate a name with a value. To declare a variable in Python, a name is provided followed by an assignment operator'~' and the value. Take a look at this example: num= 5 Inthe example, a variable named num is assigned to the value 5. By assigning a value to variable, you can refer to a given value through the name of the variable, result = num +4 print(result) Output 9 Here, the variable num is used to refer to the value of 5. Hence, 5 + 4 will give 9. In some programming languages, it is common to define a variable and assign its value later in the program. However, Python requires variables to be assigned immediately upon declaration. Also, unlike many other languages where variables are declared with a specific type, Python does not require variable declaration. Variables are dynamically typed, meaning they are assigned a value without explicitly stating their type. ProTip A variable can be assigned an integer type and subsequently reassigned a string type. Upon assigning a new value to the variable, it replaces the previous value associated with it. Choosing a variable name While you have the freedom to choose any name for your variables, it is essential to ensure that names accurately describe the associated value or object. By using meaningful and descriptive variable names, you can make your code more understandable, allowing easier comprehension for yourself and others who may read or maintain your code in the future. Pro Tip You should avoid using single letters or meaningless names as variables names of variables. Take a look at the following statements: age= 25 a=25 Using the variable name "age" instead of simply “a" would be a more suitable choice for enhancing code readability. By using age’ as the variable name, it provides clear and descriptive information about the value it represents, making the code easier to understand. Overall, here are key things to keep in mind when choosing a variable name: Variable names can contain letters, numbers and underscore characters, Variable names are case-sensitive which means that the name adam is different from Adam. Variable names cannot begin with a number or contain special characters like @, §, %,* Variable names cannot contain spaces. Reserved words or keywords cannot be used as variable names. Summary In this chapter, you learnt how to write comments. You learnt how to use proper indentations and white spaces. Additionally, you learnt how to assign values to variables and the rules for naming variables. Practice Exercises What are the reasons for the popularity of Python? How is python interpreted? What are the applications of Python? Mention 5 companies using python in their tech stack How do you write comments in python? aware Write a Python program that displays “Hello world” CHAPTER 2: DATA TYPES “t's difficult to imagine the power that you're going to have when so many different sorts of data are available.” - Tim Berners-Lee Data is actually a huge part of our everyday life. Whether we're shopping for groceries, having a chat with our friends, or just mindlessly scrolling through our social media feeds, we're constantly using or creating data. If you take a moment and reflect on this, you will be amazed to discover how involved data is in everything we do. Given the abundance of data around us, it becomes essential to organize and categorize them in order to make meanings from them. In the realm of computers, data is classified into different types, also known as data types. Learning outcome In this chapter, you will learn: + Basic data types like numeric, strings, booleans and sequences. + Various numeric data types including integers, floats and complex numbers. + Sequences or collections such as lists, tuples, dictionaries and much more. + How to use the print() and input() built-in functions. Introduction Consider the number 2 and the word ‘hello.’ While both qualify as data, however, they differ in terms of the operations applicable to them. You can perform mathematical additions on numbers, but you cannot do the same to a piece of text. Python provides support for a diverse range of data types, encompassing numbers, strings, lists, tuples, dictionaries, and more. This versatility in Python empowers programmers to efficiently and effectively handle various types of data. The following categorization presents various data types in Python: Numeric Strings Booleans Sequences Numeric Numeric data types consist of integers, floats, and complex numbers. Integers represent whole numbers without any decimal places. Floats, on the other hand, are numbers that include decimal places. Complex numbers are a combination of real and imaginary parts, allowing for operations involving both components. Here are examples of numeric data types in Python: Integers 1,2,5,10, -100 Floats 1.05, -99.5, 0.005 Complex 2-1),4- 6) Integers Integers are simply whole numbers. They can be positive or negative but without fractional or decimal parts. Numbers like 1, 777,101 and even 0 are Integers. However, integers are not only numbers in base 10, but also include whole numbers in other number systems like - binary, octal or hexadecimal. Pro Tip Number systems are ways of representing numbers, Naturally, we count in the decimal number system. Here, the smallest digit is 0 and the largest is 9. In computing, numbers are represented internally in computers in binaries, At the basic or machine level, computers only understand instructions in the form of zeros and ones. Programming languages such as Python allow programmers to write codes in letters, numbers and symbols, but these instructions are converted to streams of Os and 1s. There are essentially four kinds of number systems used in computing and programming in particular and they include: . Decimal » Binary . Hexadecimal “ Octal Now, let's briefly explain the important number systems that you may likely encounter while working with integers in python. Binary Numbers A binary number is a number expressed in base 2 or binary number system. Binary numbers have two digits -O and 1. Octal Numbers Octal numbers are numbers expressed in base 8 or octal number system. In this number system, the digits range from Oto7. Decimal Numbers These are numbers expressed in base 10. Numbers in base 10 consist of 10 digits with 0 being the smallest and 9 being the largest. Hexadecimal Numbers Hexadecimal numbers are numbers in base 16. They have 16 digits with 0 being the smallest and F being the largest. The digit F is equivalent to 15 in the decimal number system. The table below presents the digits available in the binary, octal, decimal and hexadecimal number systems. Binary octal Decimal Hexadecimal o ° o o 1 1 1 1 2 2 2 3 3 3 es ee ee ee Floats Floats or floating point numbers are numbers that contain decimal points. They can be positive or negative. The following numbers are examples of floating-point numbers: + 0.004 + -150 + 23,00045 Complex Numbers Similar to mathematical concepts, complex numbers consist of a real and an imaginary part. For example, 2 + Sjisa complex number with 2 being the real part and 5 being the imaginary part. With python, you can easily extract the real and imaginary parts using the real and imag attributes of the number as shown below: number = 2 + 5) print(number.real) print(number.imag) Outputs: 2.0 5.0 Number Type Conversion Number type conversion is a fundamental aspect of Python programming. The need for type conversion often arises ‘when you want to perform operations or comparisons between different numeric types. To achieve this, Python provides specific Functions that enable you to convert numbers or even strings into a preferred numeric type. These functions are + intQ: Converts a value to an integer. + float(): Converts a value to a floating-point number. + complex(): Converts a value to a complex number. num = 20 int_num = int(num) print(int_num) float_num = float(num) print(float_num) complex_num = complex(num) print(complex_num) Outputs: 20 20.0 (20+0) Binary, Octal and Hexadecimal Conversions ‘You have the flexibility to convert between binary, decimal, octal, and hexadecimal representations using the bin(), oct(), hex(), and int() functions. num =9 #Binary print(bin(num)) #Octal print(oct(num)) #Decimal print(int(num)) #Hexadecimal print(hex(num)) Outputs: ob1001 0011 9 ox9 Mathematical functions These are functions that are used to perform mathematically related operations on numbers. Some of these functions include: abs() pow() round() ‘math.trunc() math floor) math.ceil() abs() This function returns the absolute value of a given number. It strips of the the unary signs in a number. Pro Tip: Unary signs refer to the use of positive (+) or negative (-) symbols to denote the sign of a number in a unary numeral system. print(abs(-10)) print(abs(1.05)) print(abs(+0.5)) Outputs: 10 1.05 os pow() This function returns the value corresponding to the number raised to a given power. It accepts two arguments, the first being the number that you want to exponentiate, and the second being the power. print(pow(2,2)) print(pow(2,3)) print(pow(2,4)) Outputs: 4 8 16 round() This function rounds or approximates a number to the nearest whole number. In other words, it takes a decimal or fractional value and adjusts it to the closest integer value. If the decimal part is 0.5 or greater, the number is rounded up; ifit's less than 0.5, the number is rounded down. print(round(10.2)) print(round(10.5)) print(round(10.6)) print(round(10.9)) Outputs: 10 10 u u math.trunc() This is used to truncate a floating-point number towards zero, effectively removing the decimal part of the number and returning the integer part. However, to use this function, you have to import the math module. import math print(math.trunc(10.2)) print(math.trunc(10.9)) Outputs: 10 10 math.floor() The function operates similarly to the trunc() function. It removes the decimal part of a floating-point number, effectively truncating the value and returning a whole number. Unlike rounding, which may round up or down based on the fractional part, this function simply discards the decimal component, resulting in the integer part of the original floating-point number without any rounding. import math, print(math-floor(10.2)) print(math-floor(10.9)) Outputs: 10 10 math.ceil() This function approximates a floating-point number to a whole number, greater than the integer part of the number. import math print(math.ceil(10.2)) print(math.ceil(10.9)) Outputs: M1 1 Formatting numbers ‘The format() method allows you to control how numbers, strings, or other data types are formatted for display. It's particularly helpful when you want to display numbers in a specific way, such as controlling the number of decimal places, adding commas as thousand separators, displaying numbers in scientific notation, or specifying padding for alignment in strings. Take a look at this example: ¥rounding to 2 decimal places .2f) format(1.35) print(result) result #rounding to 1 decimal place 1f)format(1.35) print(result) result including per cent to a number result = '{}96'-format(1.35) print(result) Outputs: 1.35 14 1.35% Random Numbers The random module provides a collection of functions for generating random numbers and conducting various randomization tasks. Whether you're developing simulations, games, statistical models, or cryptographic applications, the random module serves as your essential tool for infusing an element of unpredictability. Here are some of the popular methods in the random module. randint() ‘This method is used to generate random integer numbers. To use this method, you need to provide arguments that specify the range within which the random integers should be generated. from random import randint num = randint(1,5) print(num) random() This method generates floating point numbers within the range of 0.0 (inclusive) and 1.0 (exclusive). from random import random num = random, print(num) choice() This method is used to randomly select and return a single item from a given sequence. To use this method, you need to provide a sequence such as lists, tuples, or string as an argument, and the method then randomly picks one element from that sequence from random import choice L=['apple’, ‘grape’, mango’ result = choice(L) print(result) , banana’] randrange() This method behaves like the randint0, except that it allows you to specify not only the range of values but also an optional step value, enabling you to skip values within that range. The syntax is as follows: randrange(start, stop, step) from random import randrange result = randrange(1,10,2) print(result) Strings Strings are used to represent textual data. They are enclosed within quotation marks, which can be either single (), double ("), or triple ("or "). They can contain a combination of letters, numbers, and symbols, allowing for versatile representation of textual information. The following are examples of strings: "There are 3 oranges in the box." number ='1234" contact = '55 Hillview Avenue, Trans Ekulu’ Pro Tip: Strings are used to store various types of information, such as names of individuals, addresses, or descriptions of objects or concepts. Booleans The Boolean data type is characterized by two distinct values: True and False. It is specifically utilized to represent logical values, where True denotes a condition that is considered true or valid, and False indicates a condition that is false or invalid. vall = True vali alse Itis important to note that in Python, the values True and False for boolean data type are written with capital letters (T and F) at the beginning, while the remaining letters are in lowercase. Sequences Sequences often referred to as collections, allows you to organize and store multiple elements in a specific order. These data types include: Lists Tuples Dictionaries Sets Strings Files In addition to these basic data types, Python also supports more advanced data types, such as arrays, classes, and objects. print() function The print function is a built-in function that allows you to display output on the console or terminal. It is commonly used to print text or the values of variables and expressions during program execution, The print function accepts one or more arguments, which can be strings, numbers, variables, or expressions, and displays them as output on the console. print("hetto") print((1,2,3,4,5) Output: hello U1, 2, 3, 4, 5] The print function by default results in a new line, Take a look at this example: print(‘appl print("orange") print("mango") Output: apple orange ‘Mango However, if you do not to wish to have a newline anytime you used the print() function, you can change it through the end argument. For example: print("apple", end=") print("orange", end=") print("mango", end="") Output: apple orange mango Also, the print() function has the flexibility to accept a variable number of arguments, which are then displayed as a string with white space separating them. #print() function with multiple arguments, print("greet’, "me", "") Output: greet me! Input() function The input() function in Python is used to obtain input from users. It displays a prompt to the user, requesting them to provide text or data. The user can then input their response, and upon pressing the enter Key, it signifies that they have finished supplying the input. For example: input) print(‘your name is", name) Also, the input() function takes an optional argument in form of a string, as a way of informing the user of the required information to supply. name = input("What is your name: ") print("your name is’, name) summary ‘You learnt various data types in Python including the numeric types, strings and boolean data type and sequences. You also learnt their characteristics, how to use them, and the operations you can perform on them. You used the print() function to display output to console and the input() function to receive input from the user. Practice Exercises 1 2 3. 4 5. ‘What do you understand by data type in Python? List common data types in Python. . Mention the different numeric data types. |. What isa number system? . Write a program that prompts the user to provide their name, CHAPTER 3: OPERATIONS IN PYTHON “The idea behind digital computers may be explained by saying that these machines are intended to carry out any operation which could be done by a human computer.” - Alan Turing ‘As humans, we have this innate need to measure things. We're constantly seeking to quantify and understand the world around us. Whether it's measuring time, distance, or even emotions, we have this inherent desire to put things into measurable terms, We measure success, happiness, and even personal growth. It's as if measuring things gives us a sense of progress and helps us set goals for ourselves. It's fascinating how deeply ingrained this instinct is within us. Interestingly, in the realm of programming, we can apply a similar concept using a set of tools known as operators. ‘These operators allow us to perform calculations and comparisons, providing a means to measure and manipulate data within the digital world. Learning outcome In this chapter, you will learn: + Touse various operator types. + Tocreate simple and compound expressions. + Touse operator precedence to determine how compound expressions are evaluated. Introduction ‘An operator is a symbol or word(s) that denotes the kind of operation to be performed on values. Take a look at the following line of code. 142 The plus (+) symbol is used to indicate addition. When the interpreter encounters the plus symbol (+) between numbers, it interprets it as an expression and executes the addition operation on the given values. So, an expression is formed by combining values and operators. By combining operators, such as the plus symbol (+), ‘with values, you construct an expression capable of being assessed to yield a singular value. For example, 5-3 is an expression with the minus operator (-) and values (5 and 3). In this case, the operator - denotes subtraction, and the outcome is 2. When multiple expressions are present, Python continuously evaluates each individual expression until they are reduced to a single value. For instance: Inthe expression, 2 + 3 + 4, the value 2 is added to 3, which evaluates to 5, and then 4 is added to 5, which gives 9. A lot of times, you would be assigning a name to an expression. By doing so, you can conveniently refer to the expression using its assigned name whenever needed. For example: sum=2+3 So, if you ever need to refer to this expression later on, you can simply use the name "sum." Types of operators ‘There are basically six types of operators in python and they include: Arithmetic Relational Logical Bitwise Identity Membership Arithmetic operators ‘These operators are used to perform arithmetic operations or calculations. Here are the commonly used arithmetic operators in Python. Addition (+) Subtraction (-) Multiplication (*) Division (/) Floor division (//) Modulus (9%) Exponentiation (“) The addition operator (+) is used for adding numbers, while the subtraction operator (-) is used in performing subtractions. The multiplication operator (*) is used for multiplications in numbers. The single forward slash (/) is for division and when you use a single forward slash (/) as the division operator, the result is always a floating-point number. This type of division is known as true division. The double forward slash (//) is also used for a kind of division called the floor or integer division. The outcome of this division is an integer value. When numbers are divided using the integer division operator, the decimal points are removed retaining only the integer number. The double asterisk (“) is used as an operator for exponentiation, and the percentage sign (%) is used as an operator for modulus. ‘Modulus is the same thing as the remainder. For instance, 5 divided by 2 will give 2 anda remainder of 1 2is the quotient while 1 is the remainder or modulus. Below is an example program that demonstrates the usage of arithmetic operators in calculations: arithmetic operations # Addition num1=2 num? =3 sum = numi + num2 print(‘Addition: *, sum) # Subtraction num3 = 12 numé=8 diff = num3 -num4 print("Subtraction:", diff) # Multiplication nums = 4 numé = 6 product = nums * numé print("Multiplication:", product) # Division num7 = 20 nums =3 quotient = num? / nus print("True Division: ", quotient) # Floor Division num9 = 20 num10=3 result print("True Division: *, result) ums //num10 # Modulo num1i = 17 numi2=4 remainder = numt1 % num12 print("Modulo:", remainder) #Exponentiation base -2 power=5 result = base“ power print("Exponentiation:", result) # Floor Division num13=15 num14=7 floor_division = num’3 //num14 print(’Floor Division:", floor_division) Output: Addition: Subtraction: 4 Multiplication: 24 True Division: 6,666666666666667 True Division: 6 Modulo: 1 Exponentiation: 32 Floor Division: 2 Binary and unary operators Most arithmetic operators are binary operators, meaning that they work on two values or operands. ‘An expression like 2 * 3 has the multiplication operator * and two operands 2 and 3. 2is the left operand, while 3 is the right operand, However, some arithmetic operators are unary operators and work on a single operator. For instance, negative and positive signs like + and - are unary operators representing mathematical signs. + Unary plus = Unaryminus For example: 5 +10 Representing mathematical expressions in Python Arithmetic operators allow you to translate mathematical expressions into Python expressions. Let's convert a few mathematical expressions into their corresponding Python expressions: Mathematical expression: ya2e1 Python expression: y=2%-1 Mathematical expression: Z=x3+y2+5 Python expression: xB ty"2+5 Grouping expressions with parenthesis Parentheses are used to group expressions together. Through the use of parentheses, you can break down complex expressions into smaller, more manageable chunks, thereby ensuring the accurate calculation of each sub-expression. Take a look at the example below: # using parentheses for grouping expressions # without parentheses result =2+3"4 print("Result without parentheses:', result) # with parentheses result2 = (2+3)"4 print(’Result with parentheses:", result2) Output: 14 20 In the first expression, without parentheses, Python adheres to the order of operations (PEMDAS), executing multiplication before addition, yielding 2 + 12-14. However, in the second expression, the parentheses alters the order of operations, emphasizing the calculation of the grouped addition before other operations, resulting in (2 + 3)" 4=5* 4 = 20. Pro Tip: The use of parentheses alters the grouping and precedence of operations within an expression. Ensure that you group the right expressions together. If not, you may get the wrong result. Rules of Operator Precedence Expressions in Python are executed according to the operator's order of precedence. It's important to note that expressions are not evaluated strictly from left to right or right to left. Instead, the order of precedence determines which operators are evaluated first in an expression. Python evaluates expressions based on the precedence of the operators using a set of rules. These rules are similar to the rules for algebraic expressions and are abbreviated as PEDMMAS. Operators are evaluated in the following order. Parenthesis| Exponentiation Division Multiplication Modulus Addition Subtraction NOM aw Operators that are contained in a pair of parenthesis are evaluated before those that are outside of the parenthesis. This is followed by exponentiation, division, multiplication, modulus, addition and then subtraction, Now, let’s see how it works through the example below: #arithmetic operator precedence result =2+2-2°2/22%2 print(result) #using parenthesis to confirm precedence result = 2+ 2-((2*(2/(2" 2) % 2) print(result) Output: 3.0 3.0 From the example above, you can see the expressions are evaluated according to the precedence of operators. Relational Operators Relational operators, also known as comparison operators, are utilized to compare two or more values for equality. Particularly, they are used to establish if two values are equal, less or greater than each other and are mostly used in control statements for decision-making, The following are relational operators and their meaning, + Greater than > + Less than < + Greater or equal to >= + Less or equal to <= + Equality + Not Equality’ ‘The greater than (>) returns True if the operand on the left is larger than the operator on the right. ‘The less than (<) returns True if the operand on the left is smaller than the operator on the right. Greater or equal to (>=) returns True if the operand on the left is equivalent or larger than the operator on the right. Less or equal to (<=) returns True if the operand on the left is equivalent or smaller than the operator on the right. ‘The equality operator (==) returns True if the left and right operators are equivalent, while the not equality operator (1 =) returns True if the operands are not equivalent. is not the same as equal to (=). The equality operator (==) is a relational operator used in comparing values, while the equal sign (=) is an assignment operator used in assigning values to avariable. Truthy and falsey values ‘A value that is considered "truthy" is one that is evaluated as equivalent to True in a Boolean context. On the other hand, a value that is considered "falsey’ is one that is evaluated as equivalent to False in a Boolean context. For example, any number greater than 0, anon-empty list, or anon-empty string is evaluated as True and is considered truthy. Conversely, the number 0, an empty string, or an empty list is evaluated as False and is considered falsey. In the following example, relational operators are utilized to compare values. #relational operations # Greater than valuel = 7 value2= 4 result1 = value1 > value2 print("Greater than:", result1) #Less than value3 = 8 valued = 5 result2 = value3 < valued print("Less than:’, result2) # Greater than or equal to values = 5 values = 5 result3 = valueS >= value6 print("Greater than or equal to:", result3) # Less than or equal to value? = 9 values = 9 result4 = value7 <= value8 print("Less than or equal to:", result) equality valued = 4. ‘value10 = 7 result5 = valued == value10 print("Equal to:’, results) ¥not equality value11 = 3 value12 = 2 resulté = value11 == value12 print("Equal to:", result6) Output: Greater than: True Less than: False Greater than or equal to: True Less than or equal to: True Equal to: False Equal to: False Logical operators Logical operators allow you to join together boolean values or expressions to create a more complex expression. This compound expression is then examined to determine ifit ultimately resolves to either True or False. The following are examples of logical operators: + and + or + not and Operator The "and" operator is used to combine two or more expressions into a single complex expression. When the "and" operator is used to combine expressions, each individual expression must evaluate to True for the overall outcome to be True. If any of the expressions evaluates to False, the entire expression will evaluate to False or operator The "or" operator is also used to combine two or more expressions. Unlike the and operator, the combined expression evaluates to True, if any of the individual expressions evaluate to True. It evaluates to False if all the expressions evaluate to False. not operator The "not" operator negates the boolean value of the operand, returning True if the operand is False, and False if the operand is True. Overall, these logical operators allow you to build complex conditions and make decisions based on multiple criteria. In the following example, the logical operators are used to combine expressions and values together. # Logical operations valuel = 4. value? = 8 # Logical AND operator result1 = (valuel > 0) and (value? < 15) print(result1) # Logical OR operator result2 = (valuet print(result2) ) or (value2 > 20) # Logical NOT operator result3 = not (valuel > value2) print(result3) Output: True False True Bitwise operators Any operation that involves the use or manipulation of data in its binary form is considered a bitwise operation. Bitwise operations are done using the bitwise operators. With these operators, you can perform all sorts of data manipulation on data at the basic or binary level. Bitwise operations are highly efficient and renowned for their exceptional speed due to their binary-level execution and are often used in operations where speed and efficiency are of uttermost importance. Hence, bitwise operations are widely used in encryptions, communications over networks, graphics and much more. The following are examples of bitwise operators: + Bitwise and & + Bitwise or! + Bitwise xor 4 + Bitwise leftshift << + Bitwise right shift >> + Bitiwse not ~ Bitwise AND operator This operator is represented with the symbol &. It returns 1 if both operands have a binary digit of 1 in the same position, and 0 if otherwise. ‘You can also determine the outcome of the bitwise and operation at any given position using the formula: (A&B)i= Aix Bi This is demonstrated in the figure below, where the respective bits in a given position are multiplied. 11Ol& 1001 = bitwise and x oo=- ooo Pro Tip: Converting an integer to its binary representation (bits) can be done using the bin() function. The bin() function returns a string representing the binary form of an integer. For better understanding, the following code expressed numbers in binary forms and outcomes are converted to binary. wbitwise and num2 = 0b1011 result] = bin(num1 & num2) print(zesult2) numd = 0b101 result2 = bin(num3 & num4) print(result2) Output: 0b1001 0b100 Bitwise OR operator This operator returns 1 if one or both operands have a binary digit of 1 in any given position. If both operands have 0 at any given position, the outcome is 0. The bitwise or operator is represented with the symbol |. Also, you can determine the outcome of bitwise or operation using the formula below. (A|B)i= Ai+ Bi +1101 1101 | 1001 = * 1001 bitwise or “(19) (1) (®) (10) 1101 In the illustration above, 1 is returned if the sum of the binary digits in a given position is 1 or greater than 1. Now, let's further demonstrate it using the code below. #bitwise or numS = 0b1101 numé = 0b1001 result3 = bin(nums | num6) print(zesult3) num? = 0b100 nums = 0b101 result4 = bin(num7 | num8) print(resulté) output: Ob1101 Ob101 Bitwise XOR operator The bitwise xor operator returns 1 if the bits in the same position are of opposing values. This means that, if the corresponding bits in a given position are both 1 or both 0, the outcome is 0. ‘The bitwise operator xor is represented with the symbol 4. ‘You can determine the outcome of the bitwise xor operation using the formula below. (ALB)i= (Ai + Bi) mod 2 In the illustration below, the bits in a given position are first added. Then, the resulting value is divided by 2 and the remainder or modulus becomes the outcome. ! 1ol 100! @()O)A) %2 0100 The following example demonstrates the usage of the bitwise xor operator: #bitwise xor 1101 * 1001 bitwise xor num9 = 0b1101 num10 = 0b1011 resultS = bin(num9 * num10) print(results) num11 = 0b110111 num12 = 0b101011 result6 = bin(num11 *num12) print(result6) Output: 0b110 0b11100 Bitwise NOT Operator The bitwise not operator is represented with the symbol ~. Unlike most bitwise operators that work on two sets of operands, the bitwise not operator is a unary operator that operates ona single operand. Itis used to perform logical negation and the outcome is determined with the formula below: Ai = 1-Ai ‘This is illustrated in the figure below: = 1-1100 ~11olr = -1100+1 bitwise not -(1101- 1) = -1100 The bitwise not operator is illustrated in the code snippet below: #bitwise not num13=0b10 result7 = bin(~num13) print(result7) Output: -0b11 Bitwise left shift operator The bitwise left shift operator moves the bits of the first operand to the left by the number of positions specified by the second operand. The left-shifted bits are filled with zeros on the right side. The bitwise left shift operator is represented with the symbol <<. bitwise leftshift I 0 0 I 1ool<<1 10010)<: 1001 <<2 100100\<:2 ry Here, is an example: bitwise leftshift num14 = 0b1001 result8 = bin(num14 << 1) print(results) result9 = bin(num14 << 2) print(result9) result10 = bin(num14 << 3) print(result10) Output: 0b10010 0b100100 061001000 Also, the bitwise left shift operator can be evaluated using the following formula. Assn=Axzn So, 5 <<2 is the same thing as: 5x22 = 5%4=20 Bitwise right shift operator ‘The bitwise right shift operator in Python shifts the bits of the first operand to the right by the number of positions specified by the second operand. The right-shifted bits are padded with zeros on the left side. This operator is represented by the symbol "> bitwise rightshift I 00 I 1o01>>1 100 >: 1001 >>2 O010 >2 — ‘The code below demonstrates the bitwise right shift operations. #bitwise right shift mum15 = 0b1001 result11 = bin(num15 >> 1) print(result11) result = bin(num1s >> 2) print(result12) result13 = bin(num15 >> 3) print(result13) result =bin(num1s >> 4) print(result14) Output: ob100 ob10 obi obo Membership Operators Membership operators are used to test whether a specific item or value is present in a sequence or collection. They are used to determine whether a given item or value is present in a sequence such as the list, tuple, sets and so on. There are two membership operators in python and they include: + Inoperator + Notin operator The *in" operator verifies the presence of a value within a sequence, such as a string, list, tuple, or set. On the other hand, the “not in” operator confirms the absence of a value within the sequence. If the value is not found, it returns True; otherwise, it returns False. In the following example, the membership operators are utilized to ascertain the existence of specific values within a sequence. # membership operators mums =[1, 2, 3,4, 5] print(3 in nums) ‘Hello there!" in greeting) print("world" in greeting) Output: True True False Identity operators Identity operators are used to compare the identity of two objects, checking if they refer to the same memory location. They are used to establish whether a given value is the same as another value. Identity operators in Python go beyond just checking equality. They allow you to determine if two values are not only equivalent but also refer to the exact same object in memory. In other words, even if two values may look alike and have the same content, they may not be the exact same object. So, identity comparison provides a way to distinguish between objects that are truly identical and those that are only equivalent. There are two identity operators in python and they include: + Isoperator + Isnot operator The "is" operator checks if two variables refer to the same object in memory. It returns True if the variables have the same identity, and False otherwise. The “is not" operator checks if two variables do not refer to the same object in memory. It returns True if the variables have different identities, and False if they refer to the same object. ‘The code below provides an example of the use of identity operators in Python. # identity operators num =5 num2=4 num3 = numl print(num1 is num2) print(num1 is num3) print(num2 is num3) num4 = 5 num = 10 print(numd is not nums) Output: False True False True Summary In this chapter, you learnt the different types of operators in Python. You used the arithmetic operators to perform addition, subtraction, multiplication, division, and other mathematical operations on numeric values. Also, you used the comparison operators to check for equality, inequality, greater than, less than, and other comparison conditions. ‘You used the logical operators to combine boolean values and evaluate complex logical conditions. Additionally, you learnt how to structure expressions logically and how the operator precedence is used in evaluations of compound expressions. Practice Exercises 1, What are the different types of operators in Python? ‘What is the meaning of operator precedence? State the difference between expression and statement? State 5 examples of arithmetic operators. ‘What is the use of parenthesis in operator precedence? 6. Write a program that calculates the area and volume of a rectangle and a cubiod. 7. Write a program that converts temperature in Celsius to Farenheit? 8. What is the advantages of bitwise operations. CHAPTER 4: CONTROL FLOW STATEMENTS “When you change the way you look at things, the things you look at change.” - Max Planck Atypical computer program is executed in a linear manner, from top to bottom. This means that the first line of code gets executed before any other lines, and the last line is the final one to be executed. But what if we want to change the order of execution or repeat a specific piece of code multiple times? That's when control statements come into play. They allow us to control the flow of program execution and make our programs more dynamic. By incorporating control statements into our programs, we can create more dynamic and versatile software that responds to different conditions and user inputs. Learning outcome In this chapter, you will learn: + Various types of control statements. + Touse if, elif, and else statements for decision making. + Touse nested if statements. Introduction Control flow statements in Python are programming constructs that allow you to alter the flow of execution in a program based on specific conditions. Typically, programs execute in a sequential manner, going from top to bottom and left to right. However, there are situations where you may want to break away from this linear execution. That's when control flow statements come into play. By using control statements; you can create programs that make intelligent decisions. There are three types of control statements in Python and they include: 1. Conditional statements 2. Looping statements 3. Jump statements Conditional statements Conditional statements allow you to execute specific blocks of code based on certain conditions. statements, you can break away from the linear execution of your program. This means that certain sections of code may or may not be executed, depending on the conditions you specify. ith conditional Conditional statements are incredibly powerful as they enable your program to adapt and respond intelligently to different scenarios. They make it possible to create dynamic and interactive programs that can react differently based on the input or current state of the program. ‘The main conditional statements in Python are: + if statement + if-else statement + ifelif-else If statements The "if" statement is widely used and considered the most commonly employed conditional statement. It allows you to evaluate a condition and execute a specific block of code if the condition is true This is the syntax: if condition: # Code to be executed if the condition is true The “if” keyword marks the beginning of the statement, followed by the condition, which is an expression that determines whether the block of code will be executed or not. The colon (:) denotes the end of the condition and indicates that the following indented code block is associated with the "if" statement. Take a look at this example: #if-statement num ifnum % 2 == 0: print(an even number’) Output: an even number In the above example, the condition num % 2 == 0 needs to evaluate to True. If the remainder of num divided by 2 is equal to 0, it means that num is an even number, and the code block inside the “if" statement will be executed, resulting in the message “an even number" being printed. Now, here is the problem. The print( statement never executes if num is an odd number. To fix this, you can use an else statement. This way, you can specify what to do when the number is odd. Else statement The else statement in Python is used to provide a fallback block of code to be executed when none of the preceding condition(s) in an if statement are true. In the previous example, there was no fallback option to handle the case when num is an odd number, To address this, you can use an else statement to provide an alternative set of instructions that will be executed when the condition within the if statement is false. For example: Helse statements ifmum % 2 print(an even number’) else: print(an odd number) Elif statements The "elif" statement is used to introduce an alternative condition in an "if" statement. It allows you to check for additional conditions after the initial if statement and execute a different block of code if the preceding condition(s) are false, but the elif condition is true. Here's an example to illustrate the usage: elif statement ifum % 2 ==0: print(an even number’) elif num % 2 != 0: print(an odd number) In the above example, the if statement checks if num is an even number using the condition num % 2 == 0. If this condition is true, the code inside the if block is executed, printing the message ‘an even number. The elif statement (short for "else if") introduces a new condition to be checked only if the preceding if condition is false. In this case, it checks whether num is not an even number using the condition num % 2 != 0. If this condition is true, the code inside the elif block is executed, printing the message ‘an odd number: Now, let's create additional branches using multiple elif statements: #multiple elif statement if num % 2 == 0: print(an even number’) elifnum % 3 print(divisible by 3) elifnnum % 4 {= 0: print(divisible by 4°) ‘The program checks if the number is divisible by 2. If true, it prints "an even number" If the number is not divisible by 2, it checks ifit is divisible by 3. If true, it prints "divisible by 3"1f the number is not divisible by 2 or 3, it checks if itis. not divisible by 4. If true, it prints "divisible by 4". Nested if statements Nested if statement is an if statement that is placed inside another if statement. They are particularly useful when you need to introduce more levels of conditions or perform more specific checks based on multiple conditions. Take a look at this example: #nested if statements ifnum > 0: ifnum % 2 == 0: print(‘even number) In this case, the program checks if num is greater than 0, and if so, it proceeds to check if num is even. The code block inside the inner if statement will only execute if both conditions are true. Pro Tip: [t's important to note that indentation is crucial in Python as it determines the block of code associated with each if statement. The inner if statement is indented further to indicate that it belongs to the outer if block. Summary ‘You learnt the various types of control statements and how they can be used to control the flow of execution in your program based on certain conditions or criteria. The if statement is used to execute a block of code if a certain condition is true. If the condition is false, the code block is skipped. The elif statement is used to check additional conditions after the initial if statement. The else statement is to used to provide a default block of code to be executed when none of the preceding conditions in an if-elif structure are true. Practice Exercises ‘What does it mean to control the flow of programs? ‘Mention the three types of control statements. ‘Write a program that determines if a number is even or odd or prime. ‘Write a program to check whether a number is divisible by 3 aye Write a program that tests whether an input is an integer. Write a program to determine if a person is eligible to vote or not (voting age is 18 years and above). Write a program that accepts scores from user and displays the corresponding grade using the following, criteria, F(0-39), E(40-44), D(45-49), C(50-59), B(60-69) and A( 70 and above) CHAPTER 5: LOOPING STATEMENTS “If at first you don't succeed, try, try again. Then quit. There's no point in being a damn fool about it.” -W.C. Fields Imagine people moving in a circle. They keep going around and around until a specific condition is met or a certain number of repetitions are completed. This continuous circular movement can represent a loop in programming. In programming, we often use loops to perform repetitive tasks or iterate over a set of data. It's like going around the circle multiple times, executing the same set of instructions until a certain condition is satisfied. Just as the circular movement allows us to visit the same points again and again, loops enable us to revisit and reprocess a block of code until a desired outcome is achieved. Learning outcome In this chapter, you will learn: + Touse the for loop and while loop to execute codes repeatedly. + Touse the continue and break statements to break out of a loop. + How to iterate over sequences using loops. Introduction Looping statements are used to execute a block of code repeatedly, allowing you to automate repetitive tasks and iterate over sequences or collections of data. Python provides two main types of looping statements and they include: 1. Forloop 2. While loop For loop A for loop is used to iterate over a sequence of values (such as lists, tuples or a strings) and execute the indented block of code multiple times, once for each element in the specified sequence. eu print(‘hello’) The basic syntax of a for loop in Python is as follows: for variable in sequence: # execute this block of code In a for loop, the variable that comes after the for keyword is linked to the first item in a sequence. The code block within the loop is executed, and then the variable is linked to the next item in the sequence. This process continues until the loop reaches the end of the sequence, allowing the code block to be executed for each item in the sequence one at a time. nums 1,23,4,5] fornum in nums: print(num) Output: In this example, the for loop iterates through the list, associating num with each item in sequence, and printing it. In addition to numbers, the for loop allows you to iterate over various types of sequences. ‘You can use the for loop to iterate over any kind of sequence, such as lists, strings, tuples, or even custom sequences you create fruits - 'apple’, ‘orange, ‘pineapple, ‘strawberry’, grape] for fruit in fruits: print(fruit) Output: apple orange pineapple strawberry grape Apart from using a predefined list, you can use the built-in range() function to generate a sequence of numbers to iterate over. The range() function. The range() function is used to generate a sequence of numbers within a specified range. The basic syntax is as follows range(start, stop, step) Pro Tip: The start és the initial value of the sequence. It is optional and defaults to 0 when not provided. The stop is the end value of the sequence. The sequence will encompass all numbers starting from the provided start value up to, but not including, the stop value. Then, the step is the size or interval between numbers in the sequence. If not provided, it will default to 1. Here is an example to illustrate the usage: using range( function for num in range(s): print(num) Output: ° i 2 3 While loop The while loop allows you to repeatedly execute a block of code as long asa certain condition is true. It begins with a condition. If the condition evaluates to True, the block of codes under it is executed. The process is repeated like this as Jong as the test keeps evaluating to True. The while loop consists of the while keyword, followed by a conditional test and a colon. The next line is an indented block of code. This block of code only executes if the test condition is True. The loop keeps going until the condition is no longer true. Once that condition becomes false, the program stops looping and moves on to the next set of instructions. The syntax of a while loop in Python is: while condition: statement(s) Pro Tip: If the condition never becomes false or if there's no mechanism to break out of the loop, the program will get stuck in an infinite loop, endlessly repeating the same set of instructions. This can lead to the program becoming unresponsive and consuming a lot of resources, which is something we want to avoid in programming. This can be achieved by including statements inside the loop that modify the loop condition. Now, let’s use the while loop to print numbers ranging from 0 to 9: count = 0 while count < 10: print(count) count += 1 Output: COVA HawHHO In the above example, the variable "count" is initialized with a value of 0. The while loop is defined with the condition that it will iterate as long as “count is less than 10, Inside the loop, the current value of "count" is printed using the statement print(count). The "count" is incremented by 1 with each iteration Consequently, the loop persists until the value of “count” reaches 10, at which point the condition becomes false, leading to the termination of the loop. Jump statements Jump statements are used to control the flow of execution within a program by altering the order in which statements are executed, These statements allow you to transfer control toa different part of the code based on certain conditions. ‘The most common jump statements in Python are: + Break + Continue + Pass Break The break statement is used to terminate the execution of a loop prematurely, It is typically used inside a for or while loop to exit the loop before the loop has finished iterating through all of its elements. When the break statement is encountered within a loop, the loop is immediately exited and control is transferred to the statement immediately following the loop. Below is an example that demonstrates the usage of the break statement in a for loop to end the loop when a specific condition is satisfied: #break example for num in range(10): ifnum > 5: break print(num) Output: In the above example, the program iterates through the values in the range until it encounters a number greater than 5. At that point, the loop will be terminated by the break statement. Continue The continue statement allows you to skip the current iteration of the loop and move directly to the next one. When the continue statement is encountered, the loop takes a leap forward to the next iteration, bypassing any remaining code within the current iteration. Here is an example of using the continue statement within a for loop: continue example for num in range(10): ifnum continue print(aum) Output: In this example, the for loop is used to iterate over the numbers in the range from 0 to 9. When the number 5 is encountered, itis skipped and the loop continues with the next number. As a result, the code will print all the numbers from 0 to 4 and 6 to 9, excluding the number 5. Pass The pass statement is a null operation. It simply does nothing and is often used as a placeholder for code that has not been implemented yet or for code that will be implemented later. Here is an example of using pass in an if statement: for num in range(10): pass Summary In this chapter, you learnt how to use the for loop and while loop to execute codes repeatedly. The for loop allows you to iterate over a sequence (such as a list, tuple, or string) or any kind of sequence. The while loop repeatedly executes a block of code as longas a specified condition is true. You learnt how touse the continue and break statements to skip or exit the loop prematurely. Practice Exercises 1. Explain the concept of looping in programming? 14. 15. 16. 17. State the two types of looping constructs in Python, Explain the range() function. Write a program using the for loop to display the word “hello” 10 times Write a program to print numbers from 1 to 10 and their squares using the while and for loops. Write a program to determine the last digit of a number, Write a number that determines if a number is a perfect square. Write a program that takes a sequence of number and check if all numbers are unique. Write a program to accept numbers from 1 to 7 and display them as Sunday, Monday and so on. ‘Write a program that displays a multiplication table. ‘Write a program that prints a table of binary, octal, decimal and hexadecimal equivalents for 1 to 256. ‘Write a program that counts the number of digits in a number. ‘Write a program that prompts the user for 5 numbers and prints the numbers in a line and each number separated by 4 whitespaces. ‘Write a program that reads numbers and displays the smallest and the largest numbers. ‘Write a program that prints the summation of all the numbers from 1 to 100. Calculate the LCM and HCF of two numbers using python. ‘Write a number guessing game. CHAPTER 6: STRINGS “Tike to combine the dramatic emotional warmth of strings with the grooves and body business of drums and bass.” - David Byrne Every single program we write is actually made up of characters, like alphabets, numbers, and symbols, No matter the complexity of a program, it all comes down to the fundamental elements. They are the raw materials we use to construct our code. It's remarkable how these characters can be combined in various ways to create meaningful statements, words, and sentences within our programs. They give us the power to communicate instructions and logic to the computer. And when we have a group of characters that are treated as a single unit, like a phrase or a sentence, ‘we call it a string, Learning outcome In this chapter, you will learn: + What strings are and how they are used to represent text. + String manipulation operations like concatenation, slicing, and repetition. + Different methods of formatting strings. + Touse the built-in string methods to perform common string operations. Introduction Strings are used to representa collection of characters. You can create a string by enclosing the characters within either single (") or double ("") quotation marks. Strings are immutable, which means that once a string is created, its content cannot be modified. This means that you cannot change individual characters within a string after it has been created. Creating a String To create a string in Python, simply enclose a sequence of characters in quotes. country = ‘Algeria’ sentence = 'How are you?! Pro Tip: Itis important to note that in Python, single and double quotes can be used interchangeably to create a string, as long as they match. Operations on strings Python provides a variety of operations and methods to work with strings. Here are some commonly used operations on strings: + Concatenation + Repetitions + Indexing + Slicing + Looping Concatenation Concatenation is the process of combining or joining two or more strings together to create a new string. It allows you ‘to merge the contents of multiple strings into a single string. ‘When you use the + operator between two strings, it joins the characters of the strings in the order they appear, producing a new string that contains the combined characters. For example: #concatenation of strings str] = ice’ str2 = ‘cream’ result = str1 + str2 print(result) Output: Icecream, If you want to put a space in between the words, you can include a white space as shown below: #include a white space result = str1 + "+ str2 print(result) Output: icecream Repetitions To repeat a string, you simply write the string followed by the asterisk symbol (") and then the number of times you ‘want the string to be repeated. Pro Tip: Normally, this operator does multiplication with numbers, but when it comes to strings, it does something different. It actually repeats the string as many times as you specify. ‘repetition of strings result = greeting" 3 print(result) output: hellothellothello! Indexing ‘You can access individual characters or a range of characters within a string by their position. In Python, strings are zero-indexed, which means the first character of a string is at index 0, the second character is at index 1, and so on. To access a specific character in a string, you can use square brackets [] with the index value inside. #indexing in strings fruit ='apple’ print(fruit{o)) print(fruit(1)) print(fruitl2)) print(fruit{3)) print(fruitl4]) Output: Sooo se ‘You can also use negative indexing to access characters from the end of the string. The index -1 represents the last character, -2 represents the second-to-last character, and soon. negative indexing fruit = ‘apple’ print(fruit{-1)) print(fruitl-2)) print(fruit(-3)) print(fruit(-4)) print(fruit(-s)) Output: ~ aos Also, strings are immutable, meaning that you cannot perform remove or update characters in a string once it has been defined, else you will get an error. For instance: color = ‘yellow’ color{0] ='¥" Output: TypeE ror: 'str object does not support item assignment Slicing Slicing enables you to extract a specific portion or substring from a string. It allows you to create a new string containing a range of characters from the original string. While indexing involves fetching a specific character from a string based on its position or index, slicing involves extracting a range of characters froma string. To perform slicing, you use square brackets []. Inside these brackets, you specify the start and end index of the desired substring separated by a colon (:). #slicing a string result = fruit[1:3] print(result) Output: PP Pro Tip: When youslice a string, the start indexis inclusive, meaning it includes the character at that index. The end index, however, is exclusive, so it does not include the character at that index. Slicing can also include additional parameters, such as step size, which determines the increment between indices in the slice. The default step size is 1, but you can specify a different value to skip elements. Here's an example that demonstrates slicing with a step size: #slicing with step fruit = ‘pineapple’ result = fruit{0:10:2) print(result) Output: Pnape Looping a string Strings are considered as sequences of characters. This characteristic allows you to iterate through each individual character in a string using either a for loop or a while loop. for char in apple’ print(char) Output: a Built-in methods for string Python has a variety of built-in methods that can be used to manipulate strings. Here are some commonly used built- in methods for strings: + Jower(): Converts all characters in a string to lowercase. + upper(): Converts all characters in a string to uppercase. + capitalize(): Capitalizes the first character ofa string. + strip): Removes leading and trailing whitespace from a string. + split: Splits a string into a list of substrings based ona specified separator. + join(: Joins a list of strings into a single string using a specified separator. + isdigit(): Checks if all characters in a string are digits. + isalpha(): Checks if all characters in a string are alphabetic, + islower(): Checks if all characters in a string are lowercase. + isupper(): Checks if all characters in a string are uppercase, Take a look at the following example: name = John’ #lower print(name.lower()) upper print(name.upper()) capitalize print(name.capitalize() #title sentence = ‘how are you doing?" print(sentence.title()) strip word =" hello! print(word strip) split sentence = ‘how are you doing?" print(sentence.split)) join words = '"join({‘hello’,'there']) print(words) Hisdigit nums ='1234' print(nums.isdigit0) nums ='12 Hillview’ print(nums.isdigit0) Hisalpha word = 'hello! print(word isalpha()) nums ='1234" print(nums.isalpha()) sislower word = ‘hello! print(word islower()) ‘word ='HELLO’ print(word islower()) #isupper word = ‘hello! print(word isupper()) word = "HELLO" print(word isupper()) Output: john. JOHN John How Are You Doing? hello (how; ‘are’, ‘you’, 'doing?'] hello there True False True False True False False True Membership Test Strings supports membership tests. Using the in operator, you can determine whether a character or group of characters are in a given string, The outcome of this operation is either True or False color = ‘yellow’ print('y'in color) print(‘lo' in color) print(’x'in color) Outputs: True True False Triple quotes Triple quotes also known as docstrings are used to create multiline strings. Even though some consider this as a way of commenting strings, but technically, docstrings or characters in triple quotes are considered as strings. Pro Tip: You can use triple single or double quotes, but be consistent in your choice, otherwise you will get a syntax error, However, it’s recommended that you only use single or double quotes in defining strings. Triple quotes are predominantly used for code documentations, Also, avoid using triple quotes for the commenting except if it is part of your program documentations. This is the documentation for the program #triple quotes used in defining strings Outputs: Hello 1 hello2 SyntaxError: unterminated triple-quoted string literal (detected at line 17) Strings and built-in functions Python has a rich set of built-in functions that can be used to manipulate and process strings. Some commonly used built-in functions for strings in Python are: + Tend) + str, + ord() lenQ) The len() function is a built-in function that returns the length or the number of items in a sequence. When used with strings, it returns the number of characters in the string, So, the length of a string is essentially the same thing as the number of characters within that string. fruit = ‘grape’ print(len(fruit)) Output: 5 str() The str() function is a built-in function that converts an object into a string representation. It can be used with various data types, including numbers, booleans, lists, tuples, and more. Also, it provides a convenient way to convert non-string objects into string format, making them suitable for string manipulation and display purposes. using str() function to convert integer to string num = 1200 result tr(num) print(num) Output: 1200 ord() Each character is represented in Unicode using a unique value called a code point. There may be instances where you need to find the Unicode code point of a specific character, and that's when the ord() function comes in handy. By using the ord( function, you can easily determine the Unicode code point associated with a particular character. using ord to get unicode code points print(ord('h’) print(ord(‘p)) print(ord(.)) Output: 104 112 46 Escape characters Escape characters are special characters that are used to represent non-printable characters or to create special characters within string literals. They allow you to use characters that are hard to represent ina string. When Python encounters escape characters, it interprets it asa special character rather than as part of the string. They are represented by a backslash (\) followed by a character or a sequence of characters. Here are a few examples of commonly used escape characters in Python: + \n-newline character + \t tab character + \\-backslash character + \"-double quote character + \-single quote character + \b-backspace character + \e carriage return character + \E formfeed character Let's explore some examples that involve the use of escape characters. escape characters example str1 = ‘hello \tthere’ print(str1) str2 = ‘hello \nthere! print(str2) str3 = "This isa string with a newline character\nand atab character\tin it! print(str3) Output: hello there hello there Thisis a string with a newline character andatabcharacter init. In this example, the escape characters \n and \t are used to create a new line and a tab within the string. Raw strings A regular string is represented asa sequence of characters enclosed within single ('') or double "*) quotes. However, in certain situations, the presence of escape characters can lead to unintended outcomes. For instance, if you want to include a quotation mark within a string, you use an escape character like this: "He said, \"Hello!\" Here, the backslash before the second double quote tells the interpreter to treat it as a regular character, not the end of the string. Now, if you want to make the compiler ignore escape characters and treat a string the way it is, you can use a raw string. To create a raw string, simply place an ‘r' before the beginning quotation mark. By using a raw string, all escape characters within the string will be completely ignored, and any backslashes present will be printed as they are without any special interpretation. raw string str = rhello \nthere’ print(str1) Output: hello \nthere String substitution methods String substitution plays a significant role when it comes to manipulating strings in Python. It allows you to create dynamic strings by incorporating variables, expressions, or other strings into a larger string. Python provides various methods for performing string substitutions, including the following: + Format function + E-strings + Oldstring substitution Format function The format() function in Python is a built-in method for strings that allows you to perform string formatting and substitution, ‘Touse this function, you are required to include curly braces {} as placeholders in your string. These curly braces act like markers that tell the function where you want to perform substitutions, Inside the curly braces, you can specify the positions or even assign names to the values or variables you want to substitute. $= '} shirts in the {} box’.format(s, blue’) print(S) Outputs: 5 shirts in the blue box ‘The above example contains two placeholders enclosed in curly braces. These placeholders serve as markers, indicating the positions in the string where the values will be inserted or substituted. By calling the format() function, the placeholders in the string are replaced with the provided values. The resulting string is then assigned to the variable S. In this case, the value of $ would be'S shirts in the blue box’. In addition, if you want to have more control over the substitution process and not rely solely on the positions of the arguments in the format() function, you can include numbers within the curly braces. This allows you to specify explicitly which value should be substituted at each placeholder. $= "{0} shirts in the {1} box’.format(S, blue) print(s) Outputs: 5 shirts in the blue box Now, if you want to switch things up and have the first argument replace the second set of curly braces, while the second argument takes the place of the first set of curly braces, you can achieve that by assigning a higher number to the first set of curly braces compared to the second set. $="{1} shirts in the (0} box’ format(S, blue) print(s) Outputs: blue shirts in the 5 box F-strings F-strings also known as formatted string literals is an easy way to perform string substitution in python. Instead of using the format() function or concatenation, you can place the variables or expressions directly inside curly braces {} within the string. To use f-strings for string substitution, you simply need to include the letter ‘f' before the opening quotation mark ofa string, This signals that the string is an f-string, Inside the f-string, you can place expressions or variables within curly braces {}. These expressions are treated as valid Python expressions and will be evaluated and substituted with their corresponding values when the string is evaluated. box = ‘blue! S=fThere are {2+3} shirts in the {box} box’ print(S) The above example contains two placeholders enclosed in curly braces {}. The first placeholder {2+3} contains an expression 2+3, which evaluates to 5. The second placeholder {box] expects the value of the variable 'box’ to be substituted. So, when the f-string is evaluated, the curly braces and the expression inside them will be replaced by the computed. value, resulting in the string below: Output: ‘There are 5 shirts in the blue box Old String Substitution This involves the use of the % operator for substitution. To use the % operator for string substitution, you start with a string containing one or mote placeholders represented by %s. These placeholders act as slots where values will be inserted. S = "90s oranges! % 5 print(s) Output: 5 oranges In the above example, the character after the % operator is substituted by the argument provided at the end of the string, and in this case 5. However, if more than one substitution is to be performed, the arguments for substitution should be enclosed in a parenthesis as shown below. = '%6s shirts in the %s box! % (5, blue’) print(S) Output: S oranges Standard string formatting specifiers Python provides a powerful way for presenting data in a clear and organized format through its standard string formatting specifiers. These specifiers provide a structured way to create formatted strings. Here is the syntax: [filjalignitsignI{#][0lfminimumwidthil.precision|{type] Type The type indicates the type of data that is expected or how the data should be presented. String type-s Numeric types + b'binary + ‘e'character + ‘d'decimal integer ‘octal + 'xthexadecimal + "hexadecimal + ‘n'number + "none Take a look at this example: S='Hello there %s' % 5 print(S) $= 'Hello there %s' %'5' print(S) $= 'Hello there %d' % 5 print(S) $= 'Hello there %f' % 5 print(S) $= 'Hello there %c' %'5' print(S) Outputs: Hello there 5 Hello there 5 Hello there 5 Hello there 5.000000 Hello there 5 Floating point types + 'e’exponent + 'E’exponent + f'fixed point + 'F fixed point + ‘g'general + 'Ggeneral + ‘n'number + '% percentage Time types + 'a!- abbreviated weekday name + ‘A’ full weekday Name + ‘b!-abbreviated month name + 'B'-full month name + dl-day + ‘H'-hour with trailing zeros + 'M'-Minutes with trailing zeros + 'S'- Seconds with trailing zeros + Y'- -yearwith century Precision This is a decimal number indicating number of digits after the decimal point. It is predominantly used if the expected argument is afloat. $= "Hello there %.2f'% 5 print(s) S='Hello there %.5f°% 5 print(s) Outputs: Hello there 5.00 Hello there 5.00000 Width This is a decimal number indicating the minimum field width. If the width argument is less than the width, then you ‘may decide to pad the characters of your choice. S="9od oranges’ 9% 5 print(s) S= "965d oranges! % 5 print(s) S="9005d oranges! % 5 print(s) S='9610s oranges’ % ‘apple’ print(s) Outputs: 5 oranges 5 oranges (00005 oranges apple oranges Fill The fill is used to indicate the character to be used to pad the field to minimum width as shown below: S= "005d oranges! % 5 print(s) Outputs: (00005 oranges Summary In this chapter, you learnt concept of strings and how they are used to represent text in Python, You performed various string manipulation operations such as concatenation, slicing, and repetition. You learnt the different techniques for formatting strings and embedding variables and expressions within a string. You also learnt about the numerous built- in string methods for performing common operations like splitting, and joining strings. Practice Exercises 1. How do you define a string in Python? 2. String is an immutable object, what does it mean? 3. Write a program to combine two strings together to form another string, enous 9. Write a program to determine the length of a string, Write a program that counts the number of the individual characters in a string. Write a program to get the nth item in anon empty string. Write a program that reverses a string Explain split and join methods of strings. Write a program to convert a tuple toa string 10. Write a program that displays the ASCII number and the corresponding characters. 11. Write a program that generates random passwords containing alphabets, numbers and symbols 12, Write a program that removes vowels from a word. CHAPTER 7: LISTS “The human animal differs from the lesser primates in his passion for lists.” -H. Allen Smith Let's say you want to go shopping. To ensure you don't forget anything, you start by making a list of items you need to buy. With pen and paper, you can start writing down or listing the items you need to purchase. You may want to review and revise your shopping list from time to time. You may wish to remove some items you considered not essential or add new ones that you remember. Also, you iterate over your shopping list, making adjustments to ensure it reflects your needs accurately. You may decide to arrange the items on your shopping list based on their importance or priority. And just like your shopping list, a list in python is a collection of items. Learning outcome In this chapter, you will learn: + Touse lists to store items. + Toaccess, retrieve and modify items in a list. + ToSort or arrange the items in alist. + Tolterate through the items ina list. + How to create lists on the fly using list comprehension, Introduction When it comes to managing collections of data in Python, one of the most versatile and fundamental data structures is the list. Lists can hold items of different data types and are created by enclosing items or objects ina square bracket, with each item separated by a comma. L=112,3,4,5] An empty list is represented by a pair of square brackets with nothing in-between: L-(] Lists are mutable, meaning that they can be modified after creation and serve as versatile containers capable of storing a diverse range of data items, including items of different types. This means that you can store items of different data types such as numbers, strings and even lists or other data types in the same list. heterogeneous ist L=[age,, 2.34, True, 250] Also, lists can be nested, which means you can have lists within lists, forming a matrix or a multi-dimensional structure, This nesting capability allows you to create complex data structures where each element of the outer list can contain its own list. using list to form a matrix L=[[1,2,3], [4,5,6],[7,8,9], [10,11,12]] Indexing You can access individual items by using their index. So, if you have a list with § items, the first item's index is 0, the second item's index is 1, and soon. The index of the last item in the list is always one less than the total number of items in the list. Hence, if you have 5 items, the last item's indexis 4 #indexing in lists colours = ‘orange’, ‘purple,, ‘green’, ‘red’, ‘brown'] print(coloursloD print(colours{1) print(colours{2) print(colours{3). print(coloursi4), Output: orange purple green red brown, Pro Tip: The index of the last item in the list will be n-1, where n represents the total number of items present in the list. So, if you have a list with 5 items, the indices would range from 0 to 4 In above example, items in the list were accessed using positive indexes. However, you can also use negative indexes to do the same thing! Instead of starting from 0 like in positive indexes, negative indexes start counting from the end of the list. negative indexes print(colours(-1)) print(colours(-2)) print(colours(-3)) print(colours(-4)) print(colours(-5)) Output: brown red green purple orange Slicing Slicing allows you to extract or fetch either specific items or a range of items froma list. The syntax to slice a list looks like this: List{start : end] ‘This will return all the items starting from the item with the index “start' and stopping but excluding the item with the index ‘end”. #slicinga list result = colours(1:4] print(result) Output: (purple, ‘green, red’) Now, let's say you want to slice a list, but instead of grabbing all the items within a range, you actually want to skip or leave out some of them. By adding an extra component to the slicing syntax, called the 'step" value, you can specify how many items to skip between each item you want to include in the slice. This way, you have full control over which items to include or exclude. Take a look at this list: L=[1,2,3,4,5,6,7,8,9,10] To extract a portion of this list, beginning from index 4 and extending up to the last item with index 9, you can use the following synti {4:10} Output: (5,67, 8,9, 10] However, if you want to skip the item right after a selected index, or maybe you want to select every second item in the list, then you will include a step value as shown below: 1{4:10:2] Output: (5,7, 9] ‘Adding itemsto list To add an item to an empty list or a list with an already existing item. The following methods are used: + append) + insert) Append() method The append() method serves to insert or add a specified item at the end of alist. It modifies the list in place and does not return a new list. Pro Tip: Modifying a list in place means changing the contents of the existing list without creating a new list. When you modify a list in place, you are directly altering the original list object rather than creating a new one. In the example below, the append method is used to add items to an empty list. L=(] L.append(1) print(L) L.append(2) print(t) Lappend(4) print(L) Output: a 0,2) (12,41 Insert() method The insert() method in provides a way to add items toa list at any desired position, rather than just adding them as the last items. You are required to provide the item and index where the item will be added to the list. fruits = ‘orange’, ‘apple’, ‘grape'] fruits.insert(1, ‘strawberry’) print(fruits) In the above example, the item "strawberry" was added to the list at the index of 1. Output: [orange ‘strawberry’, ‘apple’, 'grape'] Removing items froma list ‘When it comes to removing items from a list, you have two methods at your disposal and they include: + pop0 + remove() Let's take a closer look at each of them. The pop() method This is used to remove and return an element from a list based on its index. Aside from removing items from a list, the pop() method returns the item removed from the list as shown below: Pro Tip: If you want to specifically remove the last item in a list, you can simply call pop0 without providing any arguments. pop method fruits = orange, ‘strawberry’, ‘apple’, grape] fruit = fruits.pop0 print(fruits) print(fruit) Output: Corange;, ‘strawberry’, apple’) grape In the above example, the pop() method was used to remove the last element from a list and retrieve its value at the same time. However, if you want to remove an item in a given position, you can provide the index as the argument to the pop method. #pop method with argument fruits = orange, strawberry’, ‘apple’, ‘grape!] fruit = fruits.pop(2) print(fruits) Output: (orange, ‘strawberry’, ‘grape'] Remove() method The remove method is used to remove the first occurrence of a given item in a list. To remove the first occurrence of a specific item froma list using the remove() method, you need to provide an argument that corresponds to the item you wish to remove. #remove method fruits = orange’, ‘strawberry’, ‘apple’, ‘grape fruits.remove(‘apple’) print(fruits) ‘strawberry’, ‘grapel]

You might also like