Python Programming Introduction PDF
Document Details
Uploaded by PromptWolf
Hadhramout University of Science and Technology
Dr. Ahmed Alnasheri
Tags
Summary
This document is an introduction to Python programming. It covers the basics of Python, including installation, features, history, and objectives. It's geared towards those new to Python programming.
Full Transcript
PYTHON PROGRAMMING INTRODUCTION Unit 1: Introduction to Python and installation Python Programming : Lecture One Dr. Ahmed Alnasheri 1 Course Description This course is framed to cover Python Basics like Data type...
PYTHON PROGRAMMING INTRODUCTION Unit 1: Introduction to Python and installation Python Programming : Lecture One Dr. Ahmed Alnasheri 1 Course Description This course is framed to cover Python Basics like Data types, Lists, tuples, Dictionaries, Loops, functions in detail. Learn to use Object Oriented Programming with classes. Besides that, it will covers advanced level like Python for Machine Learning, AI, Web development and Data Science. Python Programming : Lecture One Dr. Ahmed Alnasheri 2 Course Objectives Establish a broad background in Python programming. Prepare you for the inevitable (necessary) coding interview Survey popular tools in academia/industry for data analysis and exploration Learn how to read documentation and quickly get new tools up and running Learn basic distributed computing frameworks Python Programming : Lecture One Dr. Ahmed Alnasheri 3 Books & References Sr. No. Title Author / s Publisher Edition Year 1 Think Python Allen Downey O’Reilly 1 2012 2 An Introduction to Computer Thomas Erl, Zaigham SPD 1 2014 Science using Python Mahmood, and Ricardo 3 Python GUI Programming Burkhard A. Meier Packt 1 2015 Cookbook 4 Introduction to Problem Solving E. Balagurusamy TMH 1 2015 with Python 5 Murach’s Python programming Joel Murach, Michael SPD 1 2017 Urban 6 Object-oriented Programming in Michael H. Goldwasser, Pearson 1 2008 Python David Letscher Prentice Hall 7 Exploring Python Budd TMH 1 2016 Python Programming : Lecture One Dr. Ahmed Alnasheri 4 Outline of this lecture 1.0 Objectives 1.1 Introduction: The Python Programming Language 1.2 History 1.3 Features 1.4 Installing Python 1.5 Running Python program 1.6 Debugging 1.6.1 Syntax Errors 1.6.2 Runtime Errors 1.6.3 Semantic Errors 1.6.4 Experimental Debugging 1.7 Formal and Natural Languages 1.8 The Difference Between Brackets, Braces, and Parentheses 1.9 Summary 1.10 References 1.11 Unit End Exercise Python Programming : Lecture One Dr. Ahmed Alnasheri 5 Lecture Objectives After reading through this chapter, you will be able to : To understand and use the basic of python. To understand the history and features of python programming. To understand the installation of python. To handle the basis errors in python. To understand the difference between brackets, braces and parenthesis. Python Programming : Lecture One Dr. Ahmed Alnasheri 6 INTRODUCTION: THE PYTHON PROGRAMMING LANGUAGE Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming language. Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc. We don’t need to use data types to declare variable because it is dynamically typed so we can write a=10 to declare an integer value in a variable. Python makes the development and debugging fast because there is no compilation step included in python development. Python Programming : Lecture One Dr. Ahmed Alnasheri 7 INTRODUCTION: THE PYTHON PROGRAMMING LANGUAGE Easy to interface with C/ObjC/Java/Fortran Easy-ish (Quite easy) to interface with C++ (via SWIG) Great interactive environment Downloads: http://www.python.org Documentation: http://www.python.org/doc/ Free book: http://www.diveintopython.org Python Programming : Lecture One Dr. Ahmed Alnasheri 8 HISTORY Python was first introduced by Guido Van Rossum in 1991 at the National Research Institute for Mathematics and Computer Science, Netherlands. Though the language was introduced in 1991, the development began in the 1980s. Previously van Rossum worked on the ABC language at Centrum Wiskunde & Informatica (CWI) in the Netherlands. The ABC language was capable of exception handling and interfacing with the Amoeba operating system. Inspired by the language, Van Rossum first tried out making his own version of it. Python is influenced by programming languages like: ABC language, Modula-3, Python is used for software development at companies and organizations such as Google, Yahoo, CERN, Industrial Light and Magic, and NASA. Why the Name Python? Python developer, Rossum always wanted the name of his new language to be short, unique, and mysterious. Inspired by Monty Python’s Flying Circus, a BBC comedy series, he named it Python. Python Programming : Lecture One Dr. Ahmed Alnasheri 9 FEATURES There are a lot of features provided by python programming language as follows: 1. Easy to Code: Python is a very developer-friendly language which means that anyone and everyone can learn to code it in a couple of hours or days. As compared to other object-oriented programming languages like Java, C, C++, and C#, Python is one of the easiest to learn. 2. Open Source and Free: Python is an open-source programming language which means that anyone can create and contribute to its development. Python has an online forum where thousands of coders gather daily to improve this language further. Along with this Python is free to download and use in any operating system, be it Windows, Mac or Linux. Python Programming : Lecture One Dr. Ahmed Alnasheri 10 FEATURES 3. Support for GUI: GUI or Graphical User Interface is one of the key aspects of any programming language because it has the ability to add flair to code and make the results more visual. Python has support for a wide array of GUIs which can easily be imported to the interpreter, thus making this one of the most favorite languages for developers. 4. Object-Oriented Approach: One of the key aspects of Python is its object-oriented approach. This basically means that Python recognizes the concept of class and object encapsulation thus allowing programs to be efficient in the long run. Python Programming : Lecture One Dr. Ahmed Alnasheri 11 FEATURES 5. Highly Portable: Suppose you are running Python on Windows and you need to shift the same to either a Mac or a Linux system, then you can easily achieve the same in Python without having to worry about changing the code. This is not possible in other programming languages, thus making Python one of the most portable languages available in the industry. 6. Highly Dynamic Python is one of the most dynamic languages available in the industry today. What this basically means is that the type of a variable is decided at the run time and not in advance. Due to the presence of this feature, we do not need to specify the type of the variable during coding, thus saving time and increasing efficiency Python Programming : Lecture One Dr. Ahmed Alnasheri 12 FEATURES 7. Large Standard Library: Out of the box, Python comes inbuilt with a large number of libraries that can be imported at any instance and be used in a specific program. The presence of libraries also makes sure that you don’t need to write all the code yourself and can import the same from those that already exist in the libraries. 8. Databases: Python provides interfaces to all major commercial databases. 9. Scalable: Python provides a better structure and support for large programs than shell scripting. Python Programming : Lecture One Dr. Ahmed Alnasheri 13 What can you do with Python? You can do some things include: Data analysis and machine learning Web development Automation or scripting Software testing and prototyping Everyday tasks Visual Programming Python Programming : Lecture One Dr. Ahmed Alnasheri 14 Why Python? Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Since it's relatively easy to learn: Python has been adopted by many non-programmers such as accountants and scientists, for a variety of everyday tasks, like organizing finances. Python Programming : Lecture One Dr. Ahmed Alnasheri 15 Why Python so popular? Python is popular for several reasons. Here's a deeper look at what makes it versatile and easy for coders to use. It has a simple syntax that mimics natural language, so it’s easier to read and understand. This makes it quicker to build projects and faster to improve on them. It’s versatile (multiple usages). Python can be used for many different tasks, from web development to machine learning. It’s beginner friendly, making it popular for entry-level coders. It’s open source, which means it’s free to use and distribute, even for commercial purposes. Python’s archive of modules and libraries—bundles of code that third-party users have created to expand Python’s capabilities—is vast and growing. Python has a large and active community that contributes to Python’s pool of modules and libraries and acts as a helpful resource for other programmers. The vast support community means that when coders need help, finding a solution is relatively easy; somebody has likely encountered the same problem before. Python Programming : Lecture One Dr. Ahmed Alnasheri 16 Python Syntax vs other programming languages? Python's clean and readable syntax is one of its outstanding features. The language prioritizes code readability by using indentation to define blocks of code, making it highly accessible, especially for beginners and non-programmers. In contrast, languages like C and Java rely on curly braces and semicolons. Python Programming : Lecture One Dr. Ahmed Alnasheri 17 INSTALLING PYTHON To install Python, firstly download the Python distribution from official website of python (www.python.org/ download). Having downloaded the Python distribution now execute it. Setting Path in Python Before starting working with Python, a specific path is to set to set path follow the steps: Right click on My Computer--> Properties -->Advanced System setting -->Environment Variable -->New In Variable name write path and in Variable value copy path up to C:// Python (i.e., path where Python is installed). Click Ok ->Ok. Python Programming : Lecture One Dr. Ahmed Alnasheri 18 RUNNING PYTHON PROGRAM There are different ways of working in Python: (1) How to Execute Python Program Using Command Prompt: If you want to create a Python file in.py extension and run. You can use the Windows command prompt to execute the Python code. Python Programming : Lecture One Dr. Ahmed Alnasheri 19 RUNNING PYTHON PROGRAM Example: Here is the simple code of Python given in the Python file demo.py. It contains only single line code of Python which prints the text “Hello World!” on execution. So, how you can execute the Python program using the command prompt. To see this, you have to first open the command prompt using the ‘window+r’ keyboard shortcut. Now, type the word ‘cmd’ to open the command prompt. This opens the command prompt with the screen as given below. Change the directory location to the location where you have just saved your Python.py extension file. We can use the cmd command ‘cd’ to change the directory location. Use ‘cd..’ to come out of directory and “cd” to come inside of the directory. Get the file location where you saved your Python file. Python Programming : Lecture One Dr. Ahmed Alnasheri 20 RUNNING PYTHON PROGRAM To execute the Python file, you have to use the keyword ‘Python’ followed by the file name with extension.py See the example given in the screen above with the output of the file Python Programming : Lecture One Dr. Ahmed Alnasheri 21 RUNNING PYTHON PROGRAM (2) Interactive Mode to Execute Python Program: To execute the code directly in the interactive mode. You have to open the interactive mode. Press the window button and type the text “Python”. Click the “Python 3.7(32 bit) Desktop app” as given below to open the interactive mode of Python. Python Programming : Lecture One Dr. Ahmed Alnasheri 22 RUNNING PYTHON PROGRAM Python Programming : Lecture One Dr. Ahmed Alnasheri 23 RUNNING PYTHON PROGRAM You can type the Python code directly in the Python interactive mode. Here, in the image below contains the print program of Python. Press the enter button to execute the print code of Python. The output gives the text “Hello World!” after you press the enter button. Type any code of Python you want to execute and run directly on interactive mode. Python Programming : Lecture One Dr. Ahmed Alnasheri 24 RUNNING PYTHON PROGRAM (3) Using IDLE (Python GUI) to Execute Python Program: Another useful method of executing the Python code. Use the Python IDLE GUI Shell to execute the Python program on Windows system. Open the Python IDLE shell by pressing the window button of the keyboard. Type “Python” and click the “IDLE (Python 3.7 32 bit)” to open the Python shell. Python Programming : Lecture One Dr. Ahmed Alnasheri 25 RUNNING PYTHON PROGRAM (3) Using IDLE (Python GUI) to Execute Python Program: Another useful method of executing the Python code. Use the Python IDLE GUI Shell to execute the Python program on Windows system. Open the Python IDLE shell by pressing the window button of the keyboard. Type “Python” and click the “IDLE (Python 3.7 32 bit)” to open the Python shell. Python Programming : Lecture One Dr. Ahmed Alnasheri 26 RUNNING PYTHON PROGRAM Python Programming : Lecture One Dr. Ahmed Alnasheri 27 RUNNING PYTHON PROGRAM Create a Python file with.py extension and open it with the Python shell. The file looks like the image given below. Python Programming : Lecture One Dr. Ahmed Alnasheri 28 RUNNING PYTHON PROGRAM It contains the simple Python code which prints the text “Hello World!”. In order to execute the Python code, you have to open the ‘run’ menu and press the ‘Run Module’ option. Python Programming : Lecture One Dr. Ahmed Alnasheri 29 RUNNING PYTHON PROGRAM A new shell window will open which contains the output of the Python code. Create your own file and execute the Python code using this simple method using Python IDLE. Python Programming : Lecture One Dr. Ahmed Alnasheri 30 DEBUGGING Debugging means the complete control over the program execution. Developers use debugging to overcome program from any bad issues. Debugging is a healthier process for the program and keeps the diseases bugs far away. Python also allows developers to debug the programs using pdb module that comes with standard Python by default. We just need to import pdb module in the Python script. Using pdb module, we can set breakpoints in the program to check the current status. We can Change the flow of execution by using jump, continue statements. Python Programming : Lecture One Dr. Ahmed Alnasheri 31 DEBUGGING Syntax Error: Errors are the mistakes or faults performed by the user which results in abnormal working of the program. However, we cannot detect programming errors before the compilation of programs. The process of removing errors from a program is called Debugging. A syntax error occurs when we do not use properly defined syntax in any programming language. For example: incorrect arguments, indentation, use of undefined variables etc. Example: age=16 if age>18: print ("you can vote”) # syntax error because of not using indentation else print ("you cannot vote”) #syntax error because of not using indentation Python Programming : Lecture One Dr. Ahmed Alnasheri 32 DEBUGGING Runtime Errors: The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened. Some examples of Python runtime errors: division by zero performing an operation on incompatible types using an identifier which has not been defined accessing a list element, dictionary value or object attribute which doesn’t exist trying to access a file which doesn’t exist Python Programming : Lecture One Dr. Ahmed Alnasheri 33 DEBUGGING Semantic Errors: The third type of error is the semantic error. If there is a semantic error in your program, it will run successfully in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing. Python Programming : Lecture One Dr. Ahmed Alnasheri 34 DEBUGGING Experimental Debugging: One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming. Debugging is also like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again. For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a program that does something and make small modifications, debugging them as you go, so that you always have a working program. Python Programming : Lecture One Dr. Ahmed Alnasheri 35 FORMAL AND NATURAL LANGUAGES Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally. Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. Programming languages are formal languages that have been designed to express computations. Formal languages tend to have strict rules about syntax. For example, 3 + 3 = 6 is a syntactically correct mathematical statement. Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. The second type of syntax rule pertains to the structure of a statement; that is, the way the tokens are arranged. The statement 3+ = 3 is illegal because even though + and = are legal tokens, you can’t have one right after the other. Python Programming : Lecture One Dr. Ahmed Alnasheri 36 THE DIFFERENCE BETWEEN BRACKETS, BRACES, AND PARENTHESES Brackets [ ]: Brackets are used to define mutable data types such as list or list comprehensions. Example: To define a list with name as L1 with three elements 10,20 and 30 >>> L1 = [10,20,30] >>> L1 [10,20,30] Brackets can be used for indexing and lookup of elements Example: >>>L1 = 40 >>>L1 [10,40,30] Example: To lookup the element of list L1 >>> L1 10 Brackets can be used to access the individual characters of a string or to make string slicing Example: Lookup the first characters of string str>>>’mumbai’ >>> str ‘m’ Example: To slice a string >>> str [1:4] ‘umb’ Python Programming : Lecture One Dr. Ahmed Alnasheri 37 THE DIFFERENCE BETWEEN BRACKETS, BRACES, AND PARENTHESES Braces {} Curly braces are used in python to define set or dictionary. Example: Create a set with three elements 10,20,30. >>> s1 = {10,20,30} >>> type(s1) Example: Create a dictionary with two elements with keys, ‘rollno’ and ‘name’ >>> d1= {‘rollno’:101, ‘name’:’ Vivek’} >>> type(d1) Brackets can be used to access the value of dictionary element by specifying the key. >>> d1[‘rollno’] 101 Python Programming : Lecture One Dr. Ahmed Alnasheri 38 THE DIFFERENCE BETWEEN BRACKETS, BRACES, AND PARENTHESES Parentheses ( ) Parentheses can be used to create immutable sequence data type tuple. Example: Create a tuple named ‘t1’ with elements 10,20,30 >>> t1= (10,20,30) >>> type(t1) Parentheses can be used to define the parameters of function definition and function call. Example: Multiply two numbers using a function def mul(a,b): returns a*b x=2 y=3 z=mul (2,3) print(x,’*’,y,’=’z) In the function definition def mul(a,b) formal parameters are specified using parentheses In the function call z=mul (2,3) actual values are specified using parenthesis Python Programming : Lecture One Dr. Ahmed Alnasheri 39 SUMMARY In this chapter we studied Introduction, history, features of Python Programming Language. We don’t need to use data types to declare variable because it is dynamically typed so we can write a=10 to declare an integer value in a variable. In this chapter we are more focused on types of errors in python like syntax error, runtime error, semantic error and experimental debugging. Execution of Python Program Using Command Prompt and Interactive Mode to Execute Python Program. Also, we studied Difference between Brackets, Braces, and Parentheses in python. Python Programming : Lecture One Dr. Ahmed Alnasheri 40 REFERENCES 1) www.journaldev.com 2) www.edureka.com 3) www.tutorialdeep.com 4) www.xspdf.com 5) Think Python by Allen Downey 1st edition. 6) Python Programming for Beginners By Prof. Rahul E. Borate, Dr. Sunil Khilari, Prof. Rahul S. Navale. Python Programming : Lecture One Dr. Ahmed Alnasheri 41 Homework 1 Use a web browser to go to the Python website http: // python.org. This page contains information about Python and links to Python related pages, and it gives you the ability to search the Python documentation. For example, if you enter print in the search window, the first link that appears is the documentation of the print statement. At this point, not all of it will make sense to you, but it is good to know where it is. Start the Python interpreter and type help () to start the online help utility. Or you can type help ('print') to get information about the print statement. Python Programming : Lecture One Dr. Ahmed Alnasheri 42 PYTHON PROGRAMMING CONDITIONAL STATEMENTS, LOOPING, CONTROL STATEMENTS Unit 3: CONDITIONAL STATEMENTS, LOOPING, CONTROL STATEMENTS Python Programming : Lecture Two Dr. Ahmed Alnasheri 1 Outline of This Lecture 3.0 Objectives 3.1 Introduction 3.2 Conditional Statements: 3.2.1 if statement 3.2.2 if-else, 3.2.3 if...elif...else 3.2.4 nested if –else 3.3 Looping Statements: 3.3.1 for loop 3.3.2 while loop 3.3.3 nested loops 3.4 Control statements: 3.4.1 Terminating loops 3.4.2 skipping specific conditions 3.5 Summary 3.6 References 3.7 Unit End Exercise Python Programming : Lecture Two Dr. Ahmed Alnasheri 2 Lecture Objectives After reading through this chapter, you will be able to : To understand and use the conditional statements in python. To understand the loop control in python programming. To understand the control statements in python. To understand the concepts of python and able to apply it for solving the complex problems. Python Programming : Lecture Two Dr. Ahmed Alnasheri 3 INTRODUCTION In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement: if x > 0: print 'x is positive' The Boolean expression after if is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens. if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements. Python Programming : Lecture Two Dr. Ahmed Alnasheri 4 INTRODUCTION There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements. In that case, you can use the pass statement, which does nothing. if x < 0: pass # need to handle negative values! Python Programming : Lecture Two Dr. Ahmed Alnasheri 5 CONDITIONAL STATEMENTS Conditional Statement in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. Conditional statements are handled by IF statements in Python. Story of Two if’s: Consider the following if statement, coded in a C-like language: if (p > q) { p = 1; q = 2; } Now, look at the equivalent statement in the Python language: if p > q: p = 1 q = 2 what Python adds what Python removes Python Programming : Lecture Two Dr. Ahmed Alnasheri 6 CONDITIONAL STATEMENTS Parentheses are optional if (x < y) ---> if x < y 2) End-of-line is end of statement: C-like languages x = 1; Python language x=1 End of indentation is end of block Why Indentation Syntax? A Few Special Cases a = 1; b = 2; print (a + b) You can chain together only simple statements, like assignments, prints, and function calls. Python Programming : Lecture Two Dr. Ahmed Alnasheri 7 CONDITIONAL STATEMENTS if statement Syntax if test expression: statement(s) Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True. If the test expression is False, the statement(s) is not executed. In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first un-indented line marks the end. Python interprets non-zero values as True. None and 0 are interpreted as False. Python Programming : Lecture Two Dr. Ahmed Alnasheri 8 CONDITIONAL STATEMENTS Example: Python if Statement # If the number is positive, we print an appropriate message num = 3 if num > 0: print (num, "is a positive number.") print ("This is always printed.") num = -1 if num > 0: print (num, "is a positive number.") print ("This is also always printed.") When you run the program, the output will be: 3 is a positive number. This is always printed. This is also always printed. Python Programming : Lecture Two Dr. Ahmed Alnasheri 9 CONDITIONAL STATEMENTS Example: Python if Statement In the previous example, num > 0 is the test expression. The body of if is executed only if this evaluates to True. When the variable num is equal to 3, test expression is true and statements inside the body of if are executed. If the variable num is equal to -1, test expression is false and statements inside the body of if are skipped. The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test expression. Python Programming : Lecture Two Dr. Ahmed Alnasheri 10 CONDITIONAL STATEMENTS if-else statement Syntax if test expression: Body of if else: Body of else The if...else statement evaluates test expression and will execute the body of if only when the test condition is True. If the condition is False, the body of else is executed. Indentation is used to separate the blocks. Python Programming : Lecture Two Dr. Ahmed Alnasheri 11 CONDITIONAL STATEMENTS Example of if...else # Program checks if the number is positive or negative # And displays an appropriate message num = 3 # Try these two variations as well. # num = -5 # num = 0 if num >= 0: print ("Positive or Zero") else: print ("Negative number") Python Programming : Lecture Two Dr. Ahmed Alnasheri 12 CONDITIONAL STATEMENTS Output Positive or Zero In the pervious example, when num is equal to 3, the test expression is true and the body of if is executed and the body of else is skipped. If num is equal to -5, the test expression is false and the body of else is executed and the body of if is skipped. If num is equal to 0, the test expression is true and body of if is executed and body of else is skipped. Python Programming : Lecture Two Dr. Ahmed Alnasheri 13 CONDITIONAL STATEMENTS if...elif...else Statement Syntax if test expression: Body of if elif test expression: Body of elif else: Body of else The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, the body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks. Python Programming : Lecture Two Dr. Ahmed Alnasheri 14 CONDITIONAL STATEMENTS Example of if...elif...else '''In this program, we check if the number is positive or negative or zero and display an appropriate message''' num = 3.4 # Try these two variations as well: # num = 0 When variable num is positive, Positive #num = -4.5 number is printed. if num > 0: print ("Positive number") If num is equal to 0, Zero is printed. elif num == 0: print("Zero") If num is negative, Negative number is p else: print ("Negative number") Python Programming : Lecture Two Dr. Ahmed Alnasheri 15 CONDITIONAL STATEMENTS nested if – else We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary Python Programming : Lecture Two Dr. Ahmed Alnasheri 16 CONDITIONAL STATEMENTS Python Nested if Example '''In this program, we input a number check if the number is positive or negative or zero and display an appropriate message This time we use nested if statement''‘ num = float (input ("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print ("Positive number") else: print ("Negative number") Python Programming : Lecture Two Dr. Ahmed Alnasheri 17 CONDITIONAL STATEMENTS Output1 Enter a number: 5 Positive number Output2 Enter a number: -1 Negative number Output3 Enter a number: 0 Zero Python Programming : Lecture Two Dr. Ahmed Alnasheri 18 LOOPING STATEMENTS In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Dr. Ahmed Alnasheri Python Programming : Lecture Two 19 LOOPING STATEMENTS for loop The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal. Syntax of for Loop for val in sequence: Body of for Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation. Python Programming : Lecture Two Dr. Ahmed Alnasheri 20 LOOPING STATEMENTS Example: Python for Loop # Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list for val in numbers: sum = sum+val print ("The sum is", sum) When you run the program, the output will be: The sum is 48 Python Programming : Lecture Two Dr. Ahmed Alnasheri 21 LOOPING STATEMENTS The range () function We can generate a sequence of numbers using range () function. range (10) will generate numbers from 0 to 9 (10 numbers). We can also define the start, stop and step size as range (start, stop,step_size). step_size defaults to 1, start to 0 and stop is end of object if not provided. This function does not store all the values in memory; it would be inefficient. So, it remembers the start, stop, step size and generates the next number on the go. To force this function to output all the items, we can use the function list(). Python Programming : Lecture Two Dr. Ahmed Alnasheri 22 LOOPING STATEMENTS The range () function Example print(range(10)) print(list(range(10))) print (list (range (2, 8))) print (list (range (2, 20, 3))) Output: range (0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7] [2, 5, 8, 11, 14, 17] Python Programming : Lecture Two Dr. Ahmed Alnasheri 23 LOOPING STATEMENTS The range () function Example We can use the range () function in for loops to iterate through a sequence of numbers. It can be combined with the len () function to iterate through a sequence using indexing. Here is an example. # Program to iterate through a list using indexing city = ['pune', 'mumbai', 'delhi'] # iterate over the list using index for i in range(len(city)): print ("I like", city[i]) Output: I like pune I like mumbai I like delhi Python Programming : Lecture Two Dr. Ahmed Alnasheri 24 LOOPING STATEMENTS for loop with else A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts. The break keyword can be used to stop a for loop. In such cases, the else part is ignored. Hence, a for loop's else part runs if no break occurs. Example: digits = [0, 1, 5] for i in digits: print(i) else: print("No items left.") When you run the program, the output will be: 015 No items left. Python Programming : Lecture Two Dr. Ahmed Alnasheri 25 LOOPING STATEMENTS for loop with else Here, the for loop prints items of the list until the loop exhausts. When the for-loop exhausts, it executes the block of code in the else and prints No items left. This for...else statement can be used with the break keyword to run the else block only when the break keyword was not executed. Example: # program to display student's marks from record student_name = 'Soyuj' marks = {'Ram': 90, 'Shayam': 55, 'Sujit': 77} for student in marks: if student == student_name: print(marks[student]) break else: print ('No entry with that name found.') Output: No entry with that name found. Python Programming : Lecture Two Dr. Ahmed Alnasheri 26 LOOPING STATEMENTS while loop The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use while loop when we don't know the number of times to iterate beforehand. Syntax of while Loop in Python while test_expression: Body of while In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False. In Python, the body of the while loop is determined through indentation. The body starts with indentation and the first unindented line marks the end. Python interprets any non-zero value as True. None and 0 are interpreted as False. Python Programming : Lecture Two Dr. Ahmed Alnasheri 27 LOOPING STATEMENTS Example: Python while Loop # Program to add natural numbers up to sum = 1+2+3+...+n # To take input from the user, When you run the program, the output will # n = int (input ("Enter n: ")) be: Enter n: 10 The sum is 55 n = 10 In the above program, the test expression will # initialize sum and counter be True as long as our counter variable i is sum = 0 less than or equal to n (10 in our program). i=1 We need to increase the value of the counter while i >> import math >>>math.pi 3.141592653589793 Another well-known mathematical constant defined in the math module is e. It is called Euler's number and it is a base of the natural logarithm. Its value is 2.718281828459045. >>> import math >>>math.e 2. 718281828459045 Python Programming : Lecture Four Dr. Ahmed Alnasheri 14 MATH FUNCTIONS The math module contains functions for calculating various trigonometric ratios for a given angle. The functions (sin, cos, tan, etc.) need the angle in radians as an argument. We, on the other hand, are used to express the angle in degrees. The math module presents two angle conversion functions: degrees () and radians (), to convert the angle from degrees to radians and vice versa. >>> import math >>>math.radians(30) 0.5235987755982988 >>>math.degrees(math.pi/6) 29.999999999999996 math.log() The math.log() method returns the natural logarithm of a given number. The natural logarithm is calculated to the base e. >>> import math >>>math.log(10) 2.302585092994046 Python Programming : Lecture Four Dr. Ahmed Alnasheri 15 MATH FUNCTIONS math.exp() The math.exp() method returns a float number after raising e to the power of the given number. In other words, exp(x) gives e**x. >>> import math >>>math.exp(10) 22026.465794806718 math.pow() The math.pow() method receives two float arguments, raises the first to the second and returns the result. In other words, pow(4,4) is equivalent to 4**4. >>> import math >>>math.pow(2,4) 16.0 >>> 2**4 16 math.sqrt() The math.sqrt() method returns the square root of a given number. >>> import math >>>math.sqrt(100) 10.0 >>>math.sqrt(3) 1.7320508075688772 Python Programming : Lecture Four Dr. Ahmed Alnasheri 16 ADDING NEW FUNCTIONS So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that execute when the function is called. Example: def print_lyrics(): print ("I'm a lumberjack, and I'm okay.") print ("I sleep all night and I work all day.") def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name. Python Programming : Lecture Four Dr. Ahmed Alnasheri 17 ADDING NEW FUNCTIONS The empty parentheses after the name indicate that this function doesn’t take any arguments. The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces.The body can contain any number of statements. The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote appears in the string. Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeat_lyrics: Python Programming : Lecture Four Dr. Ahmed Alnasheri 18 ADDING NEW FUNCTIONS def repeat_lyrics(): print_lyrics() print_lyrics() And then call repeat_lyrics: >>> repeat_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day. I'm a lumberjack, and I'm okay. I sleep all night and I work all day. Python Programming : Lecture Four Dr. Ahmed Alnasheri 19 DEFINITIONS AND USES Pulling together the code fragments from the previous section, the whole program looks like this: def print_lyrics (): print ("I'm a lumberjack, and I'm okay.") print ("I sleep all night and I work all day.") def repeat_lyrics (): print_lyrics () print_lyrics () repeat_lyrics () This program contains two function definitions: print_lyrics and repeat_lyrics. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output. Python Programming : Lecture Four Dr. Ahmed Alnasheri 20 DEFINITIONS AND USES Pulling together the code fragments from the previous section, the whole program looks like this: def print_lyrics (): print ("I'm a lumberjack, and I'm okay.") print ("I sleep all night and I work all day.") def repeat_lyrics (): print_lyrics () print_lyrics () repeat_lyrics () This program contains two function definitions: print_lyrics and repeat_lyrics. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output. Python Programming : Lecture Four Dr. Ahmed Alnasheri 21 DEFINITIONS AND USES Flow of Execution In order to ensure that a function is defined before its first use, you have to know the order in which statements are executed, which is called the flow of execution. Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom. Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called. A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off. When you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution. Python Programming : Lecture Four Dr. Ahmed Alnasheri 22 DEFINITIONS AND USES Parameters and Arguments Some of the built-in functions we have seen require arguments. For example, when you call math.sin you pass a number as an argument. Some functions take more than one argument: math.pow takes two, the base and the exponent. Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument. def print_twice(bruce): print(bruce) print(bruce) This function assigns the argument to a parameter named bruce. When the function is called, it prints the value of the parameter twice. >>> print_twice('Spam') Spam Spam >>> print_twice (17) 17 17 >>> print_twice(math.pi) 3.14159265359 3.14159265359 Python Programming : Lecture Four Dr. Ahmed Alnasheri 23 DEFINITIONS AND USES Parameters and Arguments The same rules of composition that apply to built-in functions also apply to user-defined functions, so we can use any kind of expression as an argument for print_twice. >>> print_twice ('Spam '*4) Spam SpamSpamSpam Spam SpamSpamSpam >>> print_twice(math.cos(math.pi)) -1.0 -1.0 The argument is evaluated before the function is called, so in the examples the expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once. Python Programming : Lecture Four Dr. Ahmed Alnasheri 24 DEFINITIONS AND USES Variables and Parameters Are Local When you create a variable inside a function, it is local, which means that it only exists inside the function. For example def cat_twice(part1, part2): cat = part1 + part2 print_twice(cat) This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it: >>> line1 = 'Bing tiddle ' >>> line2 = 'tiddle bang.' >>> cat_twice(line1, line2) Bing tiddle tiddle bang. Bing tiddle tiddle bang. When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an exception: >>> print cat NameError: name 'cat' is not defined Parameters are also local. For example, outside print_twice, there is no such thing as bruce. Python Programming : Lecture Four Dr. Ahmed Alnasheri 25 DEFINITIONS AND USES Stack Diagrams To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to. Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure. Python Programming : Lecture Four Dr. Ahmed Alnasheri 26 DEFINITIONS AND USES Stack Diagrams The frames are arranged in a stack that indicates which function called which, and so on. In this example, print_twice was called by cat_twice, and cat_twice was called by __main__, which is a special name for the topmost frame. When you create a variable outside of any function, it belongs to __main__. Each parameter refers to the same value as its corresponding argument. So, part1 has the same value as line1, part2 has the same value as line2, and bruce has the same value as cat. If an error occurs during a function call, Python prints the name of the function, and the name of the function that called it, and the name of the function that called that, all the way back to __main__. Python Programming : Lecture Four Dr. Ahmed Alnasheri 27 FRUITFUL FUNCTIONS AND VOID FUNCTIONS Some of the functions we are using, such as the math functions, yield results; for lack of a better name, I call them fruitful functions. Other functions, like print_twice, perform an action but don’t return a value. They are called void functions. When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression: x = math.cos(radians) golden = (math.sqrt(5) + 1) / 2 When you call a function in interactive mode, Python displays the result: >>>math.sqrt(5) 2.2360679774997898 But in a script, if you call a fruitful function all by itself, the return value is lost forever math.sqrt(5) This script computes the square root of 5, but since it doesn’t store or display the result, it is not very useful. Python Programming : Lecture Four Dr. Ahmed Alnasheri 28 FRUITFUL FUNCTIONS AND VOID FUNCTIONS Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None. >>> result = print_twice('Bing') Bing Bing >>> print(result) None The value None is not the same as the string 'None'. It is a special value that has its own type: >>> print type(None) The functions we have written so far are all void. Python Programming : Lecture Four Dr. Ahmed Alnasheri 29 WHY FUNCTIONS? It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons: Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug. Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place. Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole. Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it. Python Programming : Lecture Four Dr. Ahmed Alnasheri 30 IMPORTING WITH FROM, RETURN VALUES, INCREMENTAL DEVELOPMENT Importing with from: Python provides two ways to import modules, we have already seen one: >>> import math >>> print math >>> print math.pi 3.14159265359 If you import math, you get a module object named math. The module object contains constants like pi and functions like sin and exp. But if you try to access pi directly, you get an error. >>> print pi Traceback (most recent call last): File "", line 1, in NameError: name 'pi' is not defined Python Programming : Lecture Four Dr. Ahmed Alnasheri 31 IMPORTING WITH FROM, RETURN VALUES, INCREMENTAL DEVELOPMENT As an alternative, you can import an object from a module like this: >>> from math import pi Now you can access pi directly, without dot notation. >>> print pi 3.14159265359 Or you can use the star operator to import everything from the module: >>> from math import * >>> cos(pi) -1.0 The advantage of importing everything from the math module is that your code can be more concise. The disadvantage is that there might be conflicts between names defined in different modules, or between a name from a module and one of your variables Python Programming : Lecture Four Dr. Ahmed Alnasheri 32 BOOLEAN FUNCTIONS Syntax for boolean function is as follows Bool([value]) As we seen in the syntax that the bool() function can take a single parameter (value that needs to be converted). It converts the given value to True or False. If we don’t pass any value to bool() function, it returns False. bool() function returns a boolean value and this function returns False for all the following values 1. None 2. False 3. Zero number of any type such as int, float and complex. For example: 0, 0.0, 0j 4. Empty list [], Empty tuple (), Empty String ”. 5. Empty dictionary {}. 6. objects of Classes that implements __bool__() or __len()__ method, which returns 0 or False Python Programming : Lecture Four Dr. Ahmed Alnasheri 33 BOOLEAN FUNCTIONS Example: bool() function In the following example, we will check the output of bool() function for the given values. We have different values of different data types and we are printing the return value of bool() function in the output. # empty list lis = [] Output: print(lis,'is',bool(lis)) [] is False # empty tuple t = () print(t,'is',bool(t)) () is False # zero complex number c = 0 + 0j 0j is False print(c,'is',bool(c)) 99 is True num = 99 print(num, 'is', bool(num)) None is False val = None print(val,'is',bool(val)) True is True val = True print(val,'is',bool(val)) is False # empty string str = '' print(str,'is',bool(str)) Hello is True str = 'Hello' print(str,'is',bool(str)) Python Programming : Lecture Four Dr. Ahmed Alnasheri 34 MORE RECURSION, CHECKING TYPES What is recursion? Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively. In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions. Python Programming : Lecture Four Dr. Ahmed Alnasheri 35 MORE RECURSION, CHECKING TYPES Following is an example of a recursive function to find the factorial of an integer. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Example of a recursive function def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num)) Python Programming : Lecture Four Dr. Ahmed Alnasheri 36 MORE RECURSION, CHECKING TYPES Output: The factorial of 3 is 6 In the above example, factorial () is a recursive function as it calls itself. When we call this function with a positive integer, it will recursively call itself by decreasing the number. Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps. factorial (3) # 1st call with 3 3 * factorial (2) # 2nd call with 2 3 * 2 * factorial (1) # 3rd call with 1 3 * 2 * 1 # return from 3rd call as number=1 3 * 2 # return from 2nd call 6 # return from 1st call Python Programming : Lecture Four Dr. Ahmed Alnasheri 37 SUMMARY In this chapter we studied function call, type conversion functions in Python Programming Language. In this chapter we are more focused on math function and adding new function in python. Elaborating on definitions and uses of function, parameters and arguments in python. Also studied fruitful functions and void functions, importing with from, boolean functions and recursion in python. Python Programming : Lecture Four Dr. Ahmed Alnasheri 38 UNIT END EXERCISE Python Programming : Lecture Four Dr. Ahmed Alnasheri 39 REFERENCES https://www.tutorialsteacher.com/python/math-module https://greenteapress.com/thinkpython/html/thinkpython004.html https://beginnersbook.com/ https://www.programiz.com/python-programming/recursion www.journaldev.com www.edureka.com www.tutorialdeep.com www.xspdf.com Think Python by Allen Downey 1st edition. Python Programming : Lecture Four Dr. Ahmed Alnasheri 40 PYTHON PROGRAMMING STRINGS Unit 5: STRINGS Python Programming : Lecture Five Dr. Ahmed Alnasheri 1 Outline of This Lecture 5.1 A String is a Sequence 5.2 Traversal with a for Loop 5.3 String Slices 5.4 Strings Are Immutable 5.5 Searching 5.6 Looping and Counting 5.7 String Methods 5.8 The in Operator 5.9 String Comparison 5.10 String Operations 5.11 Summary 5.12 Questions 5.13 References Python Programming : Lecture Five Dr. Ahmed Alnasheri 2 Lecture Objectives After reading through this chapter, you will be able to : To learn how to crate string in Python To study looping and counting in Python To write programs for creating string methods in Python To understand various operators and string operation of Python To learn the string traversal with a for loop in Python Python Programming : Lecture Five Dr. Ahmed Alnasheri 3 A STRING IS A SEQUENCE There are numerous types of sequences in Python. Strings are a special type of sequence that can only store characters, and they have a special notation. Strings are sequences of characters and are immutable (unchangeable). A string is a sequence of characters. We can access the characters one at a time with the bracket operator: >>>food = 'roti' >>>letter = food The second statement retrieves the character at index position one from the food variable and assigns it to the letter variable which contain o. The expression in brackets is called an index. The index indicates which character in the sequence you required. Python Programming : Lecture Five Dr. Ahmed Alnasheri 4 A STRING IS A SEQUENCE Example. ‘I want to read book’. This is a string, It has been surrounded in single quotes. Declaring Python String String literals in Python String literals are surrounded by single quotes or double-quotes. ‘I want to read book’ “I want to read book’” You can also surround them with triple quotes (groups of 3 single quotes or double quotes). “””I want to read book’””” ”’ I want to read book’”’ Or using backslashes. >> ‘Thank\ Good Morning Sir !’ ‘ThanksGood Morning Sir!’ You cannot start a string with a single quote and end it with a double quote.. Python Programming : Lecture Five Dr. Ahmed Alnasheri 5 A STRING IS A SEQUENCE But if you surround a string with single quotes and also want to use single quotes as part of the string, you have to escape it with a backslash (\). ‘Send message to Madam\’s son ’ This statement causes a SyntaxError: ‘Send message to Madam’s son’ You can also do this with double-quotes. If you want to ignore escape sequences, you can create a raw string by using an ‘r’ or ‘R’ prefix with the string. Common escape sequences: \\ Backslash \n Linefeed \t Horizontal tab \’ Single quotes \” Double quotes. Python Programming : Lecture Five Dr. Ahmed Alnasheri 6 A STRING IS A SEQUENCE We can assign a string to a variable. name=’Sunil’ You can also create a string with the str() function. >>> str(567) Output: ‘567’ >>> str('Shri') Output: ‘Shri’ Python Programming : Lecture Five Dr. Ahmed Alnasheri 7 TRAVERSAL AND THE FOR LOOP: BY ITEM A lot of computations involve processing a collection one item at a time. For strings this means that we would like to process one character at a time. Often we start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. We have previously seen that the for statement can iterate over the items of a sequence (a list of names in the case below). for aname in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]: invitation = "Hi " + aname + ". Please come to my party on Saturday!" print(invitation) Recall that the loop variable takes on each value in the sequence of names. The body is performed once for each name. The same was true for the sequence of integers created by the range function. Python Programming : Lecture Five Dr. Ahmed Alnasheri 8 TRAVERSAL AND THE FOR LOOP: BY ITEM for avalue in range(10): print(avalue) Since a string is simply a sequence of characters, the for loop iterates over each character automatically. for achar in "Go Spot Go": print(achar) The loop variable achar is automatically reassigned each character in the string “Go Spot Go”. We will refer to this type of sequence iteration as iteration by item. Note that it is only possible to process the characters one at a time from left to right. Python Programming : Lecture Five Dr. Ahmed Alnasheri 9 TRAVERSAL AND THE FOR LOOP: BY ITEM Check your understanding Example: How many times is the word HELLO printed by the following statements? s = "python rocks" for ch in s: print("HELLO") Ans - Yes, there are 12 characters, including the blank. Example: How many times is the word HELLO printed by the following statements? s = "python rocks" for ch in s[3:8]: print("HELLO") Ans - Yes, The blank is part of the sequence returned by slice Python Programming : Lecture Five Dr. Ahmed Alnasheri 10 STRING SLICES Python slice string syntax is: str_object[start_pos:end_pos:step] The slicing starts with the start_pos index (included) and ends at end_pos index (excluded). The step parameter is used to specify the steps to take from start to end index. Python String slicing always follows this rule: s[:i] + s[i:] == s for any index ‘i’. All these parameters are optional – start_pos default value is 0, the end_pos default value is the length of string and step default value is 1. Let’s look at some simple examples of string slice function to create substring. s = 'HelloWorld' Output: print(s[:]) HelloWorld HelloWorld print(s[::]) Python Programming : Lecture Five Dr. Ahmed Alnasheri 11 STRING SLICES Note that since none of the slicing parameters were provided, the substring is equal to the original string. Let’s look at some more examples of slicing a string. s = 'HelloWorld' first_five_chars = s[:5] print(first_five_chars) Output: third_to_fifth_chars = s[2:5] Hello Llo print(third_to_fifth_chars) Note that index value starts from 0, so start_pos 2 refers to the third character in the string. Reverse a String using Slicing We can reverse a string using slicing by providing the step value as -1. s = 'HelloWorld' reverse_str = s[::-1] Output: dlroWolleH print(reverse_str) Python Programming : Lecture Five Dr. Ahmed Alnasheri 12 STRING SLICES Let’s look at some other examples of using steps and negative index values. s1 = s[2:8:2] Output: print(s1) loo Here the substring contains characters from indexes 2,4 and 6. s1 = s[8:1:-1] print(s1) Output: lroWoll Python Programming : Lecture Five Dr. Ahmed Alnasheri 13 STRINGS ARE IMMUTABLE The standard wisdom is that Python strings are immutable. You can't change a string's value, only the reference to the string. Like so: x = "hello" x = "goodbye" # New string! Which implies that each time you make a change to a string variable, you are actually producing a brand new string. Because of this, tutorials out there warn you to avoid string concatenation inside a loop and advise using join instead for performance reasons. Even the official documentation says so! This is wrong. Sort of. There is a common case for when strings in Python are actually mutable. I will show you an example by inspecting the string object's unique ID using the builtin id() function, which is just the memory address. The number is different for each object. (Objects can be shared though, such as with interning.) Python Programming : Lecture Five Dr. Ahmed Alnasheri 14 STRINGS ARE IMMUTABLE An unchanging article alludes to the item which is once made can’t change its worth all its lifetime. Attempt to execute the accompanying code: name_1 = "Aarun" name_1 = 'T' You will get a mistake message when you need to change the substance of the string. One potential arrangement is to make another string object with vital alterations: name_1 = "Aarun" name_2 = "T" + name_1[1:] print("name_1 = ", name_1, "and name_2 = ", name_2) Python Programming : Lecture Five Dr. Ahmed Alnasheri 15 SEARCHING Searching is a very basic necessity when you store data in different data structures. The simplest approach is to go across every element in the data structure and match it with the value you are searching for.This is known as Linear search. It is inefficient and rarely used, but creating a program for it gives an idea about how we can implement some advanced search algorithms. Linear Search: In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data structure. Python Programming : Lecture Five Dr. Ahmed Alnasheri 16 SEARCHING Example def linear_search(values, search_for): search_at = 0 search_res = False # Match the value with each data element Output: When the above code is executed, while search_at < len(values) and search_res is False: it produces the following result : if values[search_at] == search_for: True search_res = True False else: search_at = search_at + 1 return search_res l = [64, 34, 25, 12, 22, 11, 90] print(linear_search(l, 12)) print(linear_search(l, 91)) Python Programming : Lecture Five Dr. Ahmed Alnasheri 17 LOOPING AND COUNTING The following program counts the number of times the letter “r” appears in a string: word = 'raspberry' count = 0 for letter in word: if letter == 'r': count = count + 1 print(count) This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an “r” is found. When the loop exits, count contains the result: the total number of r’s. s = "peanut butter" count = 0 for char in s: if char == "t": count = count + 1 print(count) Python Programming : Lecture Five Dr. Ahmed Alnasheri 18 STRING METHODS Python has a set of built-in methods that you can use on strings. Note: All string methods returns new values. They do not change the original string. Python Programming : Lecture Five Dr. Ahmed Alnasheri 19 THE IN OPERATOR Now, let us take an example to get a better understanding of the in operator working. x in y Here “x” is the element and “y” is the sequence where membership is being checked. Let’s implement a simple Python code to demonstrate the use of the in operator and how the outputs would look like. vowels = ['A', 'E', 'I', 'O', 'U'] ch = input('Please Enter a Capital Letter:\n') if ch in vowels: print('You entered a vowel character') else: print('You entered a consonants character') Python Programming : Lecture Five Dr. Ahmed Alnasheri 20 STRING COMPARISON The following are the ways to compare two string in Python: 1. By using == (equal to) operator 2. By using != (not equal to) operator 3. By using sorted() method 4. By using is operator 5. By using Comparison operators Python Programming : Lecture Five Dr. Ahmed Alnasheri 21 STRING COMPARISON Comparing two strings using == (equal to) operator str1 = input("Enter the first String: ") str2 = input("Enter the second String: ") if str1 == str2: print ("First and second strings are equal and same") else: print ("First and second strings are not same") Output: Enter the first String: AA Enter the second String: AA First and second strings are equal and same Python Programming : Lecture Five Dr. Ahmed Alnasheri 22 STRING COMPARISON Comparing two strings using != (not equal to) operator str1 = input("Enter the first String: ") str2 = input("Enter the second String: ") if str1 != str2: print ("First and second strings are not equal.") else: print ("First and second strings are the same.") Output: Enter the first String: ab Enter the second String: ba First and second strings are not equal Python Programming : Lecture Five Dr. Ahmed Alnasheri 23 STRING COMPARISON Comparing two strings using the sorted() method: If we wish to compare two strings and check for their equality even if the order of characters/words is different, then we first need to use sorted() method and then compare two strings. str1 = input("Enter the first String: ") str2 = input("Enter the second String: ") if sorted(str1) == sorted(str2): print ("First and second strings are equal.") else: print ("First and second strings are not the same.") Output: Enter the first String: Engineering Discipline Enter the second String: Discipline Engineering First and second strings are equal. Python Programming : Lecture Five Dr. Ahmed Alnasheri 24 STRING COMPARISON Comparing two strings using ‘is’ operator Python is Operator returns True if two variables refer to the same object instance. str1 = "DEED" str2 = "DEED" str3 = ''.join(['D', 'E', 'E', 'D']) print(str1 is str2) print("Comparision result = ", str1 is str3) Output: True Comparision result = False In the above example, str1 is str3 returns False because object str3 was created differently. Python Programming : Lecture Five Dr. Ahmed Alnasheri 25 STRING COMPARISON Comparing two strings using comparison operators input = 'Engineering' print(input < 'Engineering') print(input > 'Engineering') print(input = 'Engineering') Output: False False True True Python Programming : Lecture Five Dr. Ahmed Alnasheri 26 STRING OPERATIONS String is an array of bytes that represent the Unicode characters in Python. Python does not support character datatype. A single character also works as a string. Python supports writing the string within a single quote('') and a double quote(""). Example "Python" or 'Python' Code SingleQuotes ='Python in Single Quotes' DoubleQuotes ="Python in Double Quotes" print(SingleQuotes) print(DoubleQuotes) Output: Python in Single Quotes Python in Double Quotes Python Programming : Lecture Five Dr. Ahmed Alnasheri 27 STRING OPERATIONS A single character is simply a string with a length of 1. The square brackets can be used to access the elements from the string. print() This function is used for displaying the output or result on the user screen. Syntax print('Text or Result') or print("Text or Result') Indexing in String It returns a particular character from the given string. Syntax getChar = a[index] message = "Hello, Python!" If I want to fetch the characters of the 7th index from the given string. Syntax print(string[index]) Code print(message) Python Programming : Lecture Five Dr. Ahmed Alnasheri 28 SUMMARY A Python String is an array of bytes demonstrating Unicode characters. Since there is no such data type called character data type in python, A single character is a string of length one. String handling is one of those activities in coding that programmers, use all the time. In Python, we have numerous built-in functions