Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

# Chapter 1 Introduction to Python ## 1.1 Features of Python - Features of Python - How to Run Python - Identifiers - Reserved Keywords - Variables - Comments in Python - Indentation in Python - Multi-Line Statements - Multiple Statement Group (Suite) - Quotes in Python - Input, Output and Import F...

# Chapter 1 Introduction to Python ## 1.1 Features of Python - Features of Python - How to Run Python - Identifiers - Reserved Keywords - Variables - Comments in Python - Indentation in Python - Multi-Line Statements - Multiple Statement Group (Suite) - Quotes in Python - Input, Output and Import Functions - Displaying the Output - Reading the Input - Import function - Operators - Arithmetic Operators - Relational Operators - Assignment Operators - Logical Operators - Bitwise Operators - Membership Operators - Identity Operators - Conclusion - Review Questions Python was developed by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in Netherlands during 1985-1990. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, Unix shell and other scripting languages. Rossum was inspired by Monty Python's Flying Circus, a BBC Comedy series and he wanted the name of his new language to be short, unique and mysterious. Hence he named it Python. It is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Python source code is available under the GNU General Public License (GPL) and it is now maintained by a core development team at the National Research Institute. ## 1.1 Features of Python - **Simple and easy-to-learn** - Python is a simple language with few keywords, simple structure and its syntax is also clearly defined. This makes Python a beginner's language. - **Interpreted and Interactive** - Python is processed at runtime by the interpreter. We need not compile the program before executing it. The Python prompt interact with the interpreter to interpret the programs that you have written. Python has an option namely interactive mode which allows interactive testing and debugging of code. - **Object-Oriented** - Python supports Object Oriented Programming (OOP) concepts that encapsulate code within objects. All concepts in OOPs like data hiding, operator overloading, inheritance etc. can be well written in Python. It supports functional as well as structured programming. - **Portable** - Python can run on a wide variety of hardware and software platforms and has the same interface on all platforms. All variants of Windows, Unix, Linux and Macintosh are to name a few. - **Scalable** - Python provides a better structure and support for large programs than shell scripting. It can be used as a scripting language or can be compiled to bytecode (intermediate code that is platform independent) for building large applications. - **Extendable** - You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. - **Dynamic** - Python provides very high-level dynamic data types and supports dynamic type checking. It also supports automatic garbage collection. - **GUI Programming and Databases** - Python supports GUI applications that can be created and ported to many libraries and windows systems, such as Windows Microsoft Foundation Classes (MFC), Macintosh, and the X Window system of Unix. Python also provides interfaces to all major commercial databases. - **Broad Standard Library** - Python's library is portable and cross platform compatible on UNIX, Linux, Windows and Macintosh. This helps in the support and development of a wide range of applications from simple text processing to browsers and complex games. ## 1.2 How to Run Python There are three different ways to start Python. - **Using Interactive Interpreter** You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. Get into the command line of Python. For Unix/Linux, you can get into interactive mode by typing $python or python%. For windows/Dos it is C:>python. Invoking the interpreter without passing a script file as a parameter brings up the following prompt ? - $ python - Python 2.7.10 (default, Sep 27 2015, 18:11:38) - [GCC 5.1.1 20150422 (Red Hat 5.1.1-1)] on linux2 - Type "help", "copyright", "credits" or "license" for more information. - >>> Type the following text at the Python prompt and press the Enter: - >>> print “Programming in Python!" The result will be as given below Programming in Python! - **Script from the Command Line** This method invokes the interpreter with a script parameter which begins the execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active. A Python script can be executed at command line by invoking the interpreter on your application, as follows. - For Unix/Linux it is $python script.py or python% script.py. For Windows/Dos it is C:>python script.py Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a first.py file. print "Programming in Python!" Now, try to run this program as follows. $ python first.py This produces the following result: Programming in Python! - **Integrated Development Environment** You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python. IDLE is the Integrated Development Environment (IDE) for UNIX and PythonWin is the first Windows interface for Python. All the programs in this book are tested in Python 3.4.3 for Windows. ## 1.3 Identifiers A Python identifier is a name used to identify a variable, function, class, module or any other object. Python is case sensitive and hence uppercase and lowercase letters are considered distinct. The following are the rules for naming an identifier in Python. - Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example Total and total is different. - Reserved keywords (explained in Section 1.4) cannot be used as an identifier. - Identifiers cannot begin with a digit. For example 2more, 3times etc are invalid identifiers. - Special symbols like @, !, #, $, % etc. cannot be used in an identifier. For example sum@, #total are invalid identifiers. - Identifier can be of any length. Some examples of valid identifiers are total, max_mark, count2, Student etc. Here are some naming conventions for Python identifiers. - Class names start with an uppercase letter. All other identifiers start with a lowercase letter. Eg: Person - Starting an identifier with a single leading underscore indicates that the identifier is private. Eg: _sum - Starting an identifier with two leading underscores indicates a strongly private identifier. Eg: _sum - If the identifier also ends with two trailing underscores, the identifier is a language-defined special name, foo_ ## 1.4 Reserved Keywords These are keywords reserved by the programming language and prevent the user or the programmer from using it as an identifier in a program. There are 33 keywords in Python 3.3. This number may vary with different versions. To retrieve the keywords in Python the following code can be given at the prompt. All keywords except True, False and None are in lowercase. The following list in Table 1.1 shows the Python keywords. ```python >>> import keyword >>> print (keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except’, 'finally', 'for' 'from', `global', `if', `import', 'in', 'is', `lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return' 'try', 'while', 'with', 'yield'] ``` | Keyword | Description | |---|---| | False | False | | None| None | | True | True | | and | Logical And | | as | Alias | | assert | Assertion | | break | Exit a Loop | | class | Define a Class | | continue | Continue to next Iteration | | def | Define a Function | | del | Delete a Variable | | elif | Else if | | else | Else | | except | Handling Exception | | finally | Finally | | for | Looping through a range of Numbers | | from | Importing from a module | | global | Accessing global variables from inside a function | | if | Decision making | | import | Import a module | | in | Check if a value exists in a list | | is | Check if a value is equivalent to | | lambda | Define an anonymous function | | nonlocal | Create a variable in the outer function | | not | Logically negates a statement | | or | Logical Or | | pass | A null statement | | raise | Raise an exception | | return | Return value to the caller | | try | Handling exception | | while | Looping | | with | Controlling a resource | | yield | Pause a generator | ## 1.5 Variables Variables are reserved memory locations to store values. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables. Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. ```python # Example Program a = 100 # An integer assignment b = 1000.0 # A floating point name = "John" # A string print a print b print name ``` Here, 100, 1000.0 and "John" are the values assigned to a, b, and name variables, respectively. This produces the following result ``` 100 1000.0 John ``` Python allows you to assign a single value to several variables simultaneously. For example ```python a = b = c = 1 ``` Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example ```python a, b, c = 1, 2, "Tom" ``` Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "Tom" is assigned to the variable c. ## 1.6 Comments In Python Comments are very important while writing a program. It describes what the source code has done. Comments are for programmers for better understanding of a program. In Python, we use the hash (#) symbol to start writing a comment. A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment. It extends up to the newline character. Python interpreter ignores comment. **Example Program** ```python >>>#This is demo of comment >>>#Display Hello >>>print("Hello") ``` This produces the following result: Hello For multiline comments one way is to use (#) symbol at the beginning of each line. The following example shows a multiline comment. Another way of doing this is to use triple quotes, either ''' or """. **Example 1** ```python """" >>>#This is a very long sentence >>>#and it ends after >>>#Three lines ``` **Example 2** ```python >>>"""This is a very long sentence >>>and it ends after >>>Three lines""" ``` Both Example 1 and Example 2 given above produces the same result. ## 1.7 Indentation In Python Most of the programming languages like C, C++ and Java use braces { } to define a block of code. Python uses indentation. A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. The amount of indentation can be decided by the programmer, but it must be consistent throughout the block. Generally four whitespaces are used for indentation and is preferred over tabspace. For example ```python if True: print "Correct" else: print "Wrong" ``` But the following block generates error as indentation is not properly followed. ```python if True: print "Answer" print "Correct" else: print "Answer" print "Wrong" ``` ## 1.8 Multi-Line Statements Instructions that a Python interpreter can execute are called statements. For example, a=1 is an assignment statement. if statement, for statement, while statement etc. are other kinds of statements which will be discussed in coming Chapters. In Python, end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character(\). For example: ```python grand_total = first_item + \ second_item + \ third item ``` Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example ```python months = [`January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] ``` We could also put multiple statements in a single line using semicolons, as follows ```python a = 1; b = 2; c = 3 ``` ## 1.9 Multiple Statement Group (Suite) A group of individual statements, which make a single code block is called a suite in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite. Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example ```python if expression : suite elif expression : suite else : suite ``` ## 1.10 Quotes in Python Python accepts single ('), double (") and triple ('' or "'") quotes to denote string literals. The same type of quote should be used to start and end the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal. ```python 'single word' word = "This is a short sentence." paragraph = """This is a long paragraph. It consists of several lines and sentences.""" ``` ## 1.11 Input, Output and Import Functions ### 1.11.1 Displaying the Output The function used to print output on a screen is the print statement where you can pass zero or more expressions separated by commas. The print function converts the expressions you pass into a string and writes the result to standard output. **Example 1** ```python >>>print("Learning Python is fun and enjoy it.") ``` This will produce the following output on the screen ``` Learning Python is fun and enjoy it. ``` **Example 2** ```python >>>a=2 >>>print("The value of a is",a) ``` This will produce the following output on the screen ``` The value of a is 2 ``` By default a space is added after the text and before the value of variable a. The syntax of print function is given below. ```python print *objects, sep='', end='\n', file=sys.stdout, flush=False ``` Here, objects are the values to be printed. Sep is the separator used between the values. Space character is the default separator. end is printed after printing all the values. The default value for end is the new line. file is the object where the values are printed and its default value is sys.stdout (screen). Flush determines whether the output stream needs to be flushed for any waiting output. A True value forcibly flushes the stream. The following shows an example for the above syntax. **Example** ```python >>>print(1,2,3,4) >>>print (1,2,3,4, sеp='+') >>> print (1,2,3,4, sep='+',end='%') ``` The Output will be as follows ``` 1 2 3 4 1+2+3+4 1+2+3+4% ``` The Output can also be formatted to make it attractive according to the wish of a user. This will be discussed in the subsequent Chapters. ### 1.11.2 Reading the Input Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are raw_input and input. The raw_input function is not supported by Python 3. **raw_input function** The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline). This prompts you to enter any string and it would display same string on the screen. **Example** ```python str = raw_input("Enter your name: "); print("Your name is : ", str) ``` **Output** - Enter your name: Collin Mark - Your name is : Collin Mark **input function** The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you. **Example 1** ```python n = input("Enter a number "); print("The number is : ", n) ``` **Output** - Enter a number: 5 - The number is: 5 **Example 2** ```python n = input("Enter an expression "); print("The result is: ", n) ``` **Output** - Enter an expression: 5*2 - The result is: 10 ### 1.11.3 Import function When the program grows bigger or when there are segments of code that is frequently used, it can be stored in different modules. A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension.py. Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this. For example, we can import the math module by typing in import math. ```python >>> import math >>> math.pi 3.141592653589793 ``` ## 1.12 Operators Operators are the constructs which can manipulate the value of operands. Consider the expression a = b + c. Here a, b and c are called the operands and +, = are called the operators. There are different types of operators. The following are the types of operators supported by Python. - Arithmetic Operators - Comparison (Relational) Operators - Assignment Operators - Logical Operators - Bitwise Operators - Membership Operators - Identity Operators Let us have a look on all operators one by one. ### 1.12.1 Arithmetic Operators Arithmetic Operators are used for performing basic arithmetic operations. The following are the arithmetic operators supported by Python. Table 1.2 shows the Arithmetic Operators in Python. | Operator | Description | |---|---| | + | Addition | | - | Subtraction | | * | Multiplication | | / | Division | | % | Modulus | | ** | Exponent | | // | Floor Division | **Example Program** ```python a, b, c = 10, 5, 2 print("Sum=", (a+b)) print("Difference=”,(a-b)) print("Product=", (a*b)) print("Quotient=", (a/b)) print("Remainder=", (b%c)) print("Exponent=", (b**2)) print("Floor Division=", (b//c)) ``` **Output** - Sum= 15 - Difference= 5 - Product= 50 - Quotient= 2 - Remainder= 1 - Exponent= 25 - Floor Division= 2 ### 1.12.2 Comparison Operators These operators compare the values on either sides of them and decide the relation among them. They are also called relational operators. Python supports the following relational operators. Table 1.3 shows the Comparison or Relational Operators in Python. | Operator | Description | |---|---| | == | If the values of two operands are equal, then the condition becomes true. | | != | If values of two operands are not equal, then condition becomes true. | | > | If the value of left operand is greater than the value of right operand, then condition becomes true. | | < | If the value of left operand is less than the value of right operand, then condition becomes true. | | >= | If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. | | <= | If the value of left operand is less than or equal to the value of right operand, then condition becomes true. | **Example Program** ```python a,b=10,5 print("a==b is", (a==b)) print("a!=b is", (a!=b)) print("a>b is", (a>b)) print("a<b is", (a<b)) print("a>=b is", (a>=b)) print("a<=b is", (a<=b)) ``` **Output** - a==b is False - alb is True - a>b is True - a<b is False - a>=b is True - a<=b is False ### 1.12.3 Assignment Operators Python provides various assignment operators. Various shorthand operators for addition, subtraction, multiplication, division, modulus, exponent and floor division are also supported by Python. Table 1.4 provides the various Assignment Operators. | Operator | Description | |---|---| | = | Assigns values from right side operands to left side operand. | | += | It adds right operand to the left operand and assign the result to left operand. | | -= | It subtracts right operand from the left operand and assign the result to left operand. | | *= | It multiplies right operand with the left operand and assign the result to left operand. | | /= | It divides left operand with the right operand and assign the result to left operand. | | %= | It takes modulus using two operands and assign the result to left operand. | | **= | Performs exponential (power) calculation on operators and assign value to the left operand. | | //= | It performs floor division on operators and assign value to the left operand. | The assignment operator = is used to assign values or values of expressions to a variable. Example: a = b+ c. For example c+=a is equivalent to c=c+a. Similarly c-=a is equivalent to c=c-a, c*=a is equivalent to c=c*a, c/=a is equivalent to c=c/a, c%=a is equivalent to c=c%a, c**=a is equivalent to c=c**a and c//=a is equivalent to c=c//a. **Example Program** ```python a,b=10,5 a+=b print(a) a,b=10,5 a-=b print(a) a,b=10,5 a*=b print(a) a,b=10,5 a/=b print (a) b,c=5,2 b=c print (b) b,c=5,2 b**=c print (b) b,c=5,2 b//=c print (b) ``` **Output** - 15 - 5 - 50 - 2 - 1 - 25 - 2 ### 1.12.4 Bitwise Operators Bitwise operator works on bits and performs bit by bit operation. The following are the bitwise operators supported by Python. Table 1.5 gives a description of Bitwise Operators in Python. | Operator | Operation | Description | |---|---|---| | & | Binary AND | Operator copies a bit to the result if it exists in both operands. | | | | It copies a bit if it exists in either operand. | | ^ | Binary XOR | It copies the bit if it is set in one operand but not both. | | ~ | Binary Ones Complement | It is unary and has the effect of 'flipping' bits. | | << | Binary Left Shift | The left operand's value is moved left by the number of bits specified by the right operand. | | >> | Binary Right Shift | The left operand's value is moved right by the number of bits specified by the right operand. | Let a = 60 (0011 1100 in binary) and b = 2 (0000 0010 in binary) **Example Program** ```python a,b=60,2 print(a&b) print(a/b) print(a^b) print(-a) print (a>>b) print (a<<b) ``` **Output** - 0 - 62 - 62 - -61 - 15 - 240 Consider the first print statement a&b. Here a=0011 1100 b=0000 0010 When a bitwise and is performed, the result is 0000 0000. This is 0 in decimal. Similar is the case for all the print statements given above. ### 1.12.5 Logical Operators Table 1.6 shows the various Logical Operators supported by Python language. | Operator | Operation | Description | |---|---|---| | and | Logical AND | If both the operands are true then condition becomes true. | | or | Logical OR | If any of the operands are true then condition becomes true. | | not | Logical NOT | Used to reverse the logical state of its operand.| **Example Program** ```python a,b,c,d=10,5,2,1 print((a>b)and(c>d)) print((a>b)or(d>c)) print (not (a>b)) ``` **Output** - True - True - False ### 1.12.6 Membership Operators Python's membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below in Table 1.7. Strings, lists and tuples will be covered in the forthcoming Chapter. | Operator | Description | |---|---| | in | Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. | | not in | Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. | **Example Program** ```python s='abcde' print('a' in s) print('f' in s) print('f'not in s) ``` **Output** - True - False - True ### 1.12.7 Identity Operators Identity operators compare the memory locations of two objects. There are two Identity operators as shown in below Table 1.8. | Operator | Description | |---|---| | is | Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. | | is not | Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. | **Example Program** ```python a,b,c=10,10,5 print(a is b) print(a is c) print(a is not b) ``` **Output** True False False ### 1.12.8 Operator Precedence The following Table 1.9 lists all operators from highest precedence to lowest. Operator associativity determines the order of evaluation, when they are of the same precedence, and are not grouped by paranthesis. An operator may be left-associative or right-associative. In left-associative, the operator falling on the left side will be evaluated first, while in right-associative, operator falling on the right will be evaluated first. In Python, '=' and '**' are right-associative while all other operators are left-associative. | Operator | Description | |---|---| | `**` | Exponentiation (raise to the power) | | `~`, `+`, `-` | Complement, unary plus and minus | | `*`, `/`, `%`, `//` | Multiply, divide, modulo and floor division | | `+`, `-` | Addition and subtraction | | `>>, <<` | Right and left bitwise shift | | `&` | Bitwise 'AND' | | `^`, `|` | Bitwise exclusive 'OR' and regular 'OR' | | `<=`, `<>`, `>=` | Comparison operators | | `<>`, `==`, `!=` | Equality operators | | `=`, `%=`, `/=`, `//=`, `-=`, `+=`, `*=`, `**=` | Assignment operators | | `is`, `is not` | Identity operators | | `in`, `not in` | Membership operators | | `not`, `or`, `and` | Logical operators | ## 1.13 Conclusion This Chapter gives an introduction to Python, its features, programming constructs like identifiers, reserved keywords, variables and various operators with illustrated examples. This Chapter also covers the purpose of indentation, the usage of comments, multi-lie statements, multiple statements and quotes in Python, each one with illustrated examples. The basic Input/Output and import functions covered in this Chapter helps to handle the input, output and import operations in Python. Moreover how to execute Python is explained in this Chapter. ## 1.14 Review Questions 1. List some of the features of Python. 2. Is Python a case sensitive language? 3. How can you run Python? 4. Give the rules for naming an identifier in Python. 5. How can you give comments in Python? 6. What are multi-line statements? 7. What do you mean by suite in Python? 8. Briefly explain the Input and Output functions used in Python. 9. What is the purpose of import function? 10. What is the purpose of // operator? 11. What is the purpose of ** operator? 12. What is the purpose of is operator? 13. What is the purpose of not in operator? 14. Briefly explain the various types of operators in Python. 15. List out the operator precedence in Python.

Use Quizgecko on...
Browser
Browser