Python Programming Unit- 1 Prof. Priyanka Sherkhane Department of Information Technology and Computer Science D. G. Ruparel College of Arts, Science and Commerce, Mumbai-16 Introduction • Python is a widely used general-purpose, high level programming language. • It was created by Guido van Rossum in 1991 and further developed by the Introduction to Python Programming Python Software Foundation. • It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. • Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. priyanka.sherkhane@ruparel.edu Why to Learn Python? • Python is Interpreted − Python is processed at runtime by the Introduction to Python Programming interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. • Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. • Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects. • Python has a simple syntax similar to the English language. • Python has syntax that allows developers to write programs with fewer lines than some other programming languages. priyanka.sherkhane@ruparel.edu Introduction to Python Programming Features of Python programming language priyanka.sherkhane@ruparel.edu History of Python • Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. History of Python Programming • Its implementation began in December 1989. • The programming language which Python is said to have succeeded is ABC Programming Language, which had the interfacing with the Amoeba Operating System and had the feature of exception handling. • Python 2.0 was released on 16 October 2000 with many major new features • Python 3.0 was released on 3 December 2008. Many of its major features were backported to Python 2.6.x and 2.7.x version series. priyanka.sherkhane@ruparel.edu Installation of Python Installation • Downloading: 1. Click Python Download. 2. Click the Windows link (two lines below the Download Python 3.7.4 button). 3. Click on the Download Windows x86-64 executable installer link under the top-left Stable Releases. 1. Click the Save File button. 2. The file named python-3.7.4-amd64.exe should start downloading into your standard download folder. 4. Move this file to a more permanent location, so that you can install Python • • • • Installing: Double-click the icon labeling the file python-3.7.4-amd64.exe. Highlight the Install Now (or Upgrade Now) message, and then click it. Click the Yes button. priyanka.sherkhane@ruparel.edu Installation Installation of Python • By using Anaconda: • https://www.datacamp.com/community/tutorials/installing-anacondawindows priyanka.sherkhane@ruparel.edu Debugging in Python • What is Debugging? • Debugging means the complete control over the program execution. • Developers use debugging to overcome program from any bad issues. So Debugging in Python debugging is a healthier process for the program and keeps the diseases bugs far away. • • • • • • programming errors are called bugs and the process of tracking them down is called debugging. Three kinds of errors can occur in a program: syntax errors, runtime errors, and Semantic errors. priyanka.sherkhane@ruparel.edu Syntax Error • Syntax refers to the structure of a program and the rules about that structure • Python can only execute a program if the syntax is correct; otherwise, the Debugging in Python interpreter displays an error message. • For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error. • If there is a single syntax error anywhere in your program, Python will display an error message and quit, and you will not be able to run your program. priyanka.sherkhane@ruparel.edu Debugging in Python Runtime Error • 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. • a problem that went undetected when the program was parsed, but is only revealed when the code is executed. 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 • • • • • priyanka.sherkhane@ruparel.edu Semantic errors • 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. Debugging in Python • It will do something else. Specifically, it will do what you told it to do. • For e.g. – Forgetting to divide by 100 when printing a percentage amount. priyanka.sherkhane@ruparel.edu Experimental debugging • Debugging is one of the most intellectually rich, challenging, and interesting parts of programming. • Once you have an idea about what is going wrong, you modify your Debugging in Python program and try again. • If your hypothesis was correct, then you can predict the result of the modification, and you take a step closer to a working program. • If your hypothesis was wrong, you have to come up with a new one. • 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. priyanka.sherkhane@ruparel.edu Formal and natural languages • 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. priyanka.sherkhane@ruparel.edu The Difference Between Brackets, Braces, and Parentheses () Parentheses = Parentheses are used for two purposes: (1) to control Brackets the order of operations in an expression, and (2) to supply parameters to a constructor or method. [] Brackets = Brackets are used to index into an array. {} Braces (Some people call these curly brackets or curly braces, but we’ll stick to just braces.) = Braces are used to group statements and declarations. The contents of a class or interface are enclosed in braces. Method bodies and constructor bodies are enclosed in braces. Braces are used to group the statements in an if statement, a loop, or other control structures. priyanka.sherkhane@ruparel.edu Variables and expressions Variables and expressions • • • • • • • • • • • • • • Values and types: A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 2, and “Hello” etc These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, If you are not sure what type a value has, the interpreter can tell you. >>> type('Hello, World!') <type 'str'> >>> type(17) <type 'int’> When you type a large integer, you might be tempted to use commas between groups of three digits, as in 1,000,000. >>> 1,000,000 (1, 0, 0) Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma separated sequence of integers. This is the first example we have seen of a semantic error. priyanka.sherkhane@ruparel.edu • Variables: • One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. >>> n = 17 >>> pi = 3.1415926535897932 Variables and Expressions • • • • • • • • • • • Variables name and keywords: A Programmer should always choose a meaningful name for their variable. Rules for Variable Names: A variable can contain both letters and numbers, but they cannot start with a number. So, variable1 is valid while 1variable is a invalid name. You may use uppercase letters for variable names but it is always perfectly fine to begin variable names with a lowercase letter. If your Variable name is long, then you can use underscore character (_) in the name. For example, top_five_members, var_1 etc. all are valid example. You can’t use special characters like !, @, #, $, % etc. in variable name. Python keywords cannot be used as variable name. priyanka.sherkhane@ruparel.edu Variables and Expressions • • • • • • • If you give a variable an illegal name, you get a syntax error: >>> 76trombones = 'big parade' SyntaxError: invalid syntax >>> more@ = 1000000 SyntaxError: invalid syntax >>> class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax • • It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names. Python also has some reserved words. These words hold some special meaning. Sometimes it may be a command, or a parameter etc. We cannot use keywords as variable names. • True False class def return if elif else try except raise finally for in is not from import global lambda nonlocal pass while break continue and with as yield del or assert None priyanka.sherkhane@ruparel.edu Operators and operands • • • Operators • • • • • • • • • • • Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands. The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and exponentiation. Operators are the constructs which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Operator Python language supports the following types of operators. Arithmetic Operators Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators priyanka.sherkhane@ruparel.edu Python Arithmetic Operators Operator Description + Addition Adds values on either side of the operator. a + b = 30 Subtraction Subtracts right hand operand from left hand operand. a – b = -10 * Multiplies values on either side of the Multiplicatio operator n Operators Example a * b = 200 / Division Divides left hand operand by right hand b / a = 2 operand % Modulus Divides left hand operand by right hand b % a = 0 operand and returns remainder ** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20 // 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) − priyanka.sherkhane@ruparel.edu Python Comparison Operators Operators Operato r Description Example == If the values of two operands are equal, then the condition becomes true. (a == b) is not true. != If values of two operands are not equal, then condition becomes true. (a != b) is true. <> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to != operator. > If the value of left operand is greater (a > b) is not true. than the value of right operand, then condition becomes true. < If the value of left operand is less (a < b) is true. than the value of right operand, then condition becomes true. >= If the value of left operand is greater (a >= b) is not true. than or equal to the value of right operand, then condition becomes true. <= If the value of left operand is less (a <= b) is true. than or equal to the value of right priyanka.sherkhane@ruparel.edu operand, then condition becomes Python Logical Operators Opera tor Operators and Logic al AND Description If both the operands are true then condition becomes true. Example (a and b) is true. or If any of the two operands are Logic non-zero then condition al OR becomes true. (a or b) is true. not Logic al NOT Not(a and b) is false. Used to reverse the logical state of its operand. priyanka.sherkhane@ruparel.edu Python Bitwise Operators Operators Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100) | Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101) ^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001) ~ Binary Ones It is unary and has the effect of Compleme 'flipping' bits. nt << Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number. a << 2 = 240 (means 1111 0000) >> Binary The left operands value is moved Right Shift right by the number of bits specified a >> 2 = 15 (means 0000 1111) by the right operand. priyanka.sherkhane@ruparel.edu Interactive mode and script mode Interactive and script mode • • • • • • • • • • One of the benefits of working with an interpreted language is that you can test bits of code in interactive mode before you put them in a script. But there are differences between interactive mode and script mode that can be confusing For example, if you are using Python as a calculator, you might type >>> miles = 26.2 >>> miles * 1.61 42.182 The first line assigns a value to miles, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. So we learn that a marathon is about 42 kilometers. But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn’t display the value unless you tell it to: miles = 26.2 print miles * 1.61 priyanka.sherkhane@ruparel.edu Interactive mode and script mode Interactive and script mode • • • • • • • • • • • • • • A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute. For e.g. print 1 x=2 print x produces the output 1 2 Exercise 2.1. Type the following statements in the Python interpreter to see what they do: 5 x=5 x+1 Now put the same statements into a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again. priyanka.sherkhane@ruparel.edu Order of operations • Order ofoperations • • • • • • • • When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules: Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result. • Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27. • Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5. • Operators with the same precedence are evaluated from left to right (except exponentiation). priyanka.sherkhane@ruparel.edu Comments in Python • Order of operations • • • • • • As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why. For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol: For e.g. # compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60 Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why. priyanka.sherkhane@ruparel.edu Conditional statements Conditional Statements • Everything you have seen so far has consisted of sequential execution, in which statements are always performed one after the next, in exactly the order specified. • Frequently, a program needs to skip over some statements, execute a series of statements repetitively, or choose between alternate sets of statements to execute. • In a Python program, the if statement is how you perform this sort of decision-making. • It allows for conditional execution of a statement or group of statements based on the value of an expression. priyanka.sherkhane@ruparel.edu Conditional statements Conditional Statements • If statement: • if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. • Syntax: – if (condition): Statements to execute Condition is true – – – Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also. • python uses indentation to identify a block. priyanka.sherkhane@ruparel.edu Conditional Statements Conditional statements • If statement: priyanka.sherkhane@ruparel.edu Conditional Statements • If statement: • For e.g. Conditional statements i = 10 if (i > 15): print ("10 is less than 15") print ("I am Not in if") priyanka.sherkhane@ruparel.edu Conditional statements Conditional Statements • If – else statement: • The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. • But what if we want to do something else if the condition is false. • Here comes the else statement. • We can use the else statement with if statement to execute a block of code when the condition is false. • Syntax: – if (condition): Statements to execute Condition is true – else : Statements to execute Condition is true priyanka.sherkhane@ruparel.edu Conditional Statements Conditional statements • If – else statement: priyanka.sherkhane@ruparel.edu Conditional statements Conditional Statements • If – else statement: • For e.g. i = 20; if (i < 15): print ("i is smaller than 15") print ("i'm in if Block") else: print ("i is greater than 15") print ("i'm in else Block") print ("i'm not in if and not in else Block") priyanka.sherkhane@ruparel.edu Conditional statements Conditional Statements • Nested If - else statement: • A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement. • Syntax: – if (condition1): Statements to execute if (condition2) : Statements to execute else priyanka.sherkhane@ruparel.edu Conditional Statements Conditional statements • Nested if - else statement: priyanka.sherkhane@ruparel.edu Conditional statements Conditional Statements • Nested If - else statement: • For e.g. i = 10 if (i == 10): # First if statement if (i < 15): print ("i is smaller than 15") # Nested - if statement # Will only be executed if statement above # it is true if (i < 12): print ("i is smaller than 12 too") else: print ("i is greater than 15") priyanka.sherkhane@ruparel.edu Python Loop Python Loop • 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. • Python programming language provides following types of loops to handle looping requirements. • Python provides three ways for executing the loops. priyanka.sherkhane@ruparel.edu Python Loop Python Loop • While Loop: • In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. • And when the condition becomes false, the line immediately after the loop in program is executed. • Syntax : • while expression: statement(s) • All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. • Python uses indentation as its method of grouping statements. priyanka.sherkhane@ruparel.edu Python Loop Python Loop • While Loop: priyanka.sherkhane@ruparel.edu Python Loop Python Loop • • • • • • While Loop: For eg. count = 0 while (count < 3): count = count + 1 print("Hello Python") • count = 0 • while (count < 3): • count = count + 1 • print("Hello Python") • else: • print("In Else Block") • priyanka.sherkhane@ruparel.edu Python Loop Python Loop • • • • • For Loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages • Syntax: • for iterator_var in sequence: statements(s) • For I in (1,10): priyanka.sherkhane@ruparel.edu Python Loop Python Loop • For Loop: priyanka.sherkhane@ruparel.edu Python Loop Python Loop • • • • • • • • • For Loop: For eg. n=4 for i in range(0, n): print(i) l = ["geeks", "for", "geeks"] for i in l: print(i) • list = ["geeks", "for", "geeks"] • for index in range(len(list)): • print list[index] • else: • print "Inside Else Block" priyanka.sherkhane@ruparel.edu Python Loop Python Loop • Nested Loops: • Python programming language allows to use one loop inside another loop. • Syntax: • for iterator_var in sequence: • for iterator_var in sequence: • statements(s) • statements(s) • The syntax for a nested while loop statement in Python programming language is as follows: • while expression: while expression: • statement(s) • statement(s) • • A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa. priyanka.sherkhane@ruparel.edu Python Loop Python Loop • Nested Loops: • For eg. • for i in range(1, 5): • for j in range(i): • print(i, end=' ') • print() priyanka.sherkhane@ruparel.edu Loop Control Statements Python Loop • Loop control statements change execution from its normal sequence. • When execution leaves a scope, all automatic objects that were created in that scope are destroyed. • Python supports the following control statements. • Continue Statement: It returns the control to the beginning of the loop. The continue statement in Python returns the control to the beginning of the while loop. • The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. • The continue statement can be used in both while and for loops. • Syntax: • continue • For eg. • for letter in ‘Hello Python': if letter == ‘o' : • continue • print 'Current Letter :', letter • priyanka.sherkhane@ruparel.edu Loop Control Statements Python Loop • Break Statement: It brings control out of the loop. It terminates the current loop and resumes execution at the next statement. • The break statement can be used in both while and for loops. • Syntax: • break • For eg. • for letter in ‘Hello Python': • if letter == ‘o‘ : • break • print 'Current Letter :', letter priyanka.sherkhane@ruparel.edu Loop Control Statements Python Loop • Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control statement, function and classes. • The pass statement is a null operation; nothing happens when it executes. • The pass is also useful in places where your code will eventually go, but has not been written yet. • Syntax: • pass • For eg. • for letter in ’Hello Python': • pass • print 'Last Letter :', letter priyanka.sherkhane@ruparel.edu