Structured Programming Languages (Python) Lecture Notes PDF

Document Details

Uploaded by Deleted User

Helwan University

2024

Dr Engy Yehia Dr. Hend Saad

Tags

structured programming python programming computer programming programming languages

Summary

This document is a set of lecture notes on structured programming languages using Python. It covers fundamental programming concepts like variables, data types, conditional logic, loops, arrays, and functions, specifically for undergraduate students at Helwan University. The notes are compiled from various sources, summarized, and presented in an easily digestible format.

Full Transcript

9 Bl ox y, > ‘ Ro J wlglo aegh Lecture Notes in SE Amp BUS Structured Programming Languages Python Level 3...

9 Bl ox y, > ‘ Ro J wlglo aegh Lecture Notes in SE Amp BUS Structured Programming Languages Python Level 3 Prepared by Dr Engy Yehia Dr. Hend Saad Information Systems Deprtment Faculty of Commerce and Business Administration Helwan Univesity =} Introduction ilgle daole - roled! GES aijaig 525 jee tpl SMgell glad dupes SoSH dull 3 gfe iil gall AB give ASL! 3 98> 2024 Jodl sly Jt Loa! = Preface Preface This lecture notes are about the basic concepts of programming languages with practical implementation using Python programming language. This material introduces computer based problem solving using algorithms and Python including variables and data types, conditional logic, loops, arrays, and functions. This material is specially made for the undergraduate students. It contains what will be explained in the lectures. The selected topics have been collected from various books, websites, and open sources, that have been edited and summarized. Its only purpose is to help the students to follow what will be explained in the lectures and present it in an easy and suitable way. =} Table of Contents Table of Contents Chapter 1: Introduction to Programming Languages Chapter 2: Getting Started with Python Chapter 3: Variables and Data Types Chapter 4: Conditional Logic Chapter 5: Loops Chapter 6: Lists and Arrays Chapter 7 Functions Case Studies Knowledge Check - MCQ Additional Video resources References = Chapter 1: Introduction to Programming Languages Chapter 1 Introduction to Programming Languages Objectives 1. Introduce programming languages 2. Explain the classification of programming languages 3. List the history of programming languages 4. Describe the paradigms of programming languages 5. Learn how to solve a problem using programming languages 6. Present Algorithms, pseudocode, and Flowcharts. =} 1.1 Introduction 1.1 Introduction We call the electronic part of a computer hardware, and the programs part software. “Software is a set of programs that performs multiple tasks together.” “A program is a set of instructions given to a computer to perform a specific operation. “ When you program a computer, you provide it instructions that are transformed into bits, the only thing that the electronics can understand. A bit can only have two values: 0 and 1. “Programs consist of a series of instructions to tell a computer exactly what to do and how to do it.” Your phone is controlled by a large program known as iOS or Android. That is a massive program, and it's not even accurate to refer to it as a program; it's a collection, an ecosystem of programs. Which we assign a name. Your vehicle is governed by software. Applications on a computer are programs. Additionally, the applications on your phone. “These computer programs are written in a programming language which are high-level languages. “ High level languages are virtually human languages that are more complex than machine language or low level language, which are computer-understandable languages. To communicate with computers, we use a variety of languages including C, C++, C#, Java, and Python. The computer understands only binary language (the language of 0's and 1's), also known as machine-understandable language or low- level language; however, the algorithms we are going to write are in a high-level language that is nearly identical to human language. =} 1.2 Classification of Programming Languages 1.2 Classification of Programming Languages “A programming language is a set of instructions and rules that we use to interface with a machine.” A programming language defines a set of instructions that are compiled to allow the CPU (Central Processing Unit) to execute a specific task. Programming languages include C, C++, Pascal, Ada, COBOL, etc. Each programming language has its own set of keywords and syntax, which are used to generate an instruction set. There have been thousands of programming languages developed to date, but each language serves a specific purpose. These languages vary in the extent of hardware abstraction they provide. Some programming languages provide less or no abstraction while some provide higher abstraction. Based on the levels of abstraction, they can be classified into two categories: « Low-level language * High-level language. Below image describes the abstraction level of programming languages from hardware. As you can see machine language provides no abstraction. Assembly language provide less abstraction from the hardware. Whereas high level language provides a higher level of abstraction. C, C++, Java, Php High Level Language Assembly Language Machine Language Hardware = 1.2.1 Low-level lanquage 1.2.1 Low-level language “The low-level language is a programming language that provides no abstraction from the hardware, and it is represented in 0 or 1 forms, which are the machine instructions.” Low-level language refers to the standard languages that provide no abstraction from the hardware components. It is the language that corresponds directly to the machine it is operating on. Machine level language and Assembly language are the languages that belong to this category. Low Level Language Machine Language Assembly Language Machine-level language “The machine-level language is a language that consists of a set of instructions that are in the binary form 0 or 1. “ As we know that computers can only comprehend machine instructions, which are represented by binary digits (0 and 1), the instructions given to the computer must also be in binary. Creating a program in a machine-level language is a challenging endeavor, as it is not simple for programmers to write machine instructions. It is prone to errors because it is difficult to comprehend, and its maintenance costs are extremely high. A machine-level language is not portable because each computer has its own machine instructions; therefore, a program written in one computer is invalid in another. various processor architectures require various machine codes; for instance, a PowerPC processor's RISC architecture requires a different machine code than an Intel x86 processor's CISC architecture. For example: SUB AX, BX = 00001011 00000001 00100010 is a subtraction instruction that subtracts the contents of registers AX and BX. In the early days of programming, only programs written in machine language existed. Every program was written as a sequence of binary digits. Before programming in machine language, a programmer must possess supplementary knowledge of the machine's architecture. Programming in machine language is a laborious task. It is extremely challenging to recall the sequence of binaries for various computer architectures. Therefore, it is not commonly used today. Assembly Language “The assembly language contains some human-readable commands such as mov, add, sub, etc. “ Using assembly language, an extended form of machine-level language, helps to alleviate some of the difficulties we encountered with machine-level programming. Since assembly language instructions are composed of English words such as mov, add, and sub, it is simpler to write and comprehend.As computers can only comprehend machine-level instructions, we need a translator to convert assembly code to machine code. “The translator used for translating the code is known as an assembler.” The assembly language code is not portable due to the fact that the data is stored in computer registers and the computer must be aware of the different register sets. Assembly code is not speedier than machine code because assembly language is higher in the hierarchy than machine language. This means that assembly language provides some abstraction from the hardware, whereas machine language provides none. Assembly language continues to be used. It is utilized for the development of operating systems, device drivers, compilers, and other programs requiring direct hardware access. The distinctions between machine-level language and assembly language are as follows: Machine-level language Assembly language The machine-level language The assembly language comes comes at the lowest levelinthe | above the machine language he n ba re ' 4 Machine-level language Assembly language The machine-level language The assembly language comes comes at the lowest level in the above the machine language hierarchy, so it has zero means that it has less abstraction abstraction level from the level from the hardware. hardware, It cannot be easily understood by It is easy to read, write, and humans. maintain. The machine-level language is The assembly language is written written in binary digits, i.e., 0 and in simple English language, so it 1. is easily understandable by the users. It does not require any translator In assembly language, the as the machine code is directly assembler is used to convert the executed by the computer. assembly code into machine code. It is a first-generation It is a second-generation programming language. programming language. 1.2.2 High-Level Language 1.2.2 High-Level Language “The high-level language is a programming language that allows a programmer to write the programs which are independent of a particular type of computer. Because they are more similar to human languages than machine-level languages, high-level languages are deemed to be of a higher level. The high-level programming languages are straightforward and resemble English. They are simple to comprehend; the statements are legible and provide the computer with precise instructions. Always, the languages are program-oriented. It is the language that is independent of the hardware on which it operates. These high-level programming languages are more readable than others, are simple to debug, have greater portability, and make software development simple. High level programs require compilers/interpreters to translate source code to machine language. Multiple machine languages can be generated from source code written in a high-level programming language. Therefore, they are machine independent. Almost all programs are created with a high-level programming language today. Using a high-level language, we can create a variety of applications. They are used to create desktop applications, websites, system software, and utility software, among others. Based on their execution mechanism, high-level languages are divided into two categories: compiled and interpreted languages. High Level Language Compiled Language Interpreted Language Compiled Languages Compiled languages are converted directly into machine code that the processor can execute As a result, they tend to be faster and more efficient to execute than interpreted languages. They also give the developer more control over hardware aspects, like memory management and CPU usage. Compiled languages need a “build” step - they need to be manually compiled first. You need to “rebuild” the program every time you need to make a change. Programs that are compiled into native machine code tend to be faster than interpreted code. However, additional time needed to complete the entire compilation step before testing. Also, compilers dependents on the platform of the generated binary code Examples of pure compiled languages are C, C++, Erlang, Haskell, Rust, and Go. Interpreted Languages “Interpreters run through a program line by line and execute each command. Interpreted languages were once significantly slower than compiled languages. But, with the development of just-in-time compilation, that gap is shrinking. Interpreted languages tend to be more flexible, and often offer features like dynamic typing and smaller program size. Also, because interpreters execute the source program code themselves, the code itself is platform independent. The most notable disadvantage is typical execution speed compared to compiled languages. Examples of common interpreted languages are PHP, Ruby, Python, and JavaScript. Most programming languages can have both compiled and interpreted implementations — the language itself is not necessarily compiled or interpreted. However, for simplicity’s sake, they’re typically referred to as such. Python, for example, can be executed as either a compiled program or as an interpreted language in interactive mode. On the other hand, most command line tools, CLIs, and shells can theoretically be classified as interpreted languages. The following are the differences between low-level language and high-level language: Low level language High level language They are faster than high level = They are comparatively slower. Low level language High level language They are faster than high level They are comparatively slower. language. Low level languages are High level languages are not memory efficient. memory efficient. Low level languages are difficult High level languages are easy to to learn. learn. Programming in low level Programming in high level do not requires additional knowledge require any additional knowledge of the computer architecture. of the computer architecture. They are machine dependent They are machine independent and are not portable. and portable. They provide less or no They provide high abstraction abstraction from the hardware. from the hardware. They are more error prone. They are less error prone. Debugging and maintenance is Debugging and maintenance is difficult. comparatively easier. They are generally used for They are used to develop a variety developing system software's of applications such as — desktop (Operating systems) and applications, websites, mobile embedded applications. software's etc. =} 1.3 History of Computer Programming Languages 1.3 History of Computer Programming Languages « Ada Lovelace and Charles Babbage created the first computer programming language in 1883 with the Analytical Engine, a mechanical computer. Babbage focused on computing numbers, but Lovelace saw that the computer's numbers might represent more. She created the first Analytical Engine algorithm. New technologies and various requirements have led to many more languages. Assembly language, a low-level computer programming language, was first used in the Electronic Delay Storage Automatic Calculator in 1949. It simplifies machine code, the instructions needed to program a computer. Autocode was a 1952 term for a family of early programming languages. Alick Glennie from Manchester University produced the first for the Mark 1 computer. Some consider autocode the first compiled computer programming language, meaning a compiler can immediately translate it into machine code. In 1957, John Backus created Formula Translation, a programming language for complicated scientific, mathematical, and statistical calculations. One of the first computer programming languages still used. In 1958, a group invented Algol, an algorithmic language for science. Pascal, C, C++, and Java were built on Algol. Computer programming language COBOL was designed in 1959 by Dr. Grace Murray Hopper for all computer brands and models. COBOL is Common Business Oriented Language. ATMs, credit card processing, telephones, hospital and government computers, automotive systems, and traffic signals use it. LISP was created by MIT's John McCarthy in 1959 and is still used. It stands for LISt Processing language. It was originally developed for artificial intelligence research but may currently be used with Ruby or Python. In 1964, Dartmouth College's John G. Kemeny and Thomas E. Kurtz designed Beginner's All-purpose Symbolic Instruction Code for those without technical or mathematical backgrounds to utilize computers. Bill Gates and Paul Allen modified BASIC. Microsoft's debut product. Niklaus Wirth called His programming language Pascal after French mathematician, physicist, and philosopher Blaise Pascal in 1970. Pascal dominated Apple's early software development. At the Xerox Palo Alto Research Center, Alan Kay, Adele Goldberg, and Dan Ingalls created Smalltalk in 1972. Smalltalk allowed programmers to edit code in real time and introduced other features found in Python, Java, and Ruby. C, invented by Dennis Ritchie at Bell Labs in 1972, is considered the first high-level programming language. Higher- level programming languages are more like human language than machine code. C was created so Unix could run on many computers. It influenced Ruby, C#, Go, Java, JavaScript, Perl, PHP, and Python. IBMers Donald D. Chamberlin and Raymond F. Boyce designed SQL in 1972. SQL stands for Structured Query Language. It examines and modifies database data. Data is added, removed, or viewed via SQL queries. In 1978, Cleve Moler created MATLAB. MATLAB means Matrix Laboratory. Mostly used in math, research, and education. It produces two- and three-dimensional visuals. Objective-C, invented by Brad Cox and Tom Love in 1983, is Apple's main programming language for macOS and iOS. Bjarne Stroustrup designed C++ in 1983 as a C extension. One of the most widely spoken languages. Adobe Photoshap and game engines use C++. Most bundled software is C++. Text manipulation scripting language Perl was established in 1987 by Larry Wall. It aided report processing. It is * widely used for Linux system administration, Web development, and network programming. Haskell was named after American mathematician and logician Haskell Brooks Curry. A purely functional programming language, Haskell is mathematical. Many industries use it, especially those that handle sophisticated calculations, records, and numbers. ¢ Python, invented by Guido Van Rossum in 1991, is easier to understand and uses fewer lines of code than most programming languages. It was named after Monty Python. Popular websites like Instagram use Python frameworks. Microsoft launched Visual Basic in 1991 to allow programmers to choose and alter pre-selected code parts using a GUI and drag-and-drop interface. R was created in 1993 by Ross Ihaka and Robert Gentleman at the University of Auckland in New Zealand. Statisticians and data analysts use it most. In 1995, Java was initially called Oak by Sun Microsystems. It was originally built for cable boxes and mobile devices but was later upgraded for Internet delivery. From desktops to smartphones to parking meters, Java is everywhere. Three billion Java-enabled devices! Web servers run PHP, introduced by Rasmus Lerdorf in 1995, for Web development. It started as Personal Home Page because Lerdorf used it to manage his internet information. PHP is widely used for website and blog creation. PHP powers WordPress, a popular website builder. ¢ Yukihiro "Matz" Matsumoto designed Ruby in 1995 by combining his favorite languages to create a general-purpose programming language. It is common in Web app development. Ruby code executes slowly but lets programmers build and run programs quickly. JavaScript, developed by Brendan Eich in ten days in 1995, improves Web browser interactions. Nearly all major websites use Javascript. C# was established in 2000 by Microsoft to combine C++'s computational capability with Visual Basic's simplicity. C# is comparable to Java and based on C++. Most Microsoft products use it for desktop application development. Martin Odersky designed Scala in 2003. Scala combines mathematically-based functional programming with data- centric object-oriented programming. Groovy, developed from Java, was invented by James Strachan and Bob McWhirter in 2003 and improves developer productivity by being simple to learn and concise. Go was designed by Google in 2009 to overcome major software system issues. Since languages like C++, Java, and Python have changed computer and technology use, huge computer systems caused challenges. Go improved programming to make complicated software systems easier to write, read, and maintain. productivity by being simple to learn and concise. « Go was designed by Google in 2009 to overcome major software system issues. Since languages like C++, Java, and Python have changed computer and technology use, huge computer systems caused challenges. Go improved programming to make complicated software systems easier to write, read, and maintain. « Apple created Swift in 2014 to replace C, C++, and Objective-C with a simpler, less error-prone language. It works for desktop, mobile, and cloud apps. =} 1.4Computer Programming Languages Today 1.4 Computer Programming Languages Today Most computer programming languages were built on ideas from other programming languages or were based on them. Even though newer languages are built on top of older ones, the newer languages make it easier for coders to do their jobs. Businesses rely greatly on programs to handle all of their data, transactions, and customer service needs. For their study, science and medicine need programs that are both accurate and hard to understand. Mobile apps need to be changed to keep up with what people want. And because of all of these new and growing needs, both old and new computer code languages will continue to be important in modern life. Most Popular Programming Languages eC « Python « C++ « Java « SCALA ° CH *R « Ruby « Go « Swift « JavaScript Characteristics of a programming Language ¢« A programming language must be simple, straightforward to learn and use, readable, and understandable by humans. « Abstraction is essential Following the capacity to define a complex structure, a programming language's degree of usability is among its defining characteristics. « Always prefer a portable programming language. ¢ The efficiency of a programming language must be high so that it can be readily converted into machine code and executed with minimal memory usage. « A programming language should be well-structured and well-documented for application development purposes. «A programming language must include the instruments necessary for the creation, debugging, testing, and maintenance of a program. « A programming language should offer an integrated development environment (IDE). « A programming language's syntax and semantics must be consistent. =} 1.5 Programming Paradigms 1.5 Programming Paradigms Different software requirements, programming practices, and developer preferences have spawned a multitude of programming paradigms over the course of several decades. Therefore, each programming paradigm provides a unique conceptual framework for logically considering the structure, organization, and data flow of your code. “A programming paradigm refers to a pattern of programming. It is an idea or a methodology or a set of principles that have been followed for writing software applications and designing programming languages and frameworks.” Most styles of programming or programming language themes can be broadly classified into three types based on their design, structures, principles, rules, and practices: ¢ Procedural Programming ¢ Object-Oriented Programming (OOP) « Functional Programming Procedural Programming “Procedural Programming is a programming language that is derived from structure programming and based upon the concept of calling procedures. It follows a step-by-step approach in order to break down a task into a set of variables and routines via a sequence of instructions.” In procedural programming, code is implemented sequentially from start to finish. You tell the computer what to do, from start to completion, and it does. The term's origin is "procedure." A procedure is fundamentally a series of executable instructions or computational steps. Therefore, procedural programming is all about the concept of completing tasks sequentially. This involves considering the operation of your code as a sequence of actions that must be carried out. Your code is not organized into logical categories or object-like entities in this section. You simply consider the various operations that must occur sequentially and code them. Some of the common languages that use procedural programming are: * Fortran « Pascal eC * Basic Procedural Programming Object Oriented Programming “Object-oriented programming is a computer programming design philosophy or methodology that organizes/ models software design around data or objects rather than functions and logic.” Object-Oriented Programming (OOP) is the most prevalent programming paradigm and is typically the first one introduced to novices, OOP systems enable programmers to divide their software into reusable blueprint-like components that prescribe a common structure that code entities can adhere to and identify with. This is implemented via classes and objects. Objects have a type, also known as class. Smalltalk and subsequently Java popularized object-oriented programming, or OOP. OOP-based programs are more abstract than a catalog of tasks to be performed by the computer. We conceive in terms of objects and their interactions. = 1.5 Programming Paradigms OOP. OOP-based programs are more abstract than a catalog of tasks to be performed by the computer. We conceive in terms of objects and their interactions. In object-oriented programming languages, an object is an instance or actual entity that conforms to a template (class). The object is an instance of this blueprint and is used to encapsulate a class's data and methods. For instance, the objects of the Car class would be actual automobiles, each with its own attributes (e.g. name, manufacturer, model, horsepower, etc.) and methods (e.g. drive, park, get cleansed, etc.). The class provides a common set of functions for its objects to use, as well as a large number of empty attributes (placeholders) that each object can then populate with its own identifying information. Some of the common OOP languages include: « Java « Ctt+ « Python + Lisp « Perl ° CH « JavaScript « Lua Class Object /a.@) 0: Nissan Functional Programming “Functional programming is an approach to problem solving that treats every computation as a mathematical function. The outputs of a function rely only on the values that are provided as input to the function and don't depend on a particular series of steps that precede the function. “ Recursion is indispensable to functional programming. A recursive function can iterate until a specified condition is met. Similar to iteration in procedural programming, but applied to a single function rather than a series of steps. Functional programming is a programming methodology derived from mathematical functions. In functional programming, code is organized into small functions, and each function returns the same result given the same inputs. Same inputs yield identical outputs. This is a crucial consideration. Composing functions, passing them as parameters, and utilizing function operations such as recursion allow us to solve all problems without having to create complex structures for our abstractions. Input ! A Function ) Output Though there are only a few pure functional programming languages, here are some which prominently support it: « Haskell carr Some of the common OOP languages include: * Java e C++ « Python * Lisp « Perl « C# « JavaScript * Lua Class Object Functional Programming “Functional programming is an approach to problem solving that treats every computation as a mathematical function. The outputs of a function rely only on the values that are provided as input to the function and don't depend on a particular series of steps that precede the function. “ Recursion is indispensable to functional programming. A recursive function can iterate until a specified condition is met. Similar to iteration in procedural programming, but applied to a single function rather than a series of steps. Functional programming is a programming methodology derived from mathematical functions. In functional programming, code is organized into small functions, and each function returns the same result given the same inputs. Same inputs yield identical outputs. This is a crucial consideration. Composing functions, passing them as parameters, and utilizing function operations such as recursion allow us to solve all problems without having to create complex structures for our abstractions. Input | A Function ’ Output Though there are only a few pure functional programming languages, here are some which prominently support it: « Haskell « SML « Clojure « Scala e Erlang « Clean « F# « Mathematica =} 1.6 Computer-Based Problem Solving 1.6 Computer-Based Problem Solving “Computer based problem solving is a systematic process of designing, implementing and using programming tools during the problem solving stage. “ This method enables the computer system to be more human-friendly than machine-friendly. The culmination of this procedure is the development of software instruments designed to address the issue under consideration. Software is merely a compilation of computer programs, and programs are a set of instructions that direct the hardware of a computer. These instructions must be precise in order to solve the problem. The software should be error-free and well-documented after its development. “Software development is the process of creating such software, which satisfies end user’s requirements and needs. “ Steps of computer-based problem solving ¢ Problem Analysis EECCCE ¢ Program Design * Coding (Programming) * Compilation and Execution Process ¢ Debugging and Testing ¢ Program Documentation 1- Problem Analysis Problem analysis is the process of defining a problem and decomposing the entire system into its constituent elements in order to identify potential inputs, processes, and outputs associated with the problem. Step 1: Understanding the problem Solving a problem requires a thorough comprehension of the issue. First, we must determine what problem is being addressed, The magnitude and complexity of the problem determine the clarity of the problem statement. This initial step is crucial because we frequently fail to completely comprehend the problem. If you do not thoroughly comprehend the problem, it will be much more difficult to solve it. Step 2: Specification of Output Before identifying the system's required inputs, we must identify the system's outputs. The optimal method for specifying output is to create output forms and the desired format for displaying results. The best individual to evaluate an output form is the system's end user, i.e., the person who benefits from the software. The programmer can create various forms that must be evaluated to determine whether they are beneficial. Step 3: Specifying Input Requirements : After the outputs have been specified, the inputs and data required by the system must also be specified. One must identify the inventory of required inputs and the data source. In a straightforward program that maintains student records, for instance, the inputs could include the student's name, address, roll numbers, etc. The sources could be the students or the individual supervising them. Step 4: Specifying Processing Requirements : When output and inputs are specified, the process that converts inputs into the desired output must be specified. If the proposed program is to replace or supplement an existing one, the current processing procedures must be evaluated thoroughly and any potential improvements noted. If the proposed system is not intended to replace an existing system, it is prudent to evaluate another system that addresses the same issue. Step 5: Evaluating the Feasibility : After successfully completing the four preceding stages, it is necessary to determine whether the things accomplished thus far are practical and realizable. To replace an existing system, one must determine the extent to which the potential enhancements outperform the existing system or other comparable systems. Step 6: Problem Analysis Documentation moe 1 48 a a 4 1 a a oe ry 7 P 1 oa) 4 a4 ao as aig gy =} 1.6 Computer-Based Problem Solving Step 6: Problem Analysis Documentation Before concluding the program analysis phase, it is advisable to document what has been accomplished in the initial phase of program development. The document should include the program's stated objectives, output and input specifications, processing requirements, and feasibility. 2- Program Design The second phase of the software development or computer-aided problem-solving cycle is program design. This phase involves preparing the algorithms, flowcharts, and pseudocodes described in the following section. This phase generally aims to make the program more user-friendly, practicable, and optimized. In this phase, where tasks are converted into a structured layout without the use of a computer, the programmer only needs a pen and pencil. In structured programming, a particular task is broken down into a number of subtasks known as modules. Each procedure is subdivided until no further subdivisions are necessary. This method of separating a program into modules and sub-modules is known as the “top down" design approach. By dividing a program into modules (functions), a given programming task is broken down into smaller, more manageable tasks. 3- Coding (Programming) In this phase, genuine program development takes place. A programmed program is commonly referred to as its source code. The procedure of coding can be carried out in any language (high level or low level). In this phase, the programmer writes a sequence of instructions that are ready to be executed, which is when the computer is actually used. Programming is another name for coding. 4- Compilation and Execution Process In most cases, coding is performed in either a high level language or a low level language (assembly language). These languages must be translated into machine level language in order for the computer to comprehend them. A compiler/interpreter (for high level languages) or an assembler (for assembly language programs) performs the translation procedure. The resulting machine language code can be saved and executed promptly or later. Each program statement in an interpreted program is converted to machine code prior to execution. The execution occurs promptly one statement at a time sequentially. BASIC is one of the most commonly employed interpretive languages. Unlike an interpreter, a compiler transforms source code into object code. After obtaining an object code, compiled programs may be quicker and more efficient than interpreted programs. Compilation Method Before a program can be executed, its source code must pass through several processes. In the first stage, syntax errors in the source code are analyzed. After syntax errors are identified, a source file is transmitted through a compiler, which converts high-level language into object code (unexecutable machine code). The object code is then linked with pre- compiled library functions by a linker, creating an executable program. The memory is then supplied with this executable program for execution. 5- Debugging and Testing To gain a more intuitive understanding of debugging and testing, let's first examine the various programming errors that can occur. Error Error indicates that the compilation and execution of the computer program failed, or that the expected results were not obtained. Debugging and testing are systematized phases of the program development cycle that serve to eliminate program errors. Following is a list of the various programming errors we may encounter: Syntax Error: A syntax error is a violation of programming principles that occurred during its creation. A syntax error prevents the code from running. Using a compiler, syntax errors can be readily detected during the compilation process. Logical Error: A logical error occurs when a programmer uses improper logic to solve a problem or omits a required programming procedure. When a logical error occurs, the program executes, but the result is incorrect. Run Time Error: Run time error occurs during the execution of program. Runtime errors include stack overflow, divide by zero, and floating point error, among others. Debugging Debugging is the process of locating and eliminating errors from a computer program; otherwise, the program will collapse. Even with the utmost care during program design and coding, a program may still contain errors that manifest during compilation, linking, or execution. Debugging is typically performed by the programmer. Testing Testing is performed to determine whether the completed software product functions or operates in accordance with the defined expectations. Generally, testing is performed by a testing team that repeatedly executes the program in an effort to discover errors. A list of errors and associated information is sent to the program developer or development team following testing. 4- Compilation and Execution Process In most cases, coding is performed in either a high level language or a low level language (assembly language). These languages must be translated into machine level language in order for the computer to comprehend them. A compiler/interpreter (for high level languages) or an assembler (for assembly language programs) performs the translation procedure. The resulting machine language code can be saved and executed promptly or later. Each program statement in an interpreted program is converted to machine code prior to execution. The execution occurs promptly one statement at a time sequentially. BASIC is one of the most commonly employed interpretive languages. Unlike an interpreter, a compiler transforms source code into object code. After obtaining an object code, compiled programs may be quicker and more efficient than interpreted programs. Compilation Method Before a program can be executed, its source code must pass through several processes. In the first stage, syntax errors in the source code are analyzed. After syntax errors are identified, a source file is transmitted through a compiler, which converts high-level language into object code (unexecutable machine code). The object code is then linked with pre- compiled library functions by a linker, creating an executable program. The memory is then supplied with this executable program for execution. 5- Debugging and Testing To gain a more intuitive understanding of debugging and testing, let's first examine the various programming errors that can occur. Error Error indicates that the compilation and execution of the computer program failed, or that the expected results were not obtained. Debugging and testing are systematized phases of the program development cycle that serve to eliminate program errors. Following is a list of the various programming errors we may encounter: Syntax Error: A syntax error is a violation of programming principles that occurred during its creation. A syntax error prevents the code from running. Using a compiler, syntax errors can be readily detected during the compilation process. Logical Error: A logical error occurs when a programmer uses improper logic to solve a problem or omits a required programming procedure. When a logical error occurs, the program executes, but the result is incorrect. Run Time Error: Run time error occurs during the execution of program. Runtime errors include stack overflow, divide by zero, and floating point error, among others. Debugging Debugging is the process of locating and eliminating errors from a computer program; otherwise, the program will collapse. Even with the utmost care during program design and coding, a program may still contain errors that manifest during compilation, linking, or execution. Debugging is typically performed by the programmer. Testing Testing is performed to determine whether the completed software product functions or operates in accordance with the defined expectations. Generally, testing is performed by a testing team that repeatedly executes the program in an effort to discover errors. A list of errors and associated information is sent to the program developer or development team following testing. 6- Program Documentation Program documentation is the process of gathering program-related information. The documentation process begins with problem analysis and continues through testing and refining. There are two distinct categories of documentation, namely: User's Documentation and Programmer's Documentation Programmer’s documentation contains all the technical details. Without adequate documentation, even the original programmer will find it difficult to update and maintain the program. The documentation of a programmer contains the information necessary for updating and maintaining the program. * Program analysis document containing a concise statement of the program's objectives, outputs, and processing procedures. * Program design documents containing the appropriate flowcharts and diagrams. * Program verification documents for outlining, testing, and correcting procedures, as well as a sample data and results list. * Log used to record future program maintenance and revision activity. User documentation is necessary for the end user who installs and utilizes the application. The package includes installation instructions and a user manual. = 1.7 Algorithms, Pseudocode, and Flowcharts 1.7 Algorithms, Pseudocode, and Flowcharts “A computer program follows an algorithm (a sequence of activities) which can be represented using pseudocode (code-like English text statements) or a flowchart (labelled symbols connected to show the flow of action). “ Pseudocode and flowcharts are used to help programmers plan and describe their proposed program. Pseudocode and flowcharts are used in assessments to determine if learners can follow the underlying algorithm or describe a system in terms of an algorithm. The algorithm, pseudocode and flowchart include following three types of control structures. 1. Sequence: In the sequence structure, statements are placed one after the other and the execution takes place starting from up to down. 2. Branching (Selection): In branch control, there is a condition and according to a condition, a decision of either TRUE or FALSE is achieved. In the case of TRUE, one of the two branches is explored; but in the case of FALSE condition, the other alternative is taken. Generally, the ‘IF-THEN’ is used to represent branch control. 3. Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed repeatedly based on certain loop condition e.g. WHILE, FOR loops. The symbol ‘=’ is used in most of the programming language as an assignment symbol, the same has been used in all the algorithms and flowcharts in the manual. The statement C = A + B means that add the value stored in variable A and variable B then assign/store the value in variable C. The statement R = R + 1 means that add I to the value stored in variable R and then assign/store the new value in variable R, in other words increase the value of variable R by 1 The following tables presents examples of logical operators, relational operators, mathematical operators, selection contro] statements, and loop control statements. Logical Operators Operator Example Meaning AND A>> print (message) Hello Python world! We've added a variable named message. Every variable is connected to a value, which is the information associated with that variable. In this case the value is the "Hello Python world!" text. Adding a variable makes a little more work for the Python interpreter. When it processes the first line, it associates the variable message with the "Hello Python world!" text. When it reaches the second line, it prints the value associated with message to the screen. Valid Variable Names Variable names are case-sensitive, so a variable named message is distinct from a variable named Message (note the capital M). For instance, the following code produces a NameError: >>> message = “Hello Python world!" >>> print (Message) Traceback (most recent call last): File “", line 1, in print (Message) NameError: name ‘Message’ is not defined. Did you mean: ‘message'? Variable names can be as long or as short as you like, but there are a couple of rules that you must follow. Variable names can only contain uppercase and lowercase letters (A-Z, a-z), digits (0-9), and under- scores (_). However, variable names cannot begin with a digit. For example, phrase, string1, _alp4a, and list_of_names are all valid variable names, but Slives is not. Inspect Values in the Interactive Window You have already seen how to use printQ to display a string that has been assigned to a variable. There is another way to display the value of a variable when you are working in the Python shell. Type the following into IDLE’s interactive window: >>> message = "Hello Python world!" >>> message ‘dello Python world!' Traceback (most recent call last): File "", line 1, in print (Message) NameError: name 'Message' is not defined. Did you mean: ‘message’? Variable names can be as long or as short as you like, but there are a couple of rules that you must follow. Variable names can only contain uppercase and lowercase letters (A-Z, a—z), digits (0-9), and under- scores (_). However, variable names cannot begin with a digit. For example, phrase, string1, aip4a, and list_of_names are all valid variable names, but Ylives is not. Inspect Values in the Interactive Window You have already seen how to use printQ) to display a string that has been assigned to a variable. There is another way to display the value of a variable when you are working in the Python shell. Type the following into IDLE’s interactive window: >>> message = "Hello Python world!" >>> message ‘dello Python world!' Python prints the string "Hello Python world!", and you didn’t have to type print(message)! Now type print(message), This time, when you hit Enter you see: >>> print (message) Hello Python world! Do you see the difference between this output and the output of simply typing message? It doesn’t have any single quotes surrounding it. When you type message and press Enter, you are telling Python to inspect the variable message. The output displayed is a useful representation of the value assigned to the variable. so the output is surrounded with single quotes to indicate that message is a string. On the other hand, when you printQ) a variable, Python displays a more human-readable representation of the variable’s value. For strings, both ways of being displayed are human-readable, but this is not the case for every type of value. For Example: >>>/ x=5 >>> X 2" >>> print(x) 5 >>> y="5" >>> y '5' >>> print(y) 5 ——————— Here, x is assigned to the number 5. Both the output of print(x) and inspecting x is not surrounded with quotes, because 5 is anumber and not a string. Suppose you have two variables: x = 2 and y = "2". In this case, print(x) and print(y) both display the same thing. However, inspecting x and y shows the difference between the each variable’s value. Inspecting a variable, instead of printing it, is useful for a couple of reasons. You can use it to display the value of a variable without typing printQ. The key takeaway here is that print() displays a readable representation of a variable’s value, while inspection provides additional information about the type of the value. 3.2 Numbers Humans tend to think about numbers in general terms. We view 1 and 1.0 as being the same number — one of them simply has a decimal point. However, as far as we’re concerned, the two numbers are equal and we could easily use them interchangeably. Python views them as being different kinds of numbers because each form requires a different kind of processing. Any whole number is an integer. For example, the value 1 is a whole number, so it’s an integer. On the other hand, 1.0 isn’t a whole number; it has a decimal part to it, so it’s not an integer. Any number that includes a decimal portion is a floating-point value. For example, 1.0 has a decimal part, so it’s a floating- point value. Sometimes you might want to know the variable type. Perhaps the type isn’t obvious from the code or you've received the information from a source whose code isn’t accessible. Whenever you want to see the type of a variable, use the typeQ method. For example, if you start by placing a value of 5 in myJnt by typing myJnt = 5 and pressing Enter, you can find the type of myInt by typing type(myJnt) and pressing Enter. The output will be >> float(1.65) se You can add (+), subtract (-), multiply (*), and divide (/) integers and floats in Python. >>> 141.25 aiuto >>> 55 ao >>> 9/2 4.5 >>> 70-30 40 Integer literals can be written in two different ways: >>> 100000 100000 >>> 1.00 000 100000 The % operator, or the modulus, returns the remainder of dividing the left operand by the right operand: >>> 20%7 6 >>> 5%2 The % operator, or the modulus, returns the remainder of dividing the left operand by the right operand: You can raise a number to a power using the ** operator: >>> 2**«3 8 >>> 5*«2 25 >>> 2*k-3 @.125 You can combine operators to form complex expressions. An expression is a combination of numbers, operators, and parentheses that Python can compute, or evaluate, to return a value. >>> 23-1 5 >>> 4/24+2*x3 10.0 >>> -1+(3%*2+4) 9 The * /, //, and % operators all have equal precedence, or priority, in an expression, and each of these has a higher precedence than the + and - operators. This is why 2*3 - 1 returns 5 and not 4. 2*3 is evaluated first, because * has higher precedence than the - operator. Python Assignment Operators Assignment operators are used to assign values to variables: Operator Description Example = Assigns values from right side c =a +b assigns value operands to left side operand of at+bintoc += It adds right operand to the c += ais equivalent to left operand and assign the C=cta result to left operand = It subtracts right operand c-=ais equivalent to from the left operand and c=C-a assign the result to left operand *s It multiplies right operand c “= ais equivalentto with the left operand and c=c*a assign the result to left operand [= It divides left operand with c /=ais equivalent to the right operand and assign c=c/a the result to left onerand = 3.2 Numbers It divides left operand with c/=ais equivalent to the right operand and assign c=c/a the result to left operand It takes modulus using two c %= a is equivalent operands and assign the to result to left operand c=c%Aa ae Performs exponential (power) c **= a is equivalent calculation on operators and to assign value to the left excita operand For example: >>>la = 21 >>> b = 10 >>> c = @ >>> c=atnb >>> print ("Value of c is ",c) Value of c is 31 >>> C t= a >>> print ("Value of c is ",c) Value of c is 52 >>> C *= a >>> print ("Value of c is ",c) Value of c is 1092 >>> c /=a >>> print ("Value of c is ",c) Value of c is 52.0 p>ric = 2 >>> C %= a >>> print ("Value of c is ",c) Value of cis 2 >>> C **K= a >>> print ("Value of c is ",c) Value of c is 2097152 >>> c //=a >>> print ("Value of c is ",c) Value of c is 99864 Built-in Functions Python has a few built-in functions you can use to work with numbers., you’ll learn about three of the most common ones: 1. round(), for rounding numbers to some number of decimal places >>> round(2.5) 2 >>> round(2.7) 3 >>> round(2.4) 2 >>> round(2.25463,3) 2.255 >>> round(3.14567,2) 3.15 2. abs(), for getting the absolute value of a number >>> abs(5) c = 6 >>> c=a+b >>> print ("Value of € 35 6) Value of c is 31 >>> ct+=a >>> print ("Value oT ¢ is ase) Value of c is 52 >>> c#= a >>> print ("Value oT c is - ¢) Value of c is 1092 >>> c /=a >>> print ("Value of c is *¢) Value of c is 52.0 >>> c =2 >>> c %=a >>> print ("Value oT c is * 6) Value of c is 2 >>> C k= a >>> print ("Value of c is ©. f) Value of c is 2097152 >>> c //=a >>> print ("Value of ¢ as " ¢) Value of c is 99864 Built-in Functions Python has a few built-in functions you can use to work with numbers., you'll learn about three of the most common ones: 1. roundQ, for rounding numbers to some number of decimal places >>> round(2. 5) 2 >>> round(2.7) 3 >>> round(2. 4) 2 >>> round(2.25463,3) 2.255 >>> round(3.14567,2) 3.15 2. absQ, for getting the absolute value of a number >>> abs(5) 5 >>> abs (-5) 5 3. pow@, for raising a number to some power >>> pow(2,3) 8 >>> pow(2,-3) @.125 3.3 Strings Strings are one of the fundamental Python data types. The term data type refers to what kind of data a value represents. Strings are used to represent text. The string data type has a special abbreviated name in Python: str. You can see this by using the type() function, which is used to determine the data type of a given value like this: >>> type("Hello, world") >> string3='she said "Hello, world" ' >>> string4="she said ‘Hello, World’ " >>> stringl ‘Hello world’ >>> string2 "Hi, this is my first string' >>> string3 ‘she said "Hello, world" ' >>> string4 “she said ‘Hello, World’ " After Python reads the first delimiter, all of the characters after it are considered a part of the string until a second matching delimiter is read. This is why you can use a single quote in a string delimited by double quotes and vice versa. Adding Whitespace to Strings with Tabs or Newlines In programming, whitespace refers to any nonprinting character, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it’s easier for users to read. « To add a tab to your text, use the character combination \t ¢ To add a newline in a string, use the character combination \n You can also combine tabs and newlines in a single string. The string "\n\t" tells Python to move to a new line, and start the next line with a tab. For example: >>> print('python') python >>> print('\tpython') python >>> print(‘\npython') python >>> print( ‘Languages: \npython\t\nJava') Languages: python >>> print( ‘Languages: \npython\t\nJava' ) Languages: python Java >>> print( ‘Languages: \npython\n\tJava' ) Languages: python Java Triple-quoted strings preserve whitespace. This means that running print(paragraph) displays the string on multiple lines just like it is in the string literal, including newlines. >>> print("""An example of a string that eee spans across multiple lines ase that also preserves whitespace """) An example of a string that spans across multiple lines that also preserves whitespace Using Variables in Strings In some situations, you'll want to use a variable’s value inside a string. For example, you might want two variables to represent a first name and a last name respectively, and then want to combine those values to display someone's full name: >>> first_name="John" >>> Llast_name="Smith" >>> full_name=f"{first_name}{last_name}" >>> print(full_name) JohnSmith >>> full_name=f"{first_name} {last_name}" >>> print(full_name) John Smith These strings are called fstrings. The fis for format, because Python formats the string by replacing the name of any variable in braces with its value. String Concatenation Two strings can be combined, or concatenated, using the + operator. For example: >>> first_name="John" >>> last_name="Smith" >>> full_name=first_name+last_name >>> full_name ‘JohnSmith' >>> full_name=first_name+" ‘'+last_name >>> full_name ‘John Smith' Determine the Length of a String The number of characters contained in a string, including spaces, is called the length of the string. To determine a string’s length, you use Python’s built-in lenQ) function. >>> Len("python") 6 >>> len("“python") 6 >>> name="python" >>> Len(name) 6 >>> Length=Len(name) >>> Length 6 Changing Case in a String One of the simplest tasks you can do with strings is change the case of the words in a string. For example: >>> name="hello world" >>> print(name.title() ) Hello World >>> print(name.upper() ) HELLO WORLD >>> name="Hello World" >>> print(name. lower() ) hello world In this example, the variable name refers to the lowercase string "hello world". The method titleQ appears after the variable in the print() call. A method is an action that Python can perform on a piece of data. The dot (.) after name in name.title() tells Python to make the title() method act on the variable name. « The title() method changes each word to title case, where each word begins with a capital letter. « The upper() method changes a string to all uppercase « The lower() method changes a string to all lowercase String Indexing Each character in a string has a numbered position called an index. You can access the character at the Nth position by putting the number N in between two square brackets ([ and ]) immediately after the string: >>> name="python" >>> name[@] ‘p' >>> name > Suppose you need the string containing just the first three letters of the string "python". You could access each character by index and concatenate them, or you can extract a portion of a string, called a substring, by inserting a colon between two index numbers inside of square brackets, like this: >>> first_three_letters=name [@]+name +name >>> first_three_letters "pyt' >>> name[@:3] "pyt' Determine if a String Starts or Ends With a Particular String When you work with text, sometimes you need to determine if a given string starts with or ends with certain characters. You can use two string methods to solve this problem:.startswithQ and.endswith(). [>>> job="Engineer™ [ Determine if a String Starts or Ends With a Particular String When you work with text, sometimes you need to determine if a given string starts with or ends with certain characters. You can use two string methods to solve this problem:.startswithQ) and.endswithQ). >>> job="Engineer™ >>> job.startswith("En") True >>> job.startswith("en") False >>> job.endswith("eer") True >>> job.endswith("ee") False «.startswith() method determines if the string starts with the certain letters «.endswith() method determines if the string ends with the certain letters startswithQ, and.endswith() method are case-sensitive = 3.4 Interact with User Input 3.4 Interact with User Input In this section, you will learn how to get some input from a user with the input() function. Write inputQ and press Enter, then type some text and press Enter The text you entered is repeated on a new line with single quotes. That’s because input() returns any text entered by the user as a string. >>> input() hello ‘hello’ To make input() a bit more user friendly, you can give it a prompt to display to the user. The prompt is just a string that you put in between the parentheses of input(). The input() function displays the prompt and waits for the user to type something on their keyboard. When the user hits Enter, input() returns their input as a string that can be assigned to a variable and used to do something in your program. For example: >>> prompt="Write your name" >>> user_input=input(prompt) Write your name John >>> print(“your name is",user_input) our name is John When you type a response and press Enter , your response is assigned to the user_input variable. Once you have input from a user, you can do something with it. Whatever you enter as input, input function convert it into a string. if you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting. For example: # Program to check input # type in Python num = input ("Enter number :") print (num) namel = input("Enter name : ") print (name1) # Printing type of input value print ("type of number", type(num) ) print (“type of name", type(name1)) Output: Enter number :120 120 Enter name : Mohamed Mohamed type of number We can also type cast this input to integer, float by specifying the input() function inside the type. There might be conditions when you might require integer input from user/Console, the following code takes two inputs from console and typecasts them to integer then prints the sum. # input = 3.4 Interact with User Input # Printing type of input value print ("type of number", type(num) ) print ("type of name", type(name1)) Output: Enter number :120 120 Enter name : Mohamed Mohamed type of number >> sok tua —— fa a >>>/| San5 >>> “Cat"s="Cat" True >>> “cat"=="CAT" False >>> ao a Fat Noe True >>> 5>8 False >>> 3>> age=30 >>> age==30 True >>> age>20 True >>> age>=31 False Each mathematical comparison can be used as part of an if statement, which can help you detect the exact conditions of interest. Checking Multiple Conditions = 4.1 Conditional Logic >>>) "cat"=="CAT" False >>> al a "4" True >>> 5>8 False >>> 3>> age=30 >>> age==30 Each mathematical comparison can be used as part of an if statement, which can help you detect the exact conditions of interest. Checking Multiple Conditions You may want to check multiple conditions at the same time. For example, sometimes you might need two conditions to be True to take an action. Other times you might be satisfied with just one condition being True. The keywords and and or can help you in these situations. Example 4.3 >>> age_1=20 >>> age_2=30 >>> age_1>1@ and age_2>20 True >>> age_1>10 and age_2>40@ False >>> age_1>1@ or age_2>40 True >>> age_1==10 or age_2>40 False When two statements are combined with and, the truth value of the compound statement is true if and only if both two statements are true. « Both statements are True, so the combination is also True. « Both statements are False, so their combination is also False. e Statement 1 is True, but Statement 2 is False, so their combination is False. « Statement 1 is False, but Statement 2 is True, so their combination is False. When we use the word “or” in everyday conversation, sometimes we mean an exclusive or. That is, only the first option or the second option can be true. If any part of a compound statement is True, even if the other part is False, the result is always true True. « Both statements are True, so the combination is also True. e Both statements are False, so their combination is also False. « Statement 1 is True, but Statement 2 is False, so their combination is True. « Statement 1 is False, but Statement 2 is True, so their combination is True = 42 if Statement 4.2 if Statement An if statement tells Python to only execute a portion of code if a condition is met. The simplest kind of if statement has one test and one action: if conditional_test: do something You can put any conditional test in the first line and just about any action in the indented block following the test. If the conditional test evaluates to True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement. Example 4.4: >>> age=30 >>> if age >= 20: nae print("you are ready to play") you are ready to play Example 4.5: Output1: enter the number? 6 Number is even Output 2: enter the number? 5 Example 4.6: Using “and” a>b c>as: ("Both conditions are True" Output Both conditions are True Example 4.7: Using “or” = 42 if Statement >>> age=30 >>> if age >= 20: oe print("you are ready to play") you are ready to play Example 4.5: ( ("enter the number?") ) ("Number is even") Output 1: enter the number? 6 Number is even Output 2: enter the number? 5 Example 4.6: Using “and” a>b c >a: ("Both conditions are True") Output Both conditions are True Example 4.7: Using “or” a>b be (ath ("At least one of the conditions is True") Output At least one of the conditions is True = 43 if-else Statement Nw x 4.3 if-else Statement An if-else block is similar to a simple if statement, but the else statement allows you to define an action or set of actions that are executed when the conditional test fails. >>> degree=80 >>> if degree>=75: ene print("your grade is Very Good") waa print("Thank you") your grade is Very Good Thank you The else keyword is used after an if statement in order to execute some code only if the if statement’s test condition is False. if-else structure if condition: #block of statements else: #another block of statements (else-block) Example 4.8: >>> degree=80 >>> if degree>=60: mes print("you are passed") eee else: a print("you are failed") you are passed Notice that the else keyword has no test condition, and is followed by a colon. No condition is needed, because it executes for any condition that fails the if statement’s test condition. Example 4.9: num = ("enter the number?") ) num% ("Number is See ("Number is odd...") Output 1: enter the number? 5 Number is odd... Output 2: enter the number?8 Number is even... = 44 The elif Keyword [A 4.4 The elif Keyword The elif keyword is short for “else if” and can be used to add additional conditions after an if statement. Just like if statements, elif statements have three parts: 1. The elif keyword 2. A test condition, followed by acolon 3. An indented code block that is executed if the test condition evaluates to True if expression 1: # block of statements elif expression 2: # block of statements elif expression 3: # block of statements else: # block of statements Example 4.10: The following script combines if, elif, and else to print the letter grade a student earned in a class: >>> grade=85 >>> if grade>=90: see print("You passed the class with a A.") --. Clif grade >= 80: ase print("You passed the class with a B.") --. elif grade >= 70: ees print("You passed the class with a C.") eee else: one print("You did not pass the class") You passed the class with a B. However, only the first block for which the test condition is True is executed. All remaining elif and else blocks are skipped. Let’s break down the execution of the script step-by-step: 1. grade is assigned the value 85 in the first line. 2. grade >= 90 is False, so the if statement is skipped. 3. grade >= 80 is True, so the block under the elif statement is executed, and "You passed the class with a B." is printed. 4. The elif and else statements in the followed lines are skipped Example 4.11: In this program, we check if the number is positive or negative or zero and display an appropriate message Output = 44 The elif Keyword N if expression 1: # block of statements elif expression 2: # block of statements elif expression 3: # block of statements else: # block of statements Example 4.10: The following script combines if, elif, and else to print the letter grade a student earned in a class: >>> grade=85 >>> if grade>=90: sn print("You passed the class with a A.")... elif grade >= 80: ees print("You passed the class with a B.")... elif grade >= 70: eae print("You passed the class with a C.") oee/ elses ees print("You did not pass the class") You passed the class with a B. However, only the first block for which the test condition is True is executed. All remaining elif and else blocks are skipped. Let’s break down the execution of the script step-by-step: 1. grade is assigned the value 85 in the first line. 2. grade >= 90 is False, so the if statement is skipped. 3. grade >= 80 is True, so the block under the elif statement is executed, and "You passed the class with a B." is printed. 4. The elif and else statements in the followed lines are skipped Example 4.11: In this program, we check if the number is positive or negative or zero and display an appropriate message ("Positive number") nun =—— F ("Zero") ("Negative number") Output Positive number When variable num is positive, Positive number is printed. If num is equal to 0, Zero is printed. If num is negative, Negative number is printed. = 45 Nested if Statements WN x 4.5 Nested if Statements We can have if..elif..else statement inside another if...elif..elsestatement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary. Syntax: if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here Example 4.12: smaller than 15") smaller than 12 too") greater than 12 and smaller than 15") Output i is smaller than 15 i is greater than 12 and smaller than 15 Example 4.13: In this program, we input a number check if the number is positive or negative or zero and display an appropriate message ("Enter a number: ")) ("Zero") ("Positive number") "Negative number" Output 1 Enter a number: 5 Positive number Outnut 2 = 4.5 Nested if Statements Output 2 Enter a number: -1 Negative number Output 3 Enter a number: @ Zero [Example 4.14: ("Expression value is less than 200") var ("Which is 100") var == * ("Which is 50") var < ("Expression value is less than 50") ("Could not find true expression") ("Good bye!") Output Expression value is less than 200 Which is 100 Good bye! Example 4.15: ("Enter a number: 200") ("Which is 150") Var ("Which is 100") var == : ("Which is =e) var < ("Expression value is less than 50") ("Could not find true expression") = 4.5 Nested if Statements ("Expression value is less than 50") ("Could not find true expression") ("Good bye!" ) Output 1 Enter a number: 150 Expression value is less than 200 Which is 150 Good bye! Output 2 Enter a number: 70 Expression value is less than 200 Good bye! Output 3 Enter a number: 300 Could not find true expression Good bye! Example 4.16: ("enter a number ")) > r ("Above ten,") x > ("and also above 20!") ("but not above 20.") ("less than 10!") Output 1 enter a number 20 Above ten, but not above 20. Output 2 Output 1 enter a number 20 Above ten, but not above 20. Output2 enter a number 30 Above ten, and also above 20! Output 3 enter a number 5 less than 10! Chapter Summary Chapter 4 discussed how to make decisions using conditional logic. This chapter explained how to use if-statement to control decisions. If-else statement, if-elif statement, and nested if statements w

Use Quizgecko on...
Browser
Browser