fund of prog.pdf
Document Details
Uploaded by WorthwhileScholarship8026
ZCAS University
Full Transcript
Introduction to Computer Programming Computer programming is the process of designing, writing, testing, and debugging computer programs. It is a complex and challenging activity, but it can also be very rewarding. A computer program is a set of instructions that tells a computer...
Introduction to Computer Programming Computer programming is the process of designing, writing, testing, and debugging computer programs. It is a complex and challenging activity, but it can also be very rewarding. A computer program is a set of instructions that tells a computer what to do. 1 These instructions are written in a programming language, which is a formal language that is used to communicate with computers. There are many different programming languages, each with its own strengths and weaknesses. The first step in computer programming is to identify the problem that you want to solve. Once you have identified the problem, you need to come up with an algorithm, which is a step-by-step solution to the problem. 2 The algorithm is then written in a programming language. Once the program is written, it needs to be tested to make sure that it works correctly. This involves running the program with different sets of input data and checking the output to make sure that it is correct. If the program does not work correctly, it needs to be debugged. Debugging is the process of finding and fixing errors in a program. 3 This can be a very time-consuming process, but it is essential to ensure that the program works correctly. Types of programming Languages There are many different types of programming languages, each with its own strengths and weaknesses. Some of the most common types of programming languages include: 4 Low-level languages: Low-level languages are designed to be close to the machine code that computers understand. This makes them very efficient, but they can also be difficult to learn and use. Examples of low-level languages include Assembly Language High-level languages: High-level languages are designed to be more abstract and closer to human languages. 5 This makes them easier to learn and use, but they can be less efficient than low-level languages. Examples of high-level languages include Python, Java, and JavaScript. 6 7 Procedural languages: Procedural languages are based on the concept of procedures, which are sequences of instructions that can be reused. This makes them well-suited for tasks that require a lot of repetition. Examples of procedural languages include C, Pascal, and BASIC. 8 Object-oriented languages: Object-oriented languages are based on the concept of objects, which are self-contained units of data and code. This makes them well-suited for tasks that require complex data structures and interactions. Examples of object-oriented languages include Java, C++, and Python. 9 Functional languages: Functional languages are based on the concept of functions, which are expressions that produce a value. This makes them well-suited for tasks that require mathematical calculations and logic. Examples of functional languages include Haskell, Lisp, and Scheme. Scripting languages: Scripting languages are designed to be interpreted rather than compiled. 10 This makes them well-suited for tasks that require dynamic code execution. Examples of scripting languages include JavaScript, Python, and Perl. Concept of Computer Programming Computer programming is the process of creating sets of instructions that enable a computer to perform specific tasks or solve problems. 11 These instructions are written in a programming language, which serves as a medium of communication between humans and computers. The primary goal of programming is to provide a series of logical steps and algorithms that a computer can understand and execute to achieve the desired outcome. The key concepts that underpin computer programming include: 12 Problem Solving: Programming is fundamentally about solving problems. Programmers analyze real-world issues, break them down into smaller, manageable tasks, and devise algorithms to solve each part. Algorithms: An algorithm is a step-by-step procedure or a well- defined set of rules used to solve a specific problem. 13 Programming involves designing, implementing, and optimizing algorithms to efficiently and accurately address various challenges. Programming Languages: Programming languages are formal languages with specific syntax and semantics. They allow programmers to communicate instructions to computers effectively. 14 Examples of programming languages include Python, Java, C++, JavaScript, and many others. Syntax and Semantics: Each programming language has its syntax and semantics. Syntax refers to the rules and structure that define how code must be written in the language. Semantics define the meaning behind the code and how the computer interprets and executes it. 15 Data and Variables: Data is fundamental in programming. Variables are used to store and manipulate data during program execution. Data can take various forms, such as numbers, text, images, and more. Control Flow: Programming often requires controlling the flow of execution based on certain conditions. This is achieved through 16 control structures like loops (for, while) and conditional statements (if-else). Functions and Modularization: Functions are reusable blocks of code that perform specific tasks. They help break down complex programs into smaller, manageable units, enhancing code organization and maintainability. 17 Debugging: Debugging is the process of identifying and fixing errors or bugs in the code. It involves carefully inspecting the code to find and correct issues that prevent the program from functioning correctly. Software Development Life Cycle: Programming is part of the broader software development life cycle, which includes phases like analysis, design, implementation, testing, and maintenance. 18 Computer programming is a creative and dynamic field that empowers individuals to create applications, software, websites, games, and more. It requires logical thinking, problem-solving skills, attention to detail, and continuous learning, as technology and programming languages continually evolve. 19 With programming skills, individuals can shape technology to meet specific needs, automate tasks, and contribute to various industries in meaningful ways. 20 The concepts related to algorithms Algorithms are fundamental to computer science and programming. They are step-by-step procedures or sets of rules used to solve problems or perform specific tasks. Understanding algorithmic concepts is crucial for designing efficient and effective solutions to various computational challenges. Here are some essential concepts related to algorithms: 21 Algorithm Analysis: Algorithm analysis is the process of evaluating the efficiency of an algorithm in terms of its time complexity and space complexity. Time complexity measures the amount of time an algorithm takes to complete based on the input size, while space complexity measures the amount of memory used by the algorithm. 22 Time Complexity: Time complexity refers to the amount of time an algorithm takes to run as a function of the input size. It helps in understanding how the algorithm's performance scales with larger inputs. Space Complexity: Space complexity refers to the amount of memory space an algorithm uses as a function of the input size. It helps in understanding how much memory the algorithm requires for its execution. 23 Sorting Algorithms: Sorting algorithms arrange elements in a specific order, such as ascending or descending. Common sorting algorithms include Bubble Sort, Insertion Sort, Merge Sort, Quick Sort, and more. The choice of sorting algorithm depends on the data size and expected performance. 24 Searching Algorithms: Searching algorithms locate a target element within a collection of data. Common searching algorithms include Linear Search, Binary Search (applicable to sorted data), and more. Recursion: Recursion is a programming technique where a function calls itself to solve a problem. It often simplifies the problem by breaking it down into smaller, more manageable sub problems. 25 Divide and Conquer: Divide and Conquer is a problem-solving paradigm where a problem is divided into smaller sub problems, which are then solved independently. The solutions to sub problems are then combined to solve the original problem. Dynamic Programming: Dynamic programming is an optimization technique used to solve problems by breaking them 26 down into overlapping sub problems and storing the results to avoid redundant computations. Greedy Algorithms: Greedy algorithms make locally optimal choices at each step in the hope of finding a global optimum. They often provide quick and simple solutions to certain problems but might not always yield the best overall solution. 27 Graph Algorithms: Graph algorithms deal with data structures composed of nodes (vertices) and edges. Optimization Problems: Optimization algorithms aim to find the best solution from a set of possible solutions. They are widely used in various fields like operations research, machine learning, and engineering. 28 Understanding these algorithmic concepts is essential for programmers and computer scientists as they enable the development of efficient and robust solutions to complex problems. By analyzing, designing, and implementing algorithms effectively, programmers can create software that performs optimally and meets the requirements of various applications and industries. 29 The good qualities of a computer program Correctness: The program must produce the correct output for all possible inputs. Efficiency: The program should run in a reasonable amount of time and use a reasonable amount of memory. Robustness: The program should be able to handle unexpected inputs and errors gracefully. 30 Usability: The program should be easy to use and understand. Maintainability: The program should be easy to modify and update. Portability: The program should be able to run on different platforms and with different configurations. Security: The program should be secure from unauthorized access and tampering. 31 Scalability: The program should be able to handle increasing amounts of data and traffic. Reliability: The program should be reliable and should not crash or hang frequently. 32 The relationship between computer programs and compilers or interpreters Computer programs are written in high-level languages that are easy for humans to understand. However, computers can only understand machine code, which is a series of binary instructions. Compilers and interpreters are programs that translate high-level language programs into machine code. 33 A compiler is a program that translates an entire high-level language program into machine code all at once. Once the program has been compiled, it can be run directly by the computer. This makes compiled programs faster than interpreted programs, because the compiler has already done the work of translating the program into machine code. 34 However, compiling a program can take a long time, so compilers are not suitable for programs that need to be run frequently. An interpreter is a program that translates a high-level language program one statement at a time. This means that the interpreter does not need to translate the entire program before it can be run. This makes interpreted programs slower than compiled programs, but it also makes them more flexible. 35 Interpreted programs can be run directly from the source code, so they are easier to debug and modify. The choice of whether to use a compiler or an interpreter depends on the specific needs of the program. If the program needs to be run quickly, then a compiler should be used. If the program needs to be easy to debug or modify, then an interpreter should be used. 36 37 Here is a table that summarizes the key differences between compilers and interpreters: Feature Compiler Interpreter Speed Faster Slower Flexibility Less flexible More flexible Debugging More difficult Easier Modifying More difficult Easier Use cases Programs that need to be run quickly Programs that need to be easy to debug or modify 38 Program Design and Development Process Problem definition: The first step is to define the problem that the program is intended to solve. This involves understanding the requirements of the program and the users who will be using it. Analysis: The next step is to analyze the problem and develop a solution. 39 This involves breaking the problem down into smaller sub problems and identifying the steps that need to be taken to solve each subproblem. Design: The design step involves creating a detailed plan for the program. This includes specifying the data structures and algorithms that will be used, as well as the user interface. 40 Coding: The coding step involves translating the design into a programming language. This is the step where the actual code for the program is written. Testing: The testing step involves testing the program to make sure that it works correctly. This involves testing the program with different inputs and checking for errors. 41 Deployment: The deployment step involves making the program available to users. This may involve installing the program on a computer or making it available online. Maintenance: The maintenance step involves fixing bugs and adding new features to the program. This is an ongoing process that is necessary to keep the program up-to-date and working properly. 42 The program design and development process is iterative, meaning that it is often necessary to go back and forth between the different steps. For example, the design step may need to be modified if the analysis step reveals that the problem is more complex than originally thought. 43 The program design and development process is a complex process, but it is essential for creating high-quality computer programs. By following the steps outlined above, you can create a program that is well-designed, efficient, and easy to use. 44 The parts of a program structure A program structure refers to the organization and layout of the code that makes up a computer program. It involves breaking the program into different parts or components, each serving a specific purpose and working together to achieve the program's objectives. 45 The key parts of a program structure include: Header: The header part of a program typically contains essential information about the program, such as the name of the program, author, date of creation, and possibly a brief description of the program's functionality. 46 Imports/Includes: In many programming languages, you need to import or include libraries, modules, or packages that provide additional functionality. This section lists all the external resources that the program requires to run. 47 Global variables are variables that are accessible throughout the entire program, from any part of the code. They hold data that may be needed across different functions or modules. Main Function: The main function is the starting point of the program's execution. 48 It contains the primary logic and is where the program's execution begins. In some languages like C, C++, and Java, the main function is the entry point of the program. 49 50 Functions/Methods: Functions or methods are blocks of code that perform specific tasks. They help in breaking down the program into smaller, manageable tasks, making the code more organized and modular. 51 Control Structures: Control structures (e.g., loops and conditional statements) determine the flow of execution in the program. They enable the program to make decisions, repeat actions, and handle different scenarios. 52 Data Structures: Data structures are used to organize and store data in a program. Examples include arrays, lists, dictionaries, and linked lists. Proper data structures are crucial for efficient data manipulation. 53 Error Handling: Error handling is the process of managing exceptions or errors that may occur during program execution. It involves catching and handling exceptions to prevent the program from crashing unexpectedly. 54 Input/Output (I/O): The I/O section deals with interactions between the program and the user or external sources. It allows the program to take input from the user or other input streams and produce output or display results. 55 Comments: Comments are non-executable lines of text used to provide explanations or documentation within the code. They help other developers (including yourself) understand the purpose and functionality of different parts of the program. 56 Constants: Constants are variables whose values cannot be changed once defined. They are often used to represent fixed values or settings within the program. Utilities/Helper Functions: These are additional functions or methods that provide utility or helper functionalities, such as 57 date/time manipulation, mathematical calculations, or string operations. Properly structuring a program improves readability, maintainability, and code reusability. It also enables collaboration among multiple developers working on the same project. 58 The specific parts of a program structure may vary depending on the programming language and the type of application being developed. However, these fundamental components can be found in most well-organized and modular programs. 59 Pseudocode What Is Pseudocode? Pseudocode is a way of representing code, such as algorithms, functions, and other processes, using a combination of natural language and programming language-like elements. It’s called “pseudo” code because it’s not actually executable. 60 Instead, it’s a way for humans to understand and plan out the logic in coding — to describe the steps of a program in a way that’s easy for humans to understand while still being detailed enough to be rapidly converted into a specific programming language. 61 Here’s a simple example of pseudocode, in which we’re working out the basic logic to greet a visitor by name when they navigate to our site or app: PROCESS GreetUser INPUT userName DISPLAY "Hello, " + userName + "!" 62 END As you can see, the above pseudocode isn’t written with syntax from any actual language or framework. Instead, it uses simple, universally understandable language and programming elements — like PROCESS, DISPLAY, and 63 + — to stand in as syntax, making it simple for anyone to follow. That’s one of the powers of writing pseudocode: By laying the code’s intentions out in a common syntax, you can jump all programming and skill-based language barriers. Benefits of Writing Pseudocode 64 One of the main benefits of pseudocode is that it allows developers to sketch out their code without getting bogged down in the syntax and structure of any one specific language. This makes it easier to catch mistakes in a program or function’s logic, all without having to write or debug any actual code. 65 What’s more, pseudocode can be easily adapted to different programming languages, making it a useful tool for developers who are familiar with multiple languages and need to translate their ideas between them. Imagine being able to explain your Node.js script to a Laravel developer! 66 This can be especially useful for teams working on a project together, as pseudocode can be used as a common language to communicate ideas and functions. Here are the main benefits pseudocode can bring to developers, both novice and experienced: 67 Improved efficiency: By writing out the steps of a process in pseudocode, developers can save time by planning out their code before diving into the details or syntax of a specific programming language. This can help coders avoid mistakes and reduce the need for debugging. 68 Easier to read: Since pseudocode is written to be simple enough for anyone to understand it makes it easier for developers to read and understand code, especially if they’re working with a team or need to revisit old code. 69 Greater flexibility: Because pseudocode isn’t tied to any specific programming language, it can be easily adapted to different languages. This makes it a useful tool for developers who are familiar with multiple languages and need to translate their ideas between them. 70 Enhanced collaboration: Pseudocode can be used as a common language for a team of developers to communicate and collaborate on a project. This can be especially useful for teams working on a project together, as pseudocode allows developers to clearly and concisely communicate their ideas. 71 Local management: Because it’s not executable, your pseudocode won’t need to be hosted online or connected to any external scripts like a full-fledged app would. It can be created and saved in a file on your local machine, in a Cloud file, or even copied into an email. 72 In addition, writing pseudocode is easy to implement at any stage of your development process. Even if you’ve never used it before, you can start right now — regardless of where you are in your coding progress — and immediately gain the 73 Common Pseudocode Use Cases Because of pseudocode’s inherent flexibility, there are plenty of uses for pseudocode — even outside the realm of programming. Here are several common use cases for developers: 74 Planning and designing processes: Pseudocode can be used to plan out the steps of a process, function, or algorithm allowing developers to think through the logic and ensure that it’s correct before implementing it in a specific programming language. 75 Communicating ideas to non-technical stakeholders: Pseudocode can be used to clearly explain the steps of a process or algorithm to non-technical stakeholders such as project managers or clients, in a way that allows them to grasp the concept easily. 76 Collaborating with a team: Pseudocode can be used as a common language for a team of developers to communicate and collaborate on a project, regardless of their individual programming expertise. 77 Adapting code to different programming languages: Because pseudocode isn’t tied to any particular programming or scripting language it can be quickly and easily adapted and translated into different languages. 78 This is especially useful for developers and teams who work with multiple languages. Teaching programming concepts: Pseudocode can be a useful tool for teaching the fundamentals of programming as it allows students to focus on the logic and structure of a program without getting bogged down in syntax. 79 These are just a few examples; many more exist. The possibilities for implementing pseudocode to your advantage are virtually limitless. How To Write Pseudocode There’s no one right way to write pseudocode. 80 The same lack of specific syntax that makes it so flexible is exactly what precludes it from having any particular syntax rules. While some languages like Pascal and Basic offer syntax- specific pseudocode guidelines 81 you can actually write pseudocode using any terminology you like, so long as your terms are ubiquitous and the logic is followable. That said, there are some basic steps and guidelines for pseudocode that most developers adhere to. We’ll delve into these next. 82 Steps For Writing Pseudocode Here are some general steps you can follow to write good pseudocode: Open your text editor: Pseudocode is most often written in a text or HTML editor, You can pick your favorite and open a new file. 83 Define your goal: Determine the purpose of your program or function. What do you want it to do? Separate it into parts: Break down the problem into smaller, more manageable chunks. This can help you think about the problem more clearly 84 and make it easier to arrange the pieces so they work where and when they should. Organize it into steps: Write out the steps of your program in logical order. 85 Use natural language, and avoid using specific programming constructs or methods such as control structures or type casting. Indent your lines: Use indentation to show the structure of your program. 86 For example, you might indent the lines of code that belong inside a loop. Test it: Test your pseudocode to make sure it’s clear and logical. 87 You can do this by walking through it verbally or by having someone else read it and report back to you what they think the pseudocode is supposed to do. Once your pseudocode is written, you’ll need to translate it into an executable script. 88 You can practice this outside your projects by contributing to open-source Git repositories, taking on code challenges, and asking/answering questions on StackOverflow or within your development community Pseudocode Constructs 89 Despite pseudocode’s lack of a defined syntax, there are several common programming constructs that developers often utilize when writing pseudocode. Let’s take a look at each. 90 Sequences A sequence is a group of statements that are executed in a specific order. They’re used to perform or repeat a series of simple actions. 91 Some familiar sequence commands commonly used in pseudocode include INPUT, SET, PRINT, READ, DISPLAY, SHOW, and CALCULATE. Here’s an example of pseudocode that uses some of these commands: 92 PROCESS CalculateCost INPUT price, quantity SET cost = price * quantity PRINT "The cost is: " + cost END 93 This pseudocode defines a process called CalculateCost that takes in a price and quantity multiplies them together to calculate the cost, and then displays the result. 94 Conditionals Conditional statements allow a program to make decisions based on certain conditions then direct the program to execute certain statements if a condition is met (or not met). 95 IF-ELSE, IF-IF ELSE-ELSE, and CASE statements are frequently utilized in pseudocode. Here’s an example showing an IF-ELSE script in pseudocode: IF user = returning PRINT "Welcome back!" ELSE 96 PRINT "Welcome!" In the above example, we’re describing a process that shows a “Welcome back!” message to users who have visited before but shows only “Welcome!” to new users. 97 Iterations Iteration statements repeat a set of steps within a larger function or process. They’re often tasked to perform the same operation on multiple items in a list or to repeat a process until certain conditions are met. 98 Iterations are useful for repeating a set of steps multiple times and can be implemented using various types of loops, including FOR, WHILE, and DO-WHILE loops. Let’s look at some pseudocode that uses a FOR loop to iterate through a list of numbers: 99 PROCESS PrintWholeList INPUT listOfNumbers FOR each number in listOfNumbers PRINT number END FOR END 100 In the above pseudocode, our PrintWholeList process takes in a list of numbers and then iterates through the list, displaying each number on the screen. The FOR loop allows the process to repeat the PRINT command for each item in the list. 101 Alternatively, we could utilize the common pseudocode to accomplish the same as our above loop. In pseudocode, it’s more common to use the keywords 102 REPEAT and UNTIL in place of DO-WHILE: PROCESS PrintWholeList INPUT listOfNumbers SET counter = 0 REPEAT PRINT listOfNumbers[counter] 103 SET counter = counter + 1 UNTIL counter = length of listOfNumbers END As shown here, we can switch out the names, keywords, and syntax pieces all we like. This is just one demonstration of pseudocode’s flexibility. 104 The key is to ensure that the logic is stable while using names that are ubiquitous enough to be read by anyone. You can see some of these constructs used in the pseudocode examples we’ll work with later on. 105 Pseudocode Best Practices As we mentioned earlier, there is no strict syntax for writing pseudocode, since it’s not an actual programming language. That said, here are a few general guidelines that can help you write clear, effective pseudocode each time: 106 Use natural language: Pseudocode should be written in a way that’s easy for anyone to understand, using natural language rather than technical jargon. Keep it simple: Avoid using complex language or syntax, and focus on expressing the steps of the algorithm or process in a clear and concise way. 107 Be specific: Be as specific as possible when writing pseudocode, including information such as variable names and specific values. Leave out unnecessary details: If you’re worrying about which case convention to adopt or whether to use semicolons, you’re overthinking it. 108 Make your pseudocode text as simple and straightforward as possible. Use programming-like elements: While pseudocode should not be written in a specific programming language 109 it can be helpful to use elements such as loops, conditional statements, and function calls to make it easier for readers to understand your program’s steps. Use indentation to show hierarchy: Indentation can be used to show the hierarchy of the steps in your program, making it easier to understand the logic and structure. 110 By following these guidelines, you can write clear and effective pseudocode that you and others can use as a guide for implementing your function or algorithm in a specific programming or scripting language. 111 Testing the logic of an algorithm using Desk checking Desk Checking Algorithm Definition It is non-computerized process of checking the logic of an algorithm before its implementation as a program code. Overview of Desk Checking Algorithm 112 Desk checking is also known as hand tracing that implies the technique of testing an algorithm’s logic and input/output variables by the programmer. Desk check is performed manually by walking through every line in a pseudo-code to identify the bugs in logic and to ensure if the algorithm works as intended. 113 It is performed on an algorithm code using tables with columns as line number, value of variables, conditions if applicable, input- output and result expected. Each line of a pseudo code is assigned a number and this line number is the first field in the table designed for desk check. 114 The variable column will get the value of variables used and condition column identifies the number of conditions applied on the variables are correct or not. Input-output field checks whether the input given by the user is logical and the output displayed by the code is performed according to the logic. 115 Desk checking is similar to proofreading where all checking is being done with a pen and a paper and converting the lines of an algorithm to a table. 116 Steps of desk checking process Analyze the given problem: It is very important for a programmer to understand the problem so as to derive a possible solution for it. Each aspect given in the problem must be specified correctly to obtain the best feasible outcome. 117 Identification of a solution: After understanding the problem, the programmer must identify a solution by checking user inputs, functions or expected outputs. Develop a plan: Programmer usually constructs an outline plan after checking all the possible elements. Gathering all sorts of data 118 and putting it into a framework helps him to draw an outline structure of an algorithm. Design an algorithm: After every possible outline, an algorithm is written as a pseudo code giving the best solution to the problem. 119 Testing: Now desk checking is performed to test the validation of the algorithm by identifying and correcting any logical errors within the code. Advantages of Desk Checking Algorithm 120 Desk checking helps in locating the bugs or issues in an algorithm before the actual coding and ensures that the code performs as expected. It reduces the time for evaluating the logic while implementing an algorithm to program as the programmer himself checks the logic or syntax errors before moving to later stages. 121 Desk checking is a manual and inexpensive method to test the semantics, syntax and the variables used. Pseudo code is tested by passing the sample test values for the variables or conditions used in the code to analyze their correctness. 122 Desk Checking 123 Manually checking each line of an algorithm may help a developer to look for inadequacies that an automatic debugger won’t find. Desk check is usually performed as different columns in a table indicating the variables, conditions or results. 124 Here is an example given for the algorithm designed to compare the values of two integers and then desk check it using a table. Algorithm (Comparing two integers) 1 PROCESS COMPARE () 125 2 INPUT a, b 3 IF a>b THEN 4 DISPLAY “a is greater” 126 5 ELSE 6 DISPLAY “b is greater” 7 ENDIF 127 8 DISPLAY “Result Found” 9 STOP 128 Columns in desk check table: Line number is the first column for every desk check identifying the serial number of the steps to be followed in an algorithm. It is not required to write the line number in pseudo code but is mandatory in desk check table. 129 Line Number a b Conditions Input-Output 1 2 78 56 3 78>56? Yes 4 a is greater 5 6 7 8 Result Found 9 130 Variables: A unique column is used for all the variables and the column name must be same as that of the name of variable used in the algorithm. It is specified in an alphabetical order and as the code continues, the respective value for each variable must be entered in their respective columns. 131 In the given algorithm, ‘a’ and ‘b’ variables are used and inserted into different columns in the desk check table. A sample value for each variable is entered into their respective column. Condition column evaluates the condition applied on various elements within a code and returns the value as true or false. 132 Generally, this column includes the results of statements: IF-Else, WHILE or FOR loop in an algorithm. In the above example, If-Else condition is used to determine the greater value and it is included into condition column in the table. Input-Output column displays the input value given by the user and the output result given by the program. 133 The above algorithm displays the result as ‘a is greater’ and it is defined in the table as well. Examples https://sites.google.com/a/campioncollege.com/ it_eveningschoool/problem-solving-and-programming/desk- check-guide 134 Introduction to Python 135 Python is a general-purpose programming language created by Guido van Rossum in the late 1980s. It was originally designed as a successor to the ABC programming language, and its implementation began in December 1989. Python was first released in 1991, and has since become one of the most popular programming languages in the world. 136 The name Python was chosen by van Rossum in reference to the BBC comedy series Monty Python's Flying Circus. He was a fan of the show, and he thought the name was short, unique, and slightly mysterious. Installing Python 137 There are two ways to install Python on Windows: From the official Python website From the Microsoft Store To install Python from the official Python website: 138 Go to the Python download page: https://www.python.org/downloads/. Click on the Windows installer (64-bit) or Windows installer (32- bit) link, depending on your system. Run the installer and follow the on-screen instructions. 139 Once the installation is complete, you can verify that Python is installed by opening a command prompt and typing python -V. To install Python from the Microsoft Store: Open the Microsoft Store app. Search for Python. 140 Click on the Get button to install Python. Once the installation is complete, you can verify that Python is installed by opening a command prompt and typing python -V. Here are some of the benefits of installing Python from the official Python website: 141 You will get the latest version of Python. You will have access to the full Python documentation. You will be able to install third-party Python modules. Here are some of the benefits of installing Python from the Microsoft Store: 142 It is easy to install and update. It is integrated with Windows, so you can use it from the Start menu or the Windows search bar. It is supported by Microsoft, so you can be sure that it is safe and secure. 143 Whichever method you choose, installing Python on Windows is a relatively simple process. Once you have installed Python, you can start learning the language and creating your own Python programs. 144 First Python Program Let us execute a Python "Hello, World!" Programs in different modes of programming. Python - Interactive Mode Programming 145 We can invoke a Python interpreter from command line by typing python at the command prompt as following − $ python Python 3.6.8 (default, Sep 10 2021, 09:13:53) [GCC 8.5.0 20210514 (Red Hat 8.5.0-3)] on linux 146 Type "help", "copyright", "credits" or "license" for more information. >>> Here >>> denotes a Python Command Prompt where you can type your commands. Let's type the following text at the Python prompt and press the Enter − 147 >>> print ("Hello, World!") If you are running older version of Python, like Python 2.4.x, then you would need to use print statement without parenthesis as in print "Hello, World!". However in Python version 3.x, this produces the following result 148 Hello, World! Python - Script Mode Programming We can invoke the Python interpreter with a script parameter which begins the execution of the script and continues until the script is finished. 149 When the script is finished, the interpreter is no longer active. Let us write a simple Python program in a script which is simple text file. Python files have extension.py. Type the following source code in a test.py file − 150 print ("Hello, World!") We assume that you have Python interpreter path set in PATH variable. Now, let's try to run this program as follows − $ python test.py This produces the following result − 151 Hello, World! Let us try another way to execute a Python script. Here is the modified test.py file − #!/usr/bin/python print ("Hello, World!") 152 We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows − $ chmod +x test.py # This is to make file executable $./test.py 153 This produces the following result − Hello, World! Python Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object. 154 An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. 155 Thus, Manpower and manpower are two different identifiers in Python. Here are naming conventions for Python identifiers − Python Class names start with an uppercase letter. All other identifiers start with a lowercase letter. 156 Starting an identifier with a single leading underscore indicates that the identifier is private identifier. Starting an identifier with two leading underscores indicates a strongly private identifier. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name. 157 Python Reserved Words and as assert break class continue def del elif else except False 158 finally for from global if import in is lambda None nonlocal not or pass raise 159 return True try while with yield Python Lines and Indentation Python programming provides no braces to indicate blocks of code for class and function definitions or flow control. 160 Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example − if True: print ("True") 161 else: print ("False") However, the following block generates an error − if True: print ("Answer") print ("True") else: 162 print ("Answer") print ("False") Thus, in Python all the continuous lines indented with same number of spaces would form a block. Python Multi-Line Statements Statements in Python typically end with a new line. 163 Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example − total = item_one + \ item_two + \ item_three 164 Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example following statement works well in Python − days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 165 Quotations in Python Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal − 166 word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" Comments Python comments are programmer-readable explanation or annotations in the Python source code. 167 They are added with the purpose of making the source code easier for humans to understand, and are ignored by Python interpreter. Comments enhance the readability of the code and help the programmers to understand the code very carefully. Just like most modern languages, Python supports single-line (or end-of-line) and multi-line (block) comments. 168 Python comments are very much similar to the comments available in PHP, BASH and Perl Programming languages. There are three types of comments available in Python Single line Comments Multiline Comments Docstring Comments Single Line Comments 169 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 and the Python interpreter ignores them. Example Following is an example of a single line comment in Python: # This is a single line comment in python print ("Hello, World!") 170 This produces the following result − Hello, World! You can type a comment on the same line after a statement or expression − name = "Madisetti" # This is again comment Multi-Line Comments 171 Python does not provide a direct way to comment multiple line. You can comment multiple lines as follows − # This is a comment. # This is a comment, too. # This is a comment, too. # I said that already. 172 Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments: ''' This is a multiline comment. ''' 173 Example Following is the example to show the usage of multi-line comments: ''' This is a multiline comment. ''' 174 print ("Hello, World!") This produces the following result − Hello, World! Variables Python variables are the reserved memory locations used to store values with in a Python Program. 175 This means that when you create a variable you reserve some space in the memory. Based on the data type of a variable, Python interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to Python variables, you can store integers, decimals or characters in these variables. 176 Creating Python Variables Python variables do not need explicit declaration to reserve memory space or you can say to create a variable. A Python variable is created automatically when you assign a value to it. The equal sign (=) is used to assign values to variables. 177 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. For example − counter = 100 # Creates an integer variable miles = 1000.0 # Creates a floating point variable name = "Zara Ali" # Creates a string variable 178 Printing Python Variables Once we create a Python variable and assign a value to it, we can print it using print() function. Following is the extension of previous example and shows how to print different variables in Python: counter = 100 # Creates an integer variable miles = 1000.0 # Creates a floating point variable 179 name = "Zara Ali" # Creates a string variable print (counter) print (miles) print (name) Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles, and name variables, respectively. 180 When running the above Python program, this produces the following result − 100 1000.0 Zara Ali Delete a Variable 181 You can delete the reference to a number object by using the del statement. The syntax of the del statement is − del var1[,var2[,var3[....,varN]]]] You can delete a single object or multiple objects by using the del statement. For example − del var 182 del var_a, var_b Example Following examples shows how we can delete a variable and if we try to use a deleted variable then Python interpreter will throw an error: counter = 100 183 print (counter) del counter print (counter) This will produce the following result: 100 184 Traceback (most recent call last): File "main.py", line 7, in print (counter) NameError: name 'counter' is not defined Multiple Assignment 185 Python allows you to assign a single value to several variables simultaneously which means you can create multiple variables at a time. For example − a = b = c = 100 print (a) 186 print (b) print (c) This produces the following result: 100 100 100 187 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 − a,b,c = 1,2,"Zara Ali" print (a) 188 print (b) print (c) This produces the following result: 1 2 Zara Ali 189 Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "Zara Ali" is assigned to the variable c. Python Variable Names Every Python variable should have a unique name like a, b, c. A variable name can be meaningful like color, age, name etc. 190 There are certain rules which should be taken care while naming a Python variable: A variable name must start with a letter or the underscore character A variable name cannot start with a number or any special character like $, (, * % etc. 191 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Python variable names are case-sensitive which means Name and NAME are two different variables in Python. Python reserved keywords cannot be used naming the variable. Example Following are valid Python variable names: 192 counter = 100 _count = 100 name1 = "Zara" name2 = "Nuha" Age = 20 zara_salary = 100000 193 print (counter) print (_count) print (name1) print (name2) print (Age) print (zara_salary) 194 This will produce the following result: 100 100 Zara Nuha 20 195 100000 Example Following are invalid Python variable names: 1counter = 100 $_count = 100 zara-salary = 100000 196 print (1counter) print ($count) print (zara-salary) This will produce the following result: File "main.py", line 3 197 1counter = 100 ^ SyntaxError: invalid syntax Python Local Variable Python Local Variables are defined inside a function. We can not access variable outside the function. 198 A Python functions is a piece of reusable code and you will learn more about function in Python - Functions lecture. Following is an example to show the usage of local variables: def sum(x,y): sum = x + y return sum 199 print(sum(5, 10)) 15 Python Global Variable Any variable created outside a function can be accessed within any function and so they have global scope. Following is an example of global variables: 200 x=5 y = 10 def sum(): sum = x + y return sum print(sum()) This will produce the following result: 201 15 Data Types Python Data Types are used to define the type of a variable. It defines what type of data we are going to store in a variable. The data stored in memory can be of many types. 202 For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various built-in data types Numeric - int, float, complex String - str Sequence - list, tuple, range Binary - bytes, bytearray, memoryview 203 Mapping - dict Boolean - bool Set - set, frozenset None - NoneType Python Numeric Data Type Python numeric data types store numeric values. 204 Number objects are created when you assign a value to them. For example − var1 = 1 var2 = 10 var3 = 10.023 Python supports four different numerical types − 205 int (signed integers) long (long integers, they can also be represented in octal and hexadecimal) float (floating point real values) complex (complex numbers) Example 206 Following is an example to show the usage of Integer, Float and Complex numbers: # integer variable. a=100 print("The type of variable having value", a, " is ", type(a)) 207 # float variable. b=20.345 print("The type of variable having value", b, " is ", type(b)) # complex variable. c=10+3j print("The type of variable having value", c, " is ", type(c)) 208 Python String Data Type Python Strings are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. 209 The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in Python. For example − str = 'Hello World!' print (str) # Prints complete string print (str) # Prints first character of the string 210 print (str[2:5]) # Prints characters starting from 3rd to 5th print (str[2:]) # Prints string starting from 3rd character print (str * 2) # Prints string two times print (str + "TEST") # Prints concatenated string This will produce the following result − Hello World! H 211 llo llo World! Hello World!Hello World! Hello World!TEST Python List Data Type Python Lists are the most versatile compound data types. 212 A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where as C array can store elements related to a particular data type. 213 The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example − 214 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print (list) # Prints complete list print (list) # Prints first element of the list print (list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting from 3rd element 215 print (tinylist * 2) # Prints list two times print (list + tinylist) # Prints concatenated lists This produce the following result − ['abcd', 786, 2.23, 'john', 70.2] abcd [786, 2.23] [2.23, 'john', 70.2] 216 [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] Python Dictionary Python dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. 217 A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example − dict = {} dict['one'] = "This is one" 218 dict = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print (dict['one']) # Prints value for 'one' key print (dict) # Prints value for 2 key print (tinydict) # Prints complete dictionary print (tinydict.keys()) # Prints all the keys 219 print (tinydict.values()) # Prints all the values This produce the following result − This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john'] 220 Python dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered. Python Boolean Data Types Python boolean type is one of built-in data types which represents one of the two values either True or False. 221 Python bool() function allows you to evaluate the value of any expression and returns either True or False based on the expression. Examples Following is a program which prints the value of boolean variables a and b − a = True 222 # display the value of a print(a) # display the data type of a print(type(a)) This produce the following result − true 223 Following is another program which evaluates the expressions and prints the return values: # Returns false as a is not equal to b a=2 b=4 print(bool(a==b)) 224 # Following also prints the same print(a==b) # Returns False as a is None a = None print(bool(a)) # Returns false as a is an empty sequence a = () 225 print(bool(a)) # Returns false as a is 0 a = 0.0 print(bool(a)) # Returns false as a is 10 a = 10 226 print(bool(a)) This produce the following result − False False False False 227 False True Python Data Type Conversion Sometimes, you may need to perform conversions between the built-in data types. 228 To convert data between different Python data types, you simply use the type name as a function. Conversion to int Following is an example to convert number, float and string into integer data type: a = int(1) # a will be 1 229 b = int(2.2) # b will be 2 c = int("3") # c will be 3 print (a) print (b) print (c) This produce the following result − 230 1 2 3 Conversion to float Following is an example to convert number, float and string into float data type: a = float(1) # a will be 1.0 231 b = float(2.2) # b will be 2.2 c = float("3.3") # c will be 3.3 print (a) print (b) print (c) This produce the following result − 1.0 232 2.2 3.3 Conversion to string Following is an example to convert number, float and string into string data type: a = str(1) # a will be "1" b = str(2.2) # b will be "2.2" 233 c = str("3.3") # c will be "3.3" print (a) print (b) print (c) This produce the following result − 1 2.2 234 3.3 Operators Python operators are the constructs which can manipulate the value of operands. These are symbols used for the purpose of logical, arithmetic and various other operations. 235 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Python Operators Python language supports the following types of operators. 236 Arithmetic Operators Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators 237 Let us have a quick look on all these operators one by one. Operator Name Example + Addition 10 + 20 = 30 - Subtraction 20 – 10 = 10 * Multiplication 10 * 20 = 200 238 / Division 20 / 10 = 2 % Modulus 22 % 10 = 2 ** Exponent 4**2 = 16 // Floor Division 9//2 = 4 Example 239 Following is an example which shows all the above operations: a = 21 b = 10 # Addition print ("a + b : ", a + b) 240 # Subtraction print ("a - b : ", a - b) # Multiplication print ("a * b : ", a * b) 241 # Division print ("a / b : ", a / b) # Modulus print ("a % b : ", a % b) # Exponent 242 print ("a ** b : ", a ** b) # Floor Division print ("a // b : ", a // b) This produce the following result − a + b : 31 243 a - b : 11 a * b : 210 a / b : 2.1 a%b: 1 a ** b : 16679880978201 a // b : 2 244 Python Comparison Operators Python comparison operators compare the values on either sides of them and decide the relation among them. They are also called relational operators. These operators are equal, not equal, greater than, less than, greater than or equal to and less than or equal to. 245 Operator Name Example == Equal 4 == 5 is not true. != Not Equal 4 != 5 is true. > Greater Than 4 > 5 is not true. < Less Than 4 < 5 is true. >= Greater than or Equal to 4 >= 5 is not true. 246 b) # Less Than print ("a < b : ", a < b) 4 = b) # Less Than or Equal to print ("a