Computer Programming 2 Lecture Notes PDF
Document Details
Uploaded by ExquisiteDenouement2566
University of Antique
Fema Rose B. Ecraela
Tags
Related
- TK2053 Programming Paradigm - Python Interpreter PDF
- Python Programming Fundamentals PDF
- Python Programming Quiz Questions PDF
- SDU CSS 115 Programming Fundamentals 1 (Python) Fall 2024 Practice 4 PDF
- CSS 115 - Programming Fundamentals 1 (Python) Fall 2024 Lecture 5 PDF
- BSc (Hons) Electronics Ist Sem - Programming Fundamentals using Python PDF
Summary
This document is lecture notes for a computer programming 2 course. It introduces Python programming, including its history, data types, and variables. The notes cover a range of fundamental programming concepts.
Full Transcript
UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 MODULE IN CPROG 2: COMPUTER PROGRAMMING 2 Effective: 2nd Semester, 2020-2021 COMPUTER PROGRAMMING 2 Review Programming Fundamentals...
UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 MODULE IN CPROG 2: COMPUTER PROGRAMMING 2 Effective: 2nd Semester, 2020-2021 COMPUTER PROGRAMMING 2 Review Programming Fundamentals Fema Rose Ecraela Instructor E-mail: [email protected] Prepared by: Fema Rose B. Ecraela P a g e 1 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 CHAPTER GOALS At the end of this topic/chapter student should be able to: ✓ Learn the basics of Python Programming ✓ Learn Python data types ✓ Learn conditional Statements that Python has like any other programming languages Lesson 1: The Python Programming Language A brief history of python Guido Van Rossum published the first version of Python code (version 0.9.0) at alt.sources in February 1991. The creation of python was heavily influenced by the development of the programming language ABC. Since then it as seen explosive growth to become one of the most common programming languages in the world. What about the name python? Guido van Rossum, the creator of Python wrote “Over six years ago, in December 1989, I was looking for a ‘hobby’ programming project that would keep me occupied during the week around Christmas. My office... would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python’s Flying Circus).” Learning to program is a bit like learning to play piano, although quite a bit easier since we won’t have to program while keeping time according to a time signature. Programming is a creative process so we’ll be working on developing some creative skills. At the same time, there are certain patterns that can be used over and over again in this creative process. The goal of this text and the course you are taking is to get you familiar with these patterns and show you how they can be used in programs. After working through this text and studying and practicing you will be able to identify which of these patterns are needed to implement a program for a particular task and you will be able to apply these patterns to solve new and interesting problems. As human beings our intelligent behavior hinges on our ability to match patterns. We are pattern-matchers from the moment we are born. We watch and listen to our parents and siblings to learn how to react to situations. Babies watch us to learn to talk, walk, eat, and even to smile. All these behaviors are learned through pattern matching. Computer Science is no different. Many of the programs we create in Computer Science are based on just a few patterns that we learn early in our education as programmers. Once we’ve learned the patterns we become effective programmers by learning to apply the patterns to new situations. As babies we are wired to learn quickly with a little practice. As we grow older we can learn to use patterns that are more abstract. That is what Computer Prepared by: Fema Rose B. Ecraela P a g e 2 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Science is all about: the application of abstract patterns to solve new and interesting problem Python is the programming language this text uses to introduce computer programming. To run a Python program you need an interpreter. The Python interpreter is a program that reads a Python program and then executes the statements found in it as depicted in Fig. 1. While studying this text you will write many Python programs. Once your program is written and you are ready to try it you will tell the Python interpreter to execute your Python program so you can see what it does. For this process to work you must first have Python installed on your computer. Python is free and available for download from the internet. The next section of this chapter will take you through downloading and installing Python. Within the last few years there were some changes to the Python programming language between Python 2 and Python 3. The text will describe differences between the two versions of Python as they come up. In terms of learning to program, the differences between the two versions of Python are pretty minor Figure 1: The Python interpreter To write Python programs you need an editor to type in the program. It is convenient to have an editor that is designed for writing Python programs. An editor that is specifically designed for writing programs is called an IDE or Integrated Development Environment. An IDE is more than just an editor. It provides highlighting and indentation that can help as you write a program. It also provides a way to run your program straight from the editor. Since you will typically run your program many times as you write it, having a way to run it quickly is handy. This text uses the Wing IDE 101 in many of its examples. This IDE is simple to install and is free for educational use. Wing IDE 101 is available for Mac OS X, Microsoft Windows, and Linux. When learning to program and even as a seasoned professional, it can be advantageous to run your program using a tool called a debugger. A debugger allows you to run your program, stop it at any point, and inspect the state of the program to help you better understand what is happening as your program executes. The Wing IDE includes an integrated debugger for that purpose. There are certainly other IDEs that might be used and nothing presented in this text precludes you from using something else. Some examples of IDEs for Python development include Netbeans, Eclipse, Eric, and IDLE. Eric’s debugger is really quite nice and could serve as an alternative to Wing should Wing IDE 101 not be an option for some reason. Prepared by: Fema Rose B. Ecraela P a g e 3 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Salient Features of Python Language 1. Python is free and open source for which source code is available. 2. Unlike C and C++ which are compiled languages, Python is an interpreted language. 3. Python uses indentation for specifying the scope which signifies the grouping of statements. 4. Unlike the programming languages such as C, C++ and Java, Python is a dynamically typed language which means you do not have to declare the type of the variable before using it. The variable’s type is resolved dynamically at runtime based on the value assigned to it which makes Python a type infer language. 5. Python is cross-platform which implies it is portable on different operating systems such as windows, linux, mac etc. 6. Python variables are case-sensitive. 7. In Python, every variable is an object and every Python object is internally implemented as a C structure. Hence in essence, Python variable is a pointer to a C structure. 8. In Python, Strings are immutable which means once created a string cannot be modified without re-creating it. 9. Python interprets a number without any prefix to be a decimal number. Different strings can be prepended to a number in order to specify a base other than 10. 10. Using the variable in an expression without initializing it will generate error Lesson 2: Python Data Types and Variables Variable is a name used to refer to a base memory location. Every variable in Python has a specific data type based on the value assigned to it. Since everything evaluates to an object in Python, a data type maps to a class and a variable to an instance of a class. The feature which distinguishes Python variable from a variable in any other programming language is that, variable in Python has type but there is no size limitation. A variable can grow in size indefinitely limited only by the physical memory of the system. Python variables are case-sensitive. In the following program, ‘lang’ and ‘Lang’ are treated as two distinct variables. Prepared by: Fema Rose B. Ecraela P a g e 4 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 On execution of the above code snippet, the following output is generated: Primitive Data Types in Python Python3 supports 3 basic data types ✓ Numeric ✓ String ✓ Boolean Floating point numbers are stored with a precision of 16 decimal places. Excess digits, if any are stripped off as shown in the following program: On execution of the above code snippet, the following output is generated: Prepared by: Fema Rose B. Ecraela P a g e 5 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 From the output generated on execution of the above code segment it is observed that the variable f is truncated up to 16 decimal places. Unlike the programming languages such as C, C++ and Java, Python is a dynamically typed language which means you do not have to declare the type of the variable before using it. The variable’s type is resolved dynamically at runtime based on the value assigned to it which makes Python a type infer language. The side effect is that the same variable may attain different data types if a different value is assigned to it as demonstrated in the following code snippet: In statement (8) the variable ‘var’ is initialized with a value 10 which is later re-initialized in statement (10) with a string value. On execution of the above code snippet, the following output is generated: As is evident from the output generated on execution of the above code, the type of the variable var has been changed from int to str on re-initialization. Python does not automatically assign default values to variables. Using the variable in an expression without initializing it will generate NameError as demonstrated in the following code segment: Prepared by: Fema Rose B. Ecraela P a g e 6 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 On execution of the above code snippet, NameError is generated as shown below: This documentation was generated from the Python documentation available by typing help(int) in the Python shell. In this documentation the variables x, y, and z refer to integers. Integers and Real Numbers In most programming languages, including Python, there is a distinction between integers and real numbers. Integers, given the type name int in Python, are written as a sequence of digits, like 83 for instance. Real numbers, called float in Python, are written with a decimal point as in 83.0. This distinction affects how the numbers are stored in memory and what type of value you will get as a result of some operations. In Fig. 2 the type of the result is a float if either operand is a float unless noted otherwise in the table. Prepared by: Fema Rose B. Ecraela P a g e 7 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Figure 2: Numeric operations Dividing the integer 83 by 2 yields 41.5 if it is written 81/2. However, if it is written 83//2 then the result is 41. This goes back to long division as we first learned in elementary school. 83//2 is 41 with a remainder of 1. The result of floor division isn’t always an int. 83//2.0 yields 41.0 so be careful. While floor division returns an integer, it doesn’t necessarily return an int. We can insure a number is a float or an integer by writing float or int in front of the number. So, float(83)//2 also yields 41.0. Likewise, int(83.0)//2 yields 41. There are infinitely many real numbers but only a finite number of floats that can be represented by a computer. For instance, the number PI is approximately 3.14159. However, that number can’t be represented in some implementations of Python. Instead, that number is approximated as 3.1415899999999999 in at least one Python implementation. Writing 3.14159 in a Python program is valid, but it is still stored internally as the approximated value. This is not a limitation of Python. It is a limitation of computers in general. Computers can only approximate values when there are infinitely many possibilities because computers are finite machines. You can use what is called integer conversion to transform a floating-point number to its integer portion. In effect, integer conversion truncates the digits after the decimal point in a floating-point number to get just the whole number part. To do this you write int in front of the floating-point number you wish to convert. This does not convert the existing number. It creates a new number using only the integer portion of the floating point number. Prepared by: Fema Rose B. Ecraela P a g e 8 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Example 1: Assume that you work for the waste water treatment plant. Part of your job dictates that you report the gallons of water treated at the plant. However, your meter reports lbs of water treated. You have been told to to report the amount of treated waste water in gallons and ounces. There are 128 ounces in a gallon and 16 ounces in a pound. Here is a short program that performs the conversion. In Example 1 the lbs were first converted to ounces. Then the whole gallons were computed from the ounces by converting to an integer the result of dividing the ounces float by 128. On line 4 the remaining ounces were computed after taking out the number of ounces contained in the computed gallons. Several of the operations between ints and floats are given in Fig. 1.18. If you need to round a float to the nearest integer (instead of truncating the fractional portion) you can use the round function. Absolute value is taken using abs. There are other operations between floats and ints that are not discussed in this chapter. A complete list of all operations supported by integers and floats are given in Appendices and B. If you need to read some documentation about an operator you can use the appendices or you can search for Python documentation on the internet or you can start a Python shell and type help(float) or help(int). This help facility is built into the Python programming language. There is extensive documentation for every type within Python. Typing help(type) in the Python shell where type is any type within Python will provide you with all the operations that are available on that type of value. Strings A string type in Python is referred to as ‘str’. Like C, string in Python is a sequence of characters starting with index 0. A string can be enclosed within single, double or triple quotes. When you want to create a string spanning multiple lines use triple quotes as demonstrated in the following code snippet: Prepared by: Fema Rose B. Ecraela P a g e 9 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 On execution of the above code snippet, the following output is generated: Strings are another type of data in Python. A string is a sequence of characters. Prepared by: Fema Rose B. Ecraela P a g e 10 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Figure 3: String operations name = 'Sophus Lie' p r i n t("A famous Norwegian Mathematician is", name) This is a short program that initializes a variable called name to the string ‘Sophus Lie’. A string literal is an actual string value written in your program. String literals are delimited by either double or single quotes. Delimited means that they start and end with quotes. In the code above the string literal Sophus Lie is delimited by single quotes. The string A famous Norwegian Mathematician is is delimited by double quotes. If you use a1.14 Integer to String Conversion and Back Again 25 single quote at the beginning of a string literal, you must use a single quote at the end of the string literal. Delimiters must come in matching pairs. Strings are one type of sequence in Python. There are other kinds of sequences in Python as well, such as lists which we’ll look at in a couple of chapters. Python supports operations on sequences. For instance, you can get an individual item from a sequence. Writing, p r i n t(name) will print the first character of the string that name references. The 0 is called an index. Each subsequent character is assigned a subsequent position in the string. Notice the first position in the string is assigned 0 as its index. The second character is assigned index 1, and so on. Integer to String Conversion and Back Again It is possible in Python to convert an integer to a string. For instance, x = str(83) p r i n t(x) p r i n t(x) y = int(x) p r i n t(y) This program converts 83 to ‘83’ and back again. Integers and floats can be converted to a string by using the str conversion operator. Likewise, an integer or a float contained in a string can be converted to its numeric equivalent by using the int or float conversion operator. Conversion between numeric types and string types is frequently used in programs especially when producing output and getting input. Conversion of numeric values to strings should not be confused with ASCII conversion. Integers may represent ASCII codes for characters. If you want to convert an integer to its ASCII character equivalent you use the chr conversion operator. For instance, chr(83) is Prepared by: Fema Rose B. Ecraela P a g e 11 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 ‘S’. Likewise, if you want to convert a character to its ASCII code equivalent you use the ord conversion operator. So ord(‘S’) is equal to 83. You might have noticed in Fig. 3 there is an operator called int and another called float. Both of these operators are also numeric operators and appear in Fig. 1.18. This is called an overloaded operator because int and float are operators that work for both numeric and string operands. Python supports overloaded operators like this. This is a nice feature of the language since both versions of int and float do similar things. Using Escape Characters in Strings Every escape character used in a string has a specific action to perform. The following table depicts commonly used escape characters in a string: The following Python program demonstrates the use of escape characters in strings. In the first print statement when the escape character ‘\r’ is encountered, the cursor is moved to the beginning of the line before displaying the string “Python”. In the second print statement, on encountering three escape characters ‘\b’, the cursor is moved in the backward direction by three characters and the string “MCA Program” is displayed from the current cursor position. Finally, in the third print statement four blank spaces are inserted between the strings “Python” and “Programming”. On execution of the above code snippet, the following output is generated: Prepared by: Fema Rose B. Ecraela P a g e 12 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Raw String in Python Raw string is generated by appending the character ‘r’ to the string which signifies not to interpret any escape characters as demonstrated in the following code snippet: In the above program, all the strings are appended with the character ‘r’ to suppress the interpretation of escape characters. On execution of the above code snippet, the following output is generated: Boolean Data Type in Python Boolean data type is a sub type of int data type which can contain one of two values, True or False which are stored internally using numeric 1 and 0, respectively. The following Python program determines the size of boolean True and False using getsizeof() method of sys class. Prepared by: Fema Rose B. Ecraela P a g e 13 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 On execution of the above code snippet, the following output is generated: From the output generated on execution of the above program, it is evident that, the boolean True and False values are stored in Python employing integer values of 1 and 0, respectively. The following Python program uses conversion function, bool() for different arguments and determines the truth value of its arguments in each case. On execution of the above code snippet, the following output is generated: Prepared by: Fema Rose B. Ecraela P a g e 14 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Lesson 3: Checking the Type of the Variable Python supports a function type() for checking the type of the variable passed to it as demonstrated in the following code segment: The above program creates the four variables, i, f, s and c initialized with integer, floating point value, string value and a complex no, respectively. type() function is used for determining the type of the variable. On execution of the above code snippet, the following output is generated: Prepared by: Fema Rose B. Ecraela P a g e 15 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 As is evident from the output generated on execution of the program, i, f, s and c are instances of int, float, str and complex classes, respectively. Python does not automatically assign default values to variables. Using the variable in an expression without initializing it will generate NameError as demonstrated in the following code segment: On execution of the above code snippet, NameError is generated as shown below: Python Numbers Prior to Python 3, there were four in-built numeric types: ✓ int ✓ long ✓ float ✓ complex where int was automatically converted into long when overflow occurred. However, long type has been eliminated in Python 3, and there is absolutely no limit on the size of the integer. In the evaluation of arithmetic expression, the numbers are automatically upcast in the order int → float → complex Python interprets a number without any prefix to be a decimal number. Different strings can be prepended to a number in order to specify a base other than 10 as depicted in the following table: Prepared by: Fema Rose B. Ecraela P a g e 16 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Table 1: Python interprets a number without any prefix to be a decimal number The following Python program displays a number 11 using different base values. On execution of the above code snippet, the following output is generated: Conversion Between Python Data Types The conversion between data types in Python can be facilitated using one of the following techniques: ✓ Implicit Type Conversion by Python ✓ Explicit Type Conversion by Programmer Implicit Type Conversion (Widening of Conversion) Implicit type conversion is automatic and does not involve any user intervention. Python always converts smaller data type to a larger data type as a precautionary measure towards data loss. In the following Python program, int and float values are added and the result is stored in a variable ‘result’. Python implicitly converts int value to float value (upcasting) and stores the value in a variable ‘result’. Prepared by: Fema Rose B. Ecraela P a g e 17 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 On execution of the above code snippet, the following output is generated: As seen from the output generated on execution of the program, the variable result evaluates to a float type. Explicit Type Conversion Python supports different type conversion functions for converting between different data types as depicted in the following table: The following Python program demonstrates different type conversions employing explicit type casting. Prepared by: Fema Rose B. Ecraela P a g e 18 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 On execution of the above code snippet, the following output is generated: Lesson 4: Conditional Statements Python Conditional Statements: IF...Else, ELIF & Switch Case What are Conditional Statements in Python? 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. What is Python If Statement? Python if Statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is true. If the condition is false, then the optional else statement runs which contains some code for the else condition. When you want to justify one condition while the other condition is not true, then you use Python if else statement. Python if Statement Syntax: if expression Statement else Statement Prepared by: Fema Rose B. Ecraela P a g e 19 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Python if...else Flowchart Figure 4: Python if...else Flowchart Let’s see an example of Python if else Statement: Prepared by: Fema Rose B. Ecraela P a g e 20 | 33 UA –Main Campus-BSCS CPROG 2: COMPUTER PROGRAMMING 2 Code Line 5: We define two variables x, y = 2, 8 Code Line 7: The if Statement in Python checks for condition x