Location via proxy:
[ UP ]
[Report a bug]
[Manage cookies]
No cookies
No scripts
No ads
No referrer
Show this form
Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
100%
(1)
100% found this document useful (1 vote)
133 views
Python Programming Full-Book
Uploaded by
savaliyaneel44
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python Programming Full-Book For Later
Download
Save
Save Python Programming Full-Book For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
100%
(1)
100% found this document useful (1 vote)
133 views
Python Programming Full-Book
Uploaded by
savaliyaneel44
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python Programming Full-Book For Later
Carousel Previous
Carousel Next
Save
Save Python Programming Full-Book For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 154
Search
Fullscreen
As Per Revised Syllabus of Gujarat Technological University Jitendra Patel | Naresh A. Patel AX ATUL PRNCASHNN 2 GANDHI ROAD, AHMEDABAD. For Diploma Students Semester-1GUJARAT TECHNOLOGICAL UNIVERSITY (GTU) Competency-focused Outcome-based Green Curriculum-2021 (COGC-2021) Semester -| Course Title: Python Programming (Course Code: 4311601) [ SYTABL TEACHING AND EXAMINATION SCHEME _ | Teaching Scheme | Total Credits (im Hours) | (L#T#P/2)__ Theory Marks | Total | t[r[e C | ca ese | CA ESE | Marks 3 -[ 4 5 | 30° | 70 25 25 150 UNDERPINNING THEORY The major underpinning theory is given below based on the higher level UOs of Revised Bloom's taxonomy that are formulated for development of the COs and competency. if Fequired, more such UOs could be included by the course teacher to focus on attainment of COs and competency. Unit Unit Outcomes (UOs) ] Topics and Sub-topics (4t06 UOs at ditferent levels) | | Unit-1 [1.1 Explain steps to solve a | 1.1.1 Introduction, Steps for | problem. | problem-solving, Algorithm and Problem | 1.2 «Draw flowchart of given) its characteristics, Importance Solving Problem based on sequence, of flowchart and algorithm: using selection, repetition. 1.2.1 Symbolic representation of 2 Flowchart | 1.3 Write pseudocode for the! flowchart, Limitations of and given problems | flowchart Algorithm Flow of control | | 1.3.1 Problem solving using | | pseudocode Unit~it | 2.1 Explain the given features and | 2.1.1 Introduction to python, Python applications of python. features, Applications of python “Python | 2.2 Write steps to Install the 1 Programming Introduction latest version of python | 2.2.1 Python installation 2.3. Apply given keywords, 2.3.1 Basic structure of python | + identifiers, variables, data program, Keywords, identifiers, types, and operators in, | and variables, Data types, python programs. Operators 2.4 Write pseudocode for the) 2.4.1 Type Conversion explicit and implicit type! conversion. ee Unit- 1} 3.1. Classify control structure. 3.1.1 Introduction to Flow of Control) 3.2 Write pseudocode forthe | 3.2.1 Selection Flow of flaw of control using - If statement j Control different selection types. |- _Flif statement IV ied| Unit Unit Outcomes (UOs) Topics and Sub-topics __(4 to 6 UOs at different levels) 3.3 Write pseudocode for the Nested if statement flow of control using. 3.3.1 Repetition | different repetition types. For loop | 3.4 Implement break and continue While loop statements in the python) - Nested loop | program. 3.4.1 Break and Continue Statements IV | 4.1 Write pseudocode for user- 4.1.1 Introduction to Functions : defined functions. |= User Defined Fy-stions | Functions | 4.2 Apply Global and Local variable Arguments and Parameters concepts in python program. | 4.2.1Scope of a Variable 4.3 Use built-in functions and | Global Variable | modules. Local Variable i | 4.3.1 Python Standard Library | Built-in functions Input or output - input() , print() Mathematical Functions - abs(), | divmod(), maxi), min(), pow), | sum{) | | Module | |= math | random | | - statistics | Unit-V_| 5.1 Use of string operations in 5.1.1 Introduction to Strings, String python programs. Operations, Traversing a String Strings and | 5.2 Use built-in functions for string _ 5.2.1 Strings Methods and Built-in | sts manipulation. Functions | 5.3 Write pseudocode for list , 5.3.1 Introduction to List and its | operations. | Operations | 5.4 Use built-in functions for list 5.4.1 List Methods and Built-in | manipulation Functions | - Nested and Copying Lists i Te __| + _List as Arguments to Function ‘SUGGESTED SPECIFICATION TABLE FOR QUESTON PAPER DESIGN ~ Unit Unit Title Teaching |_ Distribution of Theory Marks No. Hours R u A | Total _ __| Level | Level Marks Probiem Solving using Flowchart oa 02 | 02 toa | 08 and Algorithm ee TT [introduction to Python 08 | 04 [oa [oa rr ily | Flow of Control 10 | 04 | 0a] 08 ae Vv Functions Os | ry 08 16 V_| Strings and Lists 2 | 02 [06 [10 [a8 [ ___ Total [a2 16 201 3a oaContents . UNIT 1 Flowchart and Algorithm... Definition Of Flowchart sl 1.2 Importance Of Flowchart 2 1.3. Symbols of Flowchart... 2 Flow lines 2 Terminals aed Input/Output 3 Processing 5 Decision Connector (inspection) Off-page connectors... E 1.4 Guidelines for preparing Flowchart... 1.5 Flowchart structure .. 1. Sequence ~ ... 2. Selection 3. Repetition s Controlling a Repetition Structure 1.5.1 Combining Structures 15.2. Flowchart Examples. 1.6 Limitations of using flowchart 1.7 Algorithm 1.7.1 Definition ... . 1.7.2. Characteristics of an Algorithm A : 1.7.3 Developing and writing Algorithms using Pseudo code: .. 4 1.7.4 Different patterns of algorithms... 1.7.5. Examples of Algorithm 1.7.6 Examples Using Flowchart and Algorithm 1.7.7. Advantages of Algorithm 1.7.8 Disadvantage of algorithm .. 1.7.9 Comparison of flowchart and algorithm ......0. ec 99 . Solved Questions . Exercise UNIT 2 Python Introduction 24 Introduction topython .....10 7 Python features ..... a Applications of python programming... x vi24 $ Exercise . Questions, . Program Exercise UNIT 3 Flow of Control .. 34 32 Python installation Basic structure of python program First Python Program .. Keywords Identifiers andvariables Datatypes, Operators. Type Conversion Solved Questions .... Introduction toFlow ofControl .. Selection 3.2.1 if statements 3.2.2 if-else statements... 3.2.3 elif statements .. 3.2.4. Nested if-else statements 3.2.5. elif Ladder... Repetition Forloop Whileloop Nestedloop : 3.4 Break and Continue Statements... . Solved Questions : Exercise . Questions . Program Exercise an 8 M4 40 40 47 54 56 59 59 59 61 63 67 69 a we TZ 14 76 79 81 82 82 83 41 42 NIT 4 Functions Introduction to Funetions .. ‘User Defined Functions: ‘Arguments and Parameters... Scope of a Variable... Local Variable .... Global Variable .... vu4.3. PythonStandard Library 2 ico ese 89 Built-in functions. i ee : lor Input or output - input() , print() on tenes 101 Mathematical Functions - abs(), divgrod(), max(), min(), pow(), sum() .. rveeeee 103 Module é . 2 sence etna stnysoidhiactenrarocnan 00 109 . Solved Questions... Soa rn ithe : Ls . Exercise 116 . Questions 6 : Program Exercise 116 UNIT S Strings and Lists 5.1 Introduction to Strings... 7 String Operations 118 Traversing a String .. cain 120 5.2 Strings Methods and Built-in Functions... 123 5.3 Introduction to List and its Operations eee 125 5.4 List Methods and Built-in Functions... 128 Nestedand Copying Lists 139 List as Arguments to Function ... laa ‘ Solved Questions lag . Exercise 147 * Questions 147 . Program Exercise 147 Best of Luck...... vuFlowchart and Algorithm 1.1 Definition Of Flowchart 1.2. Importance Of Flowchart 1.3. Symbols of Flowchart * Flow lines * Terminals + InpuvOutput + Processing * Decision + Connector (inspection) + Off-page connectors 1.4 Guidelines for preparing Flowchart 1.5 Flowchart structure 1. Sequence 2. Selection 3. Repetition Controlling a Repetition Structure 1.5.1 Combining Structures 1.5.2 Flowchart Examples 16 Limitations of using flowchart 1.7 Algorithm 1.7.1 Definition 1.7.2 Characteristics of an Algorithm 1.7.3 Developing and writing Algorithms using Pseudo code: 1.7.4 Different patterns of algorithms 1.7.5 Examples of Algorithm 1.7.6 Examples Using Flowchart and Algorithm 1.7.7 Advantages of Algorithm 1.7.8 Disadvantage of algorithm 1.7.9 Comparison of flowchart and algorithm © Solved Questions * O1 Rxercise "LL Definition of Flowchart : Flowchart and algorithms are the way to start working with the problems and them converting them into the program of any language. So, let's start learning flowchart and algorithm. A. flowchart is a pictorial representation of a program.A Flowchart is a graphical representation of the Process or system or the step-by-step solution of the problem, The Flowchart describes the flow of data and control in the systems. The flow is a set of the logic operations. Python Programming - (IT) / 2021712 | Python Programming Flow charts are an important tool for the improvement of processes. They help to identity the different elements of a process.Flow charts shows steps in sequential order and is used in presenting the flow of processes.Flowcharts are a means to help design a program before you start to code the program ‘The benefits of using flowcharts are as follows ‘Communication Flowcharts are better way of communicating the logic of a system, Effective analysis With the help of flowchart, problem can be analyzed in more effective way. Proper documentation Flowcharts serve as a good program documentation, which is needed for various purposes. Efficient Coding ‘The flowcharts are useful during the systems analysis and program development phase. Proper Debugging The flowchart helps in debugging process. Efficient Program Maintenance ‘The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part SS Syhnbias ot Fowehart Flowchart is a graphical representation of an algorithm. Programmers use it as a program-planning tool to solve a problem. It makes use of various symbols which are connected among them to indicate the flow of information and processing. Various symbols are used to write different instructions/operations in the flowchart. All symbols are connected among themselves to indicate the flow of information and processing. 5 Flow Lines Flow lines are indicated using arrow or lines. They are used to indicate flow of the problem. The flow line connects the various symbols. a Terminals Terminals are used to indicate beginning and end of the flowchart,Flowchart and Algorithm 3 J InpuvOutput Input ancl output are represented as a parallelogram. Program instructions that take input from input devices and display output on output devices are indicated with parallelogram in a flowchart, Examples: Get X from the user: display X. Processing steps are represented as rectangles. Processing Examples: “Add | to X"; “replace identified part”: “save changes” or similar. 7 Deci mond (rhombus). Diamond symbol Decisions (Conditions) in flowchart are represented as a di represents a decision point. Decision based operations such as yes/no question or true/false are indicated by diamond in flowchart. The arrows should always be labeled. False mw, Tre Yesnn Python Example : Check if X is Positive or Negative? Yes | Connector (Inspection) A connector (represented by a small circle) allows you to connect two flowchart segments. Connecter 4's used to show a jump from one point in the process flow to another. Connectors are usually labeled with capital letters (A, B, AA) to show matching jump points. They are useful for avoiding flow lines that cross other shapes and flow lines. Whenever flowchart becomes complex or it spreads over more ‘than one page. it is useful to use connectors to avoid any confusions. It is represented by a circle. O cs The “A” connector indicates that the second flowchart segment begins where the first segment ends | Om-Page Connectors Off-Page Connector shows continuation of a flowchart onto another page. It is important to remember to keep these connections logical in order,Howehart and Sigorithen Faget ee,” se 14 Guidelines for Preparing Flowchart Flowcharts are usually drawn using standard symbols, however. some special symbols can alo be developed when required The following are some guidelines in flewehaning 1 When drawing a proper flowchart. aff necessary requirements should be histed out in logical order 2) The flowchart should he clear neat and eacy ter follow There showkd net he any ambiguity in understanding the flowchart 3) The usual direction of the flow of a procedure or vywem ry from left to night or wp tu bottom 4) Only one flow tine should come out from a pracess sym oo + Or 3) Only one flow line should enter 4 dewsion symbol but two or three How lines, ume for each possible answer. should leave the decision symbdot >_— ©) Only one flow line 1s used in coqyunctuce with termunal symbol eaeee a 7D 8) » 10) iD Python Programming] Write within standard symbols briefly. As necessary, you can use the annotation symbol jy describe data or computational steps more clearly. This is top secret data If the flowchart becomes complex and lengthy, it is better to use connector symbols 1g reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication. Ensure that the flowchart has a logical start and finish. It is useful to test the validity of the flowchart by passing through it with a simple test data 1.5 Flowchart Structure [ 1. Sequence In this type of flow chart a series of actions are performed in sequence. There is no jump or loop. For Example : 2. Selection In this type of flow chart one of two possible actions is taken, depending on a condition result. Ne flow is determined based on the result of condition (whether true/false). A diamond indicates « yes question, If the answer to the question is yes, the flow follows one path. If the answer is no, the MOF follows another pathFlowchart and Algorithm 7 YES eal CT L_ For example : In the flowchart segment below, the question “is x < y?" is asked. If the answer is no, then process A is performed; if the answer is yes, then process B is performed. —- Process A [roses a | | momen 8 | B [ 3. Repetition A repetition structure represents part of the program that repeats. This type of structure is commonly known as a loop or iteration. | Notice the use of the diamond symbol. A loop tests a condition, and if the condition exists, it performs an action. Then it tests the condition again, If the condition still exists, the action is repeated. This continues until the condition no longer exists.8 Python Programming For example : In the flowchart segment, the question “is x < y?" is asked. If the answer is yes, then Process jg performed. The question “is x < y?" is asked again, Process A is repeated as long as x is less than y, When x is no longer less than y, the repetition stops and the structure is exited. Pera mers | YES Process A | Controtiing » Repetition Structure ‘The action performed by a repetition structure must eventually cause the loop to terminate. Otherwise, an infinite loop is created. 1 YES Display x In this flowchart segment, x is never changed. Once the loop starts, it will never end. So our question is: How cans this flowchart is modified so it is no longer an infinite loop? Yes, by adding an action within the repetition that changes the value of x. YES Display x al Add I to x [=Flowchart aud Algorithm 1.5.1 Combining Structures This flowchart segment shows two decision structures combined. a Display “x is outside the limits” No Display “x is the limits” Display “x is within limits” ‘Test your skills What type of structure is this? [| Python Programming - (IT) / 2021 / 2(e] 1.8.2 Flowchart Examples Example 1: Guess Answer ? ee se a 5 ay ) Print “Hello, World” (C Begin Print “Hello, World” ae Print “Hello again!” ati wails iidiaaienicibeasstalFlowchart and Algorithm Lv] Example 3: 4 Print “Hello again!" 7 4 a (end } a) Example 4 : Draw a flowchart to find the sum Of first 50 natural numbers SUM = SUM +N PRINT SUM12 Example 5: Flowchart for finding out the largest of three numbers Read A, B, C mple 6 : Draw a flowchart for computing factorial N (N!) STARTFlowchart and Algorithm Example 7 : Flowchart for computing the series 1! + 2! + 3! + .....+ m! fact = fact *j r Print series result Example 8 : Flow chart to do the sum of 10 elements read from the user Start sum = sum + elements, Print sum 13[v4 Python Programming] 1.6 Limitations of using Flowchart I is difficult to draw flowchart for large and complex programs. In flowcharts there is no standard to determine the amount of detail. Difficult to reproduce the flowcharts. It is very difficult to modify the Flowchart. 1.7 Algorithm 1.7.1 Defi ion An algorithm is aset of instructions to solve a given problem. Programs = Algorithms + Data. An algorithm is division of problem into small steps. Algorithm was first developed by A\- Khwartnd the Persian astronomer and mathematician in Arabic in 825 AD. 1.7.2 Characteristics of an Algorithm Input It accept zero or more inputs Definiteness Each instruction must be clear, well-defined and precise. There should not be any ambiguity Effectiveness Each instruction must be simple and be carried out in a finite amount of time. Finiteness Algorithm should have finite sequence of instructions. That is, it should end after a fixed tm should not enter into an infinite loop Output It should produce at least one output. i : 1.7.3 Developing and writing Algorithms using Pseudo Code : Algorithms can be expressed in many kinds of notation, including natural languages, pseudo-code, flowcharts, and programming languages. Pseudo code is a term which is often used in programming and algorithm, Pseudo code : It’s simply an implementation of an algorithm in the form of annotations and informative text written in plain English. It has no syntax like any of the programming language and thus can't be compiled or interpreted by the contputer. Notations used in Pseudo code Name of algorithm This specifies problem to be solved. tFlowchart and Algorithm T 15 | Input It specifies any given data to process Step no It is an identification tag of an instruction and it is an unsigned position numbers. "2-s.hax Explanatory comments re This is for the ease of understanding the algorithms; comments can be given within the square brackets Termination sigh To indicate end of algorithm How to write a Pseudo-code? + Start by writing down the purpose of the process. + Arrange the sequence of tasks and write the pseudocode accordingly, + Write only one statement per line. + Use white space and indentation effectively. * Capitalize key commands if necessary. + Write using simple terminology + Keep your preudocode in the proper order + Use standard programming structures + Organize your pseudocode sections. 1.7.4 Different Patterns of Algorithms Sequential In this pattern different steps occur in a sequence Conditional In this different steps are executed based on the result of condition (whether true/false). In programming languages, a conditional pattern is implémented using degision making stalements. Iterative \ In this a task (one or more steps) is repeated more than Once. Iv programming languages, an iterative pattern is implemented using loops. An iterative construct is also known as “repetitive”. construct 1.7.5 Examples of Algorithm cP ome BE Example 1 (Sequential) : An algorithm to find sum and average of 3 numbers are. Algorithm : CalculateSum . Step 1: Start > Lu Step 2: Read A, B, C [Input 3 Numbers} & , Step 3: Sum 8 A + B + C [Find Sum}16 Python Programming | Step 4: Avg 8 Sum/3 [Find Average] Step 5: Print Sum. Avg [Output the Result] Step 6: Stop Example 2 (Decision making) : An Algorithm to find whether an entered integer number is posi negative Algorithm : CheckMagnitude Step 1: Start (Beginning of the Algorithm] ve or Step 2: Read a number A [Input the integer number] Step 3: Check A > 0 {Compare A to zero} Print “number as positive” Else Print “number as negat Step 4: Stop [End of the Algorithm) Example 3(Decision making) : Write en algorithm to find largest of two numbers Algorithm: FindMax Step 1: Start (Beginning of the Algorithm} Step 2: Read a, b [Input two numbers a, b) Step 3: Check a > b (Compare a and b} Print “a is maximum” Else Print “b is maximum” [Output the result] Step 4: Stop Example 4(Iterative): Algorithm to do the sum of 28 numbers read from the user Algorithm: AddNumbers Step 1: Start Step 2: sum = 0 Step 3: Repeat steps 3 to 5 until i
S a fee windows Close Congrats, you just i led Python on Windows! Let's now see how to run a simple code in Python Run a Code in Python You can run a code in Python via the Python IDLE A quick way to find your Python IDLE on Windows is by clicking on the Start menu. You should “then see the IDLE under “Recently added” Deen es | eer ey Deed Vet oe CUCL nam) you'll see the Shell sc Once you click on the Python IDLE.[Python Introduction [LB Python 33.0 shen File Edt Shell Debug Options Window Help Python 3.5.0 (cags/v3.3. 64 Pit (AMDES)} on wins2 Type “help, "copyright", "credits" ox "License ()" for more informact ct67E2, Oct $ 2029, 16:34:40) (MSC v.4927 | | | Click on File and then select New File (alternatively, you may use the keyboard shortcut of Ctrl+N): “| 0)" (HSC vs a9a7 | ‘se£6752, Oct § 202 woxedice™ ox “License()" for more informari32 Python Programming | You would now see the following “untitled” box, where you can type ee Python code | Lae unttied - o | File Edit Format Run Options Window Help *| | | | | For example. type/copy the command below. This command will print the famous expression of “Hello World” af tt Cok 0} print (“Hello World") This is how the syntax would look like in the “untitled” box [a vuntitier” i Run Options Window Hi v Ln: 16 Cok 0Python Introduction 33 Press F5 on your keyboard. You will then get the following message to save your code oT] | [& Save Before Run or Check X | | Source Must Be Saved | OK to Save? | | EZ ome Choose a location where the Python file will be saved on your computer. You'll also need to type a name for your file. For example, type “Test” for your file name: Ud Saves ‘ ot This PC > Desktop > Test vB Seren Test 1 citi | Fucks | mb pettop 47 $ Downloads « Documents # © Pictures ete Install Python Once you're done, press Save, and you'll then see the “Hello World” expression printed on your Python Shell: = . [& Python 3.9.0 Shell File Edit Shell Debug Options Window Help Hello World >>> 2.3 Basie Structure of Python Program > The structure Python Program consists of three files such as :a.py.bpy and c.py. The file model a.py is chosen for high level file. it is known as a simple text file of statements. ... Files b.py and c.py are modules Python Programming = (FT) / 2021 1Python Programming Standard library modules oy Im General Python Program Consists of so many text files, which contains python statements Program 1s designed as single main. high file with one or more supplement files Python Statemenis i general. the interpreter reads and executes the statements line by line i.e sequentially. In python high level file has Important path of control of your Program where you can stan your application. The library tools are also known as Module files. These tools are implemented for making collection of top-level files. High level files use tools which are defined in Module files. + Modules : Modules are having top end of code. + Standard library files : Python has large collection of modules known as standard library.it contains many modules for GUI Design, Internet and network scripting, Text design matching, Operating system Interfaces. First Python Program Let us execute programs in different modes of programming + Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the following prompt ~ Type the following text at the Python prompt and press the Enter “ >55 print “Hello, Python!” If you are running new version of Python, then you would need to use print statement wit parenthesis as in print (“Hello, Python!”);. this produces the following result “ Hello, Python ! * Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and contnis until the script is finished. When the script is finished, the interpreter is no longer nective, Let us write a simple Python program in a script. Python files have extension -py. Type following source code in a test.py fileHello, Python [Python Introduction 38 We assume that you have Python interpreter set in PATH variable Now. try to program as follows ~ File C&t Format Run Options Yindow Help peine (rHeiin, eye This produces the following result * [ Hello, Python! Python Statements Python programs are typically organized with one statement per line. In other words. each statement occupies a single line, with the end of the statement delimited by the newline character that marks the end of the line. Example : print("Welcome to python programming’) Output : Welcome to python programming Multiple Statements per Line We can also write multiple statements per line, but it 1s not a 800d practice as it reduces the readability of the code. For Example, consider the following code. Example : a= 10: b= 2:cebta Print(a); print(b); print(c) Output fo ; 20 30x Python Programming Implicit Line Continuation + Any statement containing opening parentheses (*(*), brackets (‘['), oF eurly braces ¢ { ) 18 presume, to be incomplete until all matching parentheses, brackets, and braces have been encountered For example, the nested list definition from above can be made much more readable using impligj line“continuation because of the open brackets >>> >>> as | (23.4, 5), | 16. 7, 8. 9. 10), (11, 12, 13, 14, 15}, U6, 17, 18, 19, 20), (21, 22, 23, 24, 25) >>> a (UL, 2, 3, 4, 5), (6, 7, 8, 9, 10], (11, 12, 13, 14, 15], U6, 17, 18, 19, 20}, (21, 22, 23, 24, 251] A long expression can also be continued across multiple lines by wrapping it in grouping parenthese: PEP 8 explicitly advocates using parentheses in this manner when appropriate : 7 oe >>> >>>someone_is_of_working_age = ( (person|_age >= 18 and person!_age <= 65) or (person2_age >= 18 and person2_age <= 65) or (person3_age >= 18 and person3_age <= 65) >>>someone_is_of_working_age True If you need to continue a statement across multiple lines, it is usually possible to use impli line continuation to do so. This is because parentheses. brackets, and curly braces appear so frequet! in Python syntaxPython Introduction [37] Parentheses + Expression grouping + Function call >>> >>>print( “foo’. “bar”, “baz” o) foo bar baz + Method call >>> >>> ‘abe’ center( 9,Ey b Python Programmi * Tuple definition r | >>> >r> t= ( Curly Braces * Dictionary definition >>> >>> d = { * Set definition >>> | >>> xl = ( } “foo”. *bar’, Square Brackets * List definition >>> paras [ “foo”. ‘bar’, *baz’, ‘qux’Python Introduction [39 * Indexing >>> >>>al 1 | ‘bar’ * Slicing >>> | >>>al - 12 1 bar’) * Dictionary key reference >>> >>>d[ * Comments in Python Symbols used for writing comments include Hash (#) or Triple Double Quotation marks (“""). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment. Example : 1 ‘##tH#H# This example will not print Hello World #¥##### print(Hello World’) # This is a commen{+o | Multiline Comments ™ This example will demonstrate multiple comments The following a variable contains the string “Your age’ a = ‘Your age?” The following statement prints what's insige the variable a _Print(a) Python Programminy, Keywords The following list shows the Python keywords. These are reserved words and you cannot use the as constant or variable or any other identifier names. All the Python keywords contain lowerca letters only. and exe not assert finally on break for pass ‘class from print continue | _ global raise def if return del impor | try elif in while else is with [except lambda | yield Identifiers and Variables A Python identifier is a name used to identify « variable, function, class, module or 0 object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by ze" more letters, underscores and digits (0 (0 9)Python Introduction Python does not allow punctuation characters such as @, $, and % within identifiers. Python [+] isa case sensitive programming language. Thus, name and Name are two different identifiers in Python, Python is not “statically typed”. We do not need to declare variables betore using them or declare their type A variable is created the moment we first assign a value to it. A variable is a name given to a memory location. It is the basic unit of storage in a program. + The value stored in a variable can be changed during program execution + A variable is only a name given to a memory location; all the operations done on the variable effects that memory location. A variable can have a short name (like x andy) or a more descriptive mame (age, carname, total_volume). Rules for Python variables * A variable name cannot start with a number * A variable name must start with a letter or the underscore chat +A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _) + Variable names are case-sensitive (age, Age and AGE are three different variables) Valid Variable Invalid Variable myCountry = “India” my_Country = “India” _my_Country = “India” myCountry = “India” MYCOUNTRY = “India” myCountry2 = “India” 2myCountry = “Ind my-Country = “India” my Country = “India” Example variable creation : # An integer assignment age = 41 # A floating point salary = 1234.5 # A string name = “India” print(age) Print(salary) print(name) LL Python Programming eS42 | Python Programming Output = fat 1234.5 India _ + Declare the Variable Let's see how to declare the variable and print the variable. (w declaring the var | Number = 100 # display print( Number) + Output : 100 + Variable redectaration: # declaring the var Number = 100 # display print(“Before declare: “, Number) | # re-declare the var Numbejyg. 120.3. | prinAfter re-declare:", Number) We can re-declare the python variable once we have declared the variable already. + Output : Before declare: 100 After re-declare: 120.3 Assigning a single value to multiple variables: For example : print(a) Also, Python allows assigning # single value to several vuriables simultaneously with “ operatorsPython Introduction print(b) print(c) uu Output : 10 10 10 Assigning different values to multiple variables: Python allows adding different values in a single line with “{” operators a,b, ¢ = 1, 20.2, “India” print(a) print(b) print(c) Output : 1 20.2 India DATA TYPES Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes, Following are the standard or built-in data type. of Python > Numbers > String > List > Tuple > Dictionaryaa Python Programming Python - Data Types | t / [- | Dictionary Boolean Set Se + Numbers Python supports four distinct numeric types : integers, long, float and complex numbers. In addition, Booleans are 4 subtype of plain integers. Integers or int are positive or negative whole numbers with no decimal point . Long integers have unlimited precision and floats represent real numbers and are written with a decimal point dividing the integer and fractional parts. Compl numbers have a real and imaginary part, a + bc, where a is the real part and b is the imaginary part. Example : #integer example =9999 Print(“type of x is “, type(x)) #float example ys3.14l Print(“The type of y is“. typety)) #complex example 229945} Print("The type of 2 is”, type(z)) Output : | Type of x is
The type of y 1s < class “float” > The type of 2 is < class ‘complex’ > + String A String 1s an array of characters, They are formed by a list of characters, which is really an “array of characters”. They are less useful when storing information for the computer to use. An important characteristic of each string is its length, which is the number of characters in it. There are numerous algorithms for processing strings, including for searching, sorting, comparing and transforming.Python Introduction 45 ‘Tn Python. string is a sequence of Unicode character. Unicode was introduced to include every character in all languages and bring uniformity in encoding. We can create them simply by enclosing characters in quotes. Python treats single quotes the, double qui str = “Hello World” —//double quotes str = ‘Hello World!’//u 1g single quotes Python strings are “im “Characters in a siring can be Example : Hello World” table” which means they cannot be changed after they are created. iccessed using the standard [ ] syntax and zero-based indexing. su print (str{0)) | print (str{6:11]) | print (str + * !!") | print (len(str)) Output : e ¥ World Hello World !! i ra + List Python List is one of the most frequently used and very versatile datatype. Lists work similarly to strings: use the len() function and square brackets [ ] to access data, with the first element at index 0. Example : weekdays = ["Monday", “Tuesday” ‘Wednesday’, “Thursday”, “Friday"] print (weekdays{0)) print (weekdays(4]) Output : Monday + Tuple A tuple is « container which holds a series of comma-separated values between parentheses. A tuple is similar to a list. Since, tuples are quite similar to lists, both of them are_used 146 Python Programming | as_well. The only the difference is thal list is_enclosed between square bracket, tuple between parenthesis and List have mutable objects whereas Tuple have immutable objects 7 Example : my_Tuple_l = (1.2,"Hello” 3.14,"world”) | print(my_Tuple_1) print(my_Tuple_1[3}) my_Tuple_2 = (5,"six”) | printimy Tupte_1 + my_Tuple_23) Output : = 1, 2, ‘Hello’, 3.14, ‘world’) 3.14 2, ‘Hello’, 3, * Dictionary Pyhton Dictionaries allow you store and retrieve related information in a way that means something both to humans and computers. Dictionaries are _non-o: a contuin “keys” and “values”. Each key is unique and the values can _be just about anything. bil usually they are string, int, or float, or a listof these_things. Like lists dictionaries can easily be changed. can be shrunk and grown ad libitum at run ume, Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists. Dictionaries belong to the builtin mapping type. Example : # Creating a Dictionarywith Integer Keys ‘world’, 5, ‘six’) Dict = {1: 1, 2: ‘For’, 3: India} print(“\nDictionary with the use of Integer Keys: “) print(Dict) Output : Dictionary with the use of Integer Keys : {1: ‘I’, 2: ‘For’, 3: ‘India’} To tell what the value type is. you can use the buil we use the type() function to display the value type : type() function. In the following examples. >>> x = 42 \ >>> print(type(x))
>>> x = ‘hi’ =IPython Introduction i faz >>> print(type(x)) |
po> x= 3.4 >>> print(type(x))
>>> x = False >>> print(type(x))
>>> + Checking for Type Equality While the type() function lets us check which type a variable contains. The is operator used for identity checking, Numeric values may compare as equal to each other using the equality test == yet _not match on their type. Consider this example: 1 pap xsl poe y = 10 >>> x y True >>> x is y False >>> In the above example, x is assigned the integer value | and y is assigned the float value 1.0. When tested using the equality match ==, the result is True. Yet when tested using the object identity operator is, the result is False since float and int are different types. + Operators Operators are used for carrying out operations on values and variables. Python has 7 types of Operators as stated below: lL Arithmetic Operator 2+ Comparison operators 34 Logical operators + Bitwise operators Ss Assignment OperatorPython Programming * Identity operators Membership operators 1) Arithmetic Operators Python programming language suppons different kinds of arithmetic operators for both integer an floating point like addition, subtraction, multiplication, division and so on. — a Subtra Operator Type L_ Definition | Ado Addition (+) |_ Addition operator Subtraction () Subtraction operator Muluplication (*) Multiphe: Division (/) |_ Division operator | Modulus (%) | ]On operator Reminder operator Floor division (//) __Divides and returns the value of the remainder. Exponentiation (**) |” Raises the left operand to the power of right y= 10 Print(’x + y =", x+y) Output: x + y = 25 print(’x = y =", x-y) Output: x = y = 5 print(‘x * y =", x*y) Output: x * y = 150 print(*x / y =", x/y) Output: x / y = 1.5 print(’x % y =". x%y) Output: x % y = 5 print(*x // y =", wy) Output: x // y= | prim(-x ™* y =", x**y) Output: x ** 576650390625on Introduction 49 [[@ Python 364 Shell - ao x File Edit Shell Debug Options Window Help Python 3.6.4 (¥3.6.4:d48eceb, Dec 19 2017, © on win32 Type "copyright", "credits" or *license()" for more information. pp> m= 1S 3) (HSC v.1900 32 bic (1 pop v= 10 p>> print (*x + y =", xy) x ty = 28 po> print(*x - y =", x-y) x-yes >>> primt('x * y =", xty) x * y = 150 >>> prin('x / y =", x/y) x/ yrs >>> print('x t y =", xty) xtyas >>> print (*x // y = ', x//y) x//y= >>> print ('x ** y= ', x**y) x ** y = 576650390625 2) Comparison Operators Comparison operators are used for companng values. It either returns True or False according to the condition. | Operators Definition Greater than (>) ‘True if left operand is greater than the nght Less than (<) True if left operand is less than the right Equal to True if both operands are equal , Not equal to True if operands are not equal , Greater than or equal to (>=) Truc if left operand is greater than or equal to the right | Less than or equal to (<=) ‘True if left operand is less than or equal to the right Example : x=8 ysis Uxpy is’x>y) Output : x > y is False Prinw'x< y is’, x
=y) Output = x >= y 1s False Print('x<= y is", x<=y) Output : x <= y is True La Python 364 Shett File _Edit_Shell_Oebug Options Window Help Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [HSC v.1900 92 bit (Intel)] on wins2 Type "copyright", "credits" or "license()" for more information. >> a=e »>> ys as >>> PEamt('x > y ist, ay) x > y is False >>> DEAME(*x < y As", xcy? x
>> PEARe('x == y ist, ay) x= y is False >>> print('x != y ist, xt=y) | x t= y is Tre >>> prime (tx >= y 4 | x >= y is False | J x >>> print ('x <= y ist, xcey) x <= y is True 3) Logical Operators Logical operators are used for performing AND, OR and NOT operations. It either retums True o False according to the condition Definitions Truc if both the operands are tue True if either of the operands is true True if operand is false a = True B = False Print(‘a and b is’, a and b) Output Print(‘a and b is’. a or b) Output : 4 or b is True prin(‘a and b is’, a not b) Output : not a is False and b is FalsePython Introduction 31 (BD Python 3.64 Shelt Seas et File Edit Shell Debug Options Window Help python 3.6.4 (¥3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC ¥.1900 32 bit (Intel)] on win32 Type “copyright”, *credic: >>> a = True >>> b= False >>> print (‘a and b is‘, a and b) a and b is False >>> print (‘a or b is', a or b) a or b is True >> print (‘not a is’, not a) not_a is False or *license()* for more information. 4) Bitwise Operators Bitwise operators operate on bits and perform bit by bit operation xox 5 Operators Definitions } & Bitwise AND | | Bitwise OR | - Bitwise NOT | * Bitwise XOR | > Bitwise right shift | << Bitwise lett shift j 5) Assignment Operator > An assignment operator is used to assign a value to a variable. Operators T Output = x=15 + x axe 5 = | REK- 1s * | years ta x=x/ 15 KEN 15 REx His ee x15 &= AEX & 15 k | | R= RIS x=x* ds >= x =x >> 1552 Python Programming —t 6) Identity Operators Python offers 2 types of identity operators i.e is and is not. Both are used to compare if two values are located on the same part of the memory. Two variables that are equal does not imply that they are identical Operators Definitions is True if the operands are identical ts not True if the operands are not identical Example : al=3 bl =3 a2 = “Python” 2 = “Python” a3 = [45,6] b3 = [4,5,6] Print(al is not b1) Output : False print(a2 is b2) Output : True print(a3 is 63) Output : False Lo Python 3.64 Shelt - a x File Edit Shell Debug Options Window Help Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.is00 32 Bit (intelll on win32 Type “copyxight", “credits” or *"license()" for more informacion. >>> alas >>> bliss >>> a2 = "Pythen” >>> b2 = "Fythen” >>> a3 = (4,5,6) >>> D3 = (4,5,6] >>> prant(al +s 2t bl) False >>> print (a2 =5 b2) True >>> print (a3 _s bB3) FalsePython Introduction 53 Here a3 und b3 are listed, interpreter allocates memory separately and even though they are equal. it returns False. 7) Membership Operators Python offers 2 types of membership operators i.¢ in und not in. Both are used to test whether a value or variable is in a sequence. [ Operators Definitions ‘True if value is found in the sequence ‘True if value is not found in the sequence Example : a = “Python operators” b= (Ix, 2¢y)} " print ("P” in a) Output : True print (“python” not in a) Output + False print (1 in b) Output : True print (“y” in b) Output : False G& Python 2.7.14 Shell - oF x File Edit Shell Debug Options Window Help Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (In tel}} om win32 Type "copyright", “credits” or "license(}" for more information. >>> a = "python operators” >>> b= Gitxt, 2ity") >>> print ("p" in a} True >>> print ("python not in a} False >>> print (1 ir b) True >>> print (ty? in b) False 1 is key and *x’ is the value in dictionary b. Hence, *y’ in b returns False. Operators Precedence ‘The following table lists all operators from highest precedence to lowest.$a {_Python Programming] Sr. No.| Operator & Description 1 | **Exponentiation (raise to the power) | 2 ~ + Complement, unary plus und minus (method names for the last two are +@ and-@) 3 “1 % I[Multiply, divide, modulo and floor division | 4 + -Addition and subtraction 5 >><
>=Comparison ‘operators | 9 Equality operators 10 “= += *= **SAssignment operators MW is is not Identity operators | 12 in not in Membership operators | 8 not or and Logical operators \ 2.4 Type Conyersion Type Conversion The process of converting the value of one data type (integer, string, flout, etc.) to another dati type is called type conversion 1. Type Conversion is the conversion of object from one data type to another data type. 2. Implicit Type Conversion is automatically performed by the Python interpreter. 3. Python avoids the loss of data in Implicit Type Conversion. 4 Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user. 5. In Type Casting, loss of data may occur as we enforce the object to a specific data type Python has two types of type conversion 1. Implicit Type Conversion 2. Explicit Type Conversion Implicit Type Conversion In Implicit type conversion, Python automatically converts one data type to another data type This process doesn’t need any user involvement, Example 1 Converting integer to float x= 10 Print(“x is of type: stype(x))Python Introduction RQ | y = 106 print("y is of type:"\type(y)) xaxty print(x) [_print(’x is of type:".typet)) Bieta Output : x is of type:
y is of type:
206 x is of type:
As we can see the type od *x” got automatically changed to the “float” type from the “integer” type. this is a simple case of Implicit type conversion in python. Explicit Type Conversion In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(), float(), str(), etc to perform explicit type conversion. This type of conversion is also called typecasting because the user casts (changes) the data type of the objects. Syntax :
(expression) Typecasting can be done by assigning the required data type function to the expression In Explicit Type Conversion in Python, the data type is manually changed by the user as per their requirement. Various form of explicit type conversion are explained below: + int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string + float(): This function is used to convert any data type to a floating-point number. Example: Explicit type conversion # Python code to demonstrate Type conversion # using int(), float(), str Integers : int(1)-# x will be I x y = int(2.8) # y will be 2 = int("3") # z will be 3 Floats : X= float(]) — # x will be 1.0 Y = float(2.8) # y will be 28—, oy Python Programsming | 7 = floa"3") #7 will be 30 w = float” ") # w will be 42 strings [x = srs) x will be y= sti?) #y wall be “2° [7 = Str3.0) #7 will be “3.0 1. Define python Python is an object-onemted. high levellanguage. imterpreted. dyaamic and mulipurpene programming language 2. Give thefeatures ofpython. J+ Easyto Use 2 + Bapressivelanguage Interpretedi anguage + Cross-platform language 5+ Free and Open Source “6 + Object-Onented language + Extensible +3. What is python interpreter? ‘The engine that transtates and runs Pythows called he Python Interpreter Theme sn Iwowaystousen immediate made and script made Thea»oe caited the Pyshon promt The imterpoeas uses the promptto indicate that it is ready for instructiome 4. What is the difference between in termediate mode and seript mode” + Inimmediate mode, you ype Python expressams i to the Python Eaterpretcr eumbon aot the interpreter immediatelyshows theresult - atively, you can write a program im afile aed ese the imterpretre to exeewer Me coment soft hefile Such afileis called « scripe Sept shave the advantage that dey oat be saved to disk. printed, and x0 on 4. What is meant by valuein python? A. value is oneof th: fundamental things—like 4 totter or 4 sumber that 2 peogram ma Pulates 5. List the standard data types in python, Python hay fivestandard data_— — — —77) Types + Numbers + Strings + Lint + Tuples * Dictionary What is meant by python numbers? Number data types store numeric values, Number objects are created when you assign a vale 0 them Python supports four different numerical types: © intcuegned integers} + lomgilongintegers, theycanalso berepresented in octal and © te halen nema) © ened (Moatongpeunireal valves) + comple escomple somber) 7. What are pytibon strings” Strings @ Python are wtenihied as a contiguous set of characters represented in ihe quotation marks Pythow all ows for cuther pairsof singleor doublequotes. Subsetsof strings can be taken using the slice operator (FJandl {) with indexes starting at 0 in the beginning of thestring and working thew way from fat the em Theplus:+ iignethesinag conatenatonoperatorandtheasterish(* pisthe repetition operator aye Hello Word” pret strfO}—# Ponts firnt character ofthe string we Ko What i a variate? Qnept themosipewertul features of a programming language is the abilityte mampulate variables Avariabie os 3 pame chat fefers to avaiue The assignment statement gives a value 1 4 variable te pooge = 314159 9. What are the rules for naming a variable? Varnable pases can be arbitearily long They can contain both letters and digits, but they have wo begia with a letter oF an under scure Although itty legal touse upper case Fetters, by convention © dont If you do, remember that cae matters. Brace and brace are different variables Presa Promramnsing oT) BAL58 Python Programming The under score character( _) can appear in a name. Eg my_name 10. What are keywords? Keywords are the reserved words in Python, We cannotuse a keyword as variable name function name or any other identifier. They are used to define the syntax and structure of the Python language In Python, key words are case sensitive. There are 33 keywords in Python. Eg False, class, finally, return 11, What are the rules for writing an identifier? * Identifiers can be a combination of letters in lower case (atoz) or upper case (A 10Z) or digits(O 109) or an underscore(_). Name slike my Class,var_l and print_this_to_screen, all are valid example. * An identifier can not start with a digit. 1 variable is invalid, but variable | is perfectly fine. Key words can not be usedas identifiers * We can not usespecial symbols like!, @, #, 5, ete. in our * identifier. Identifier can beof any length 12. What are expressions? An expression is a combination of values, variables, operators, and calls to functions. If you type an expression at the Python prompt, the in terpretere valu at esit and displays there sult: >>> +1=2 13. What is a statement? A statement is an in struction that the Python interpreter can execute. When you type a Statement on the command line, Python executes it. Statements don't produce any result. For example, = | is an assignment statement. if statement, for statement, while statement etc. are other kinds of statements, 14. What is multiline statement? In Python, end of a statement is marked by a new line character. But we can make a statement extend over multiple lines with the line continuation character(\) For example: a=] $243 4) 44546 4) 7 48 49 15. Mention the features of identity operators? is and is not are the identity operators in Python. Theyare used to check if two values (orvariables) are located on the same part of thememory. Two variable sthat are equal does not imply that they are identical.Python Introduction 59 16. Give the characteristics of membership operator? in and not in are the membership operatorsin Python. They are used to test whether a value or variable is foundina sequence (string, list, tuple, setand dictionary). In adictionary we can only test for presence of key, not the value. ‘Operator | Meaning Example in Trueif value/variable is found in thesequence | $ in x not in | Trucif value/variable isnot found in thesequence | 5 not in x Pears + Questions What is data type? List out the types of data types with example. Define Variable and mention rules for choosing names of Variable Describe the is and is not operators and type() function. Also,-discuss why Python is called as dynamic and strongly typed language Discuss the int), float(), strO, chr() and complex() type conversion functions with examples List various types of operators in Python and write any 4 types of operators. Outline with an example the assignment and bitwise operators supported in Python > Program Exercise Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. Implement the python program to calculate total and average marks based on input Write Pythonic code to solve the quadratic equation ax**2 + bx + ¢ = 0 by getting input for coefficients from the user ‘ind the area and perimeter of a circle using functions. Prompt the user for input Write a Python program which accepts the radius of a circle from the user and compute the area, Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them eeeUnit Flow of Control 3.1 Introduction toFlow ofControl 3.2 Selection 3.2.1 if statements 3.2.2 if-else statements 3.2.3 Elif statements 3.2.4 Nested if-else statements 3.2.8 Elif Ladder 3.3. Repetition Forloop Whileloop Nestedloop 3.4 Break and Continue Statements J Solved Questions J Exercise 7 Questions 1 Program Exercise The control flow of a Python program is regulated by conditional statements, loops, and function calls 3.1 Introduction to Flow of Control Python has three types of control structures: + Sequential - default mode * Selection - used for decisions and branching «Repetition - used for looping, i-c., repeating a piece of code multiple times —+ T — v Selection Iteration Sequence[ Flow of Control + Selection Selection statements allow programmers to ask questions and then, based on the result, perform different actions. Most programming languages provide two versions of this useful construct: the ifelse and the if + Iteration For iteration, Python provides a standard while statement and a very powerful for statement. The while statement repeats a body of code as long as a condition is true. + Sequential Sequential execution is when statements are executed one after another in order. You don’t need to do anything more for this to happen. 3.2 Selection Python provides four conditional statements. 3.2.1 If Statements Python if statement decides whether certain statements need to be executed or not. It checks for a given condition, if the condition is true, then the set of code present inside the “ if “ block will be executed otherwise not . syntax +f? If ( EXPRESSION == TRUE ): Block of code else: | Block of code Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true, chen the statement or program present inside the * if“ block will be executed and if the condition is false, then the statements or program present inside the “else” block will be executed. + Flow chart px statements of if block rest of the code62 Python Programming Let's see some examples of “ if “ statements. Example : 1 num = 5 ! if (num < 10): print(“Num is smaller than 10") Output : Num is smaller than 10. i] In the above example, we declared a variable called “Num’ with the value as 5 and the ~ if ~ statemen is checking whether the number is lesser than 10 or not. If the condition is true then a set of statemeng inside the if block will be executed, Example : 2457 a=7 | b=0 if (a > b): LL Prin“ greater than b”) Output : a is greater than b In the above example, we are checking the relationship between a and b using the grealer than () Operator in the if condition. If “a” is greater than “b” then we will get the above output. Example : 3 a=0 é b=7 if (b > a): print(“b is greater than a") Output ; J b is greater than a. Example : 4 a=7 b=0 if (a): print” Output : trueFlow of Control [ss | If you observe, in the above example, we are not using or evaluating any condition in the “if” statement. ‘Always remember that in any programming language, the positive integer will be treated as true value and an integer which is less than 0 or equal to O will be treated as false. Here the value of a is 7 which is positive, hence it prints true in the console output python If Statement In One Line In Python, it is permissible to write if statement in one line Syntax :/ if (condition): #Set of statements to execute if condition in true There can be multiple statements as well, you just need to separate it by a semicolon (;) Syntax 27 if (condition) : statement 1; statement 2: statement 3;...;statement 1 If the condition is true, then execute statement 1, statement 2 and so on up to statement n. In case if the condition is false then none of the statements will be executed. Example : LPY num = if (num > 0): print(“Numiber is greater than Zero”) Output : Number is greater than Zero Multiple Conditions In If Statements It’s not that you can only write one condition inside an “if” statement, we can also evaluate multiple conditions in an “if” statement like below. Example : 1 num! = 10 num? = 20 num3 = 30 if (num1 == 10 and num? == 20 and num3 == 30): print(“All the conditions are true”) Output : All the conditions are true 3.2.2 If-Else Statements if-else statement evaluates the Boolean expression. If the condition is TRUE then, the code present in the “ if * block will be executed otherwise the code of the “else” block will be executed Syntax : If (EXPRESSION == TRUE) Statement (Body of the block) else: Statement (Body of the block)oA Python Programming Flowchart of if-else oe. | | true & statements of if block _restofthe code (> Example : 1 | num = 5 if(num > 10) Print(“number is greater than 10°) | ee: | print(“number is less than 10") Output : f [number is less than 10. In the above example, we have declared a variable called ‘num’ with the value as 5 and in the “if” statement we are checking if the number is greater than 5 or not 3 If the number is greater than 5 then, the block of code inside the “if” block will be executed and if the condition fails then the block of code present inside the “else” block will be executed. Example : 2 a=7 b=0 | if @> by | print(“a is greater than b”) | else: | print(“b is greater than a”) Output : [is greater than b~~ Flow of Control 65 In the above code if “a” is greater than “b then the statements present inside the “if” block will be executed and the statements present inside the “else” block will be skipped. Example + 3 a=7 if (a < be print( “a is smaller than b” ) | else: print( “b is smaller than a” ) Output = b is smaller than a In the above code, “a” is smaller than “b”, hence statements present inside the “else” block will be executed and statements present inside the “if” block will be skipped. If-else Statements In One Line Syntax if (condition): #Set of statement to execute if condition 1s true else: #Set of statement to execute if condition is false Naps There can be multiple statements as well, you just need to separate it by a semicolon (:) Syntax : if (condition): statement 1; statement 2; statement 3;...:statement n clse: statement 1; statement 2; statement 3:...;statement | Example : 1 num = 7 if (num > 0): print(“Number is greater than Zero”) else : print(*Number is smaller than Zero”) Output : Number is smaller than Zero Example : 2 if (‘a’ in “fruits’): print(’Apple”); print("Orange”) | else: print(“Mango"); print("Grapes”) Output: Mango Bp Grapes Fython Progsamming - (IT) / 2021/9a Python Programming 3.2.3 Elif Statements “ In Python, we have one more conditional statement called “elif” statements. “elif” statement is used to check multiple conditions only if the given condition is false. It’s similar to an “if-else” statement and the only difference is that in “else” we will not check the condition but in “elif” we will check the condition, “elif” statements are similar to “if-else” statements but “eli™ statements evaluate multiple conditions. Syntax : if (condition) ‘#Set of statement to execute if condition is true elif (condition): ‘#Set of statements to be executed when if condition is false and elif condition is true else: ‘#Set of statement to be executed when both if and elif conditions are false Example : 1 num = 10 if (num 0): print(“Number is Zero”) elif (num > 5): print(“Number is greater than 5”) else: print("Number is smaller than 5”) Output Number is greater than $ In the above example we have declared a variable called ‘num’ with the value as 10, and in the “if” statement we are checking the condition if the condition becomes true. Then the block of code present inside the “if” condition will be executed, If the condition becomes false then it will check the “elif” condition if the condition becomes true, then @ block of code present inside the “elif” statement will be executed, If it is false then a block of code present inside the “else” statement will be executed. Example ares if (num > 0): print(“Number is positive”) elif (num < 0): print(“Number is negative”) else: print(“Number is Zero”)[Row of Controt 67 Output + [Number is negative In the above example, first, we are assigning the value 7 to a variable called num. The controller will come to the “if” statement and evaluate the Boolean expression num > 0 but the number is not greater than zero hence if block will be skipped. As the if condition is evaluated to false the controller will come to the “elif” statement and evaluate the Boolean expression num <0, hence in our case number is less than zero hence ‘Number is negative’ is printed. In case both the “if” and “elif” condition is evaluated to false then a set of statements present inside the “else” block will be executed Elif Statements In One Line The elif block can also be written as below. Syntax : if (condition): #Set of statement to execute if condition is true elif (condition): #Set of statement to execute if condition! is true | else: #Set of statement to execute if condition and condition! is false ‘There can be multiple statements as well; you just need to separate it by a semicolon (;) Syntax : if (condition): statement 1; statement 2; statement 3:...:statement n elif (condition): statement 1; statement 2; statement 3;...:statement n else: statement 1; statement 2; statement 3;...;statement n Example : 1 num = if (num < 0): print(“Number is smaller than Zero”) elif (num > 0): print(“Number is greater than Zero”) else: print(“Number is Zero") Output : Number is greater than Zero Example : 2 if Ca" in “fruits’): print(*Apple”); print(Orange”) elif (‘e’ in fruits’): print(*Mango”); print("Grapes”) else: print(""No fruits available”) Output = No fruits available 3.2.4 Nested if-Else Statements ) Nested “if-else” statements mean that an “if statement or “if-else” statement is present inside another if or ifelse block. Python provides this feature as well, this in turn will help us to check multiple conditions in a given program68 Python Programming and so on Nested if-else Syntax: iffcondition): | ‘#Statements to execute if condition is true if condition): #Statements to execute if Condition is true else: ‘#Statements to execute if condition is false else: | | #Statements to execute if condition is false An “if statement 1s present inside another “if” statement which is present inside another “if statements, Here we have included the “if-else” block inside an if block, you can also include an “if-else” block inside “else” block. Let’s look at the nested if-else statement Example: nested if-else statement score=74. | af score >= 90: | prin’) else: if score >=80:Flow of Conteot [ss] print'B") 1 cbse | if score >= 70: | print’) else: if score >= 60: print(‘D') else: | print(‘F') fax Output + 7 J 32.5 Elif Ladder /} We have seen about the “elif” statements but what is this elif ladder? As the name itself suggests & program that contains a ladder of “elif” statements or “elif” statements are structured in the form of ladder. This statement is used to test multiple expressions Syntax : if (condition): #Set of statement to execute elif (condition): #Set of statements to be executed elif (condition): #Set of statements to be executed | elif (condition): #Set of statements to be executed | else: | #Set of statement to be executed when all if and elif conditions are false |70 Python Programming Flowchart of elif ladder Test Expression ofit False Test Expression of elif False Body of if Body of elif Body of else Fig: Operation ol t..e.ele statement print(‘A’) elif score >=80: print(‘B’) elif score >= 70: print(‘C’) elif score >= 60: print(‘D") else: print(‘F') Output : c The above example describes the elif ladder. Firstly, the control enters the “if” statement and evaluates the condition if the condition is true then the set of statements present inside the if block will be executed else it will be skipped and the controller will come tu the first elif block and evaluate the condition. A’similar process will continue for all the remaining “elif” statements and in case all if and elif conditions are evaluated to false then the else block will be executed.Flow of Control n In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. We know Example : 2 a= 10 if (a): print( "The given value of a: “ ); print(a) Output : [ The given value of a: 10 In Python, statements are executed in a sequential manner i.e., if our code is made up of several lines of code, then execution will start at the first line, followed by the second, and so on.However, there will be cases where we may want a block of code to execute several times until a condition is met. Thanks to loop statements, we can do just that.Given below is a flowchart that illustrates how a loop statement works. ‘t condtion is True, erate 1 conto s False, break from oop Flowchart of a Loop Statement Based on the above diagram, a Python program will start at Start{circle}, and the execution will proceed to the condition statement [Diamond], if the condition is TRUE, then the program will execute the code block72 Python Programming Execution will proceed again to the condition statement and the same process continues each time when, the condition is TRUE. It only breaks out of the loop or stops executing the code block if the condition is FALSE, and in this case, the program will continue execution sequentially. Python has two types of Loops Loop type Description =e] for loop Is an iterator based loop, which steps through the items of iterable objects like lists, tuples, string and executes a piece of code repeatedly for a number of times, based on the number of items in that iterable object. while loop _|_Executes a block of statements repeatedly as long as the condition is TRUE. For Loop the for statement, can be used in conjunction with many of the Python collections. The for loop is zero indexed and has the following syntax. for inn 1 ‘The condition in the for loop stays TRUE only if it hasn’t iterated through all the items in the iterable object(n). Flowchart : for loop for Condition istrue for Condition is false The for statement can be used to iterate over the members of a collection, so long as the collection is? sequence. for item in [1,3,6,2.5]: print(item) Output = [ wnaweFlow of Control 73 ibe assigns the variable item to be each successive value in the list [1,3,6,2,5]. The body of the iteration is then executed. This works for any collection that is a sequence (ists, wples, and strings). ‘A common use of the for statement is to implement definite iteration over a range of values. The statement Tor item in range(3) print(item*#2) Output fo 1 4 16 will perform the print function five times. The range function will return a range object representing the sequence 0.1,2,3.4 and each value will be assigned to the variable item. This value is then squared and printed. Example 1: Print Numbers ranging from Start to End To achieve this, we will use the Python range function. This is how the flowchart will look like : fpr) Foriin the range trom stan to ond End Flowchart of for loop Python Programming - (IT) / 2021 10 .74 | Python Programming | Example: Using for loop in to print range of numbers start = int(input(‘Enter a start number:")) | end = int(input(‘Enter an end number: ‘)) for i in range(start, end+1): print(i) Output + Enter a start number: 1 Enter an end number: 4 3 4 w In the above example, we used Python range, which is @ function that returns a sequence of numbers, starting from astart number (0 by default), increments by astep (1 by default), and stops before an end number. Parameters and Values for the Python range function Parameters | Value start: ho end | 20 step C 1 (default value) So, for loop will iterate through a sequence of numbers from 1 to 4, and for each iteration, it will print the number. The iteration stops when all the numbers in the sequence have been visited. While Loop 4 The Python while loop executes a block of statements repeatedly as long as the condition is TRUE. We notice that it is a bit similar to the if statement, However. unlike the while loop, the if statement executes only once if its condition is TRUE. The while loop has the following syntax : While condition : 7 J |__expression(block of code) | Unlike the for loop, the while loop doesn’t iterate over a sequence. It uses the comparison operators and booleans for its condition
You might also like
Complete Python With Numpy and Panadas
PDF
100% (1)
Complete Python With Numpy and Panadas
269 pages
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
PDF
No ratings yet
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
5 pages
Python CheatSheet - CodeWithHarry
PDF
No ratings yet
Python CheatSheet - CodeWithHarry
23 pages
Advance Python Programming
PDF
0% (1)
Advance Python Programming
184 pages
Python Notes 2020
PDF
100% (1)
Python Notes 2020
329 pages
Functions Python
PDF
100% (1)
Functions Python
39 pages
Python Tkinter Gui Projects - Removed
PDF
No ratings yet
Python Tkinter Gui Projects - Removed
208 pages
Python Programming
PDF
No ratings yet
Python Programming
142 pages
230 Programming in Python
PDF
No ratings yet
230 Programming in Python
142 pages
35 Python Programming Exercises and Solutions - Pythonista Planet
PDF
No ratings yet
35 Python Programming Exercises and Solutions - Pythonista Planet
45 pages
Unit 1
PDF
No ratings yet
Unit 1
86 pages
Python Revision Tour
PDF
No ratings yet
Python Revision Tour
14 pages
Xii Cs Question Bank For Bright Students Chapter Wise Set-II
PDF
No ratings yet
Xii Cs Question Bank For Bright Students Chapter Wise Set-II
40 pages
Introduction To Programming With Python
PDF
100% (2)
Introduction To Programming With Python
170 pages
Python Data Types
PDF
No ratings yet
Python Data Types
56 pages
Mastering Python Design Patterns Sample Chapter
PDF
No ratings yet
Mastering Python Design Patterns Sample Chapter
25 pages
Selenium With Python
PDF
No ratings yet
Selenium With Python
23 pages
Python Data Structures Cheat Sheet
PDF
No ratings yet
Python Data Structures Cheat Sheet
10 pages
Python Workbook v1 0 en
PDF
100% (1)
Python Workbook v1 0 en
83 pages
Learn Python With Examples
PDF
100% (3)
Learn Python With Examples
92 pages
12th Phython Unit-1 PDF
PDF
No ratings yet
12th Phython Unit-1 PDF
86 pages
Python GUI Programming With Tkinter - Real Python
PDF
No ratings yet
Python GUI Programming With Tkinter - Real Python
62 pages
Chris Ford - Learn Python Programming Quickly (2021)
PDF
100% (1)
Chris Ford - Learn Python Programming Quickly (2021)
209 pages
80+ Python Coding Challenges For Beginners
PDF
No ratings yet
80+ Python Coding Challenges For Beginners
128 pages
Introduction To Programming Using Python
PDF
No ratings yet
Introduction To Programming Using Python
11 pages
Python W3school
PDF
No ratings yet
Python W3school
44 pages
ECS 32B: Winter 2019 Homework Assignment 3: Due Date: No Later Than Saturday, February 16, 9:00pm
PDF
100% (1)
ECS 32B: Winter 2019 Homework Assignment 3: Due Date: No Later Than Saturday, February 16, 9:00pm
3 pages
Python UNIT III-Part-1
PDF
No ratings yet
Python UNIT III-Part-1
34 pages
Python Question Solution
PDF
No ratings yet
Python Question Solution
11 pages
File Handling in Python
PDF
No ratings yet
File Handling in Python
1 page
Ultimate Python Guide 1721491488
PDF
No ratings yet
Ultimate Python Guide 1721491488
225 pages
Python MCQs
PDF
No ratings yet
Python MCQs
199 pages
Oop in Python Best Resources
PDF
No ratings yet
Oop in Python Best Resources
1 page
Python Basics to Advanced by Sardar Azeem (1)
PDF
No ratings yet
Python Basics to Advanced by Sardar Azeem (1)
122 pages
My Lecture in W3school1
PDF
No ratings yet
My Lecture in W3school1
185 pages
Python Programming
PDF
No ratings yet
Python Programming
41 pages
Advance Python
PDF
No ratings yet
Advance Python
202 pages
Python Practice 200+
PDF
No ratings yet
Python Practice 200+
136 pages
Python Practice Problems List
PDF
No ratings yet
Python Practice Problems List
4 pages
Zerotohero Python3 170809030243
PDF
100% (1)
Zerotohero Python3 170809030243
96 pages
Python Programming Lab Manual
PDF
No ratings yet
Python Programming Lab Manual
36 pages
Python Programming
PDF
100% (1)
Python Programming
150 pages
Python Advance Programming Course Outline
PDF
No ratings yet
Python Advance Programming Course Outline
14 pages
Python 3 Beginner's Reference Cheat Sheet: by Via
PDF
100% (1)
Python 3 Beginner's Reference Cheat Sheet: by Via
1 page
Python Tutorial
PDF
No ratings yet
Python Tutorial
60 pages
Python Essentials
PDF
No ratings yet
Python Essentials
7 pages
File Handling in Python
PDF
No ratings yet
File Handling in Python
17 pages
Python Workbook For Absolute Beginners (Part 1) (BooksRack - Net)
PDF
No ratings yet
Python Workbook For Absolute Beginners (Part 1) (BooksRack - Net)
55 pages
Modul Python 1
PDF
No ratings yet
Modul Python 1
36 pages
Python Programming Tutorials (BASIC + ADVANCE) - Learn From Scratch With Examples
PDF
100% (2)
Python Programming Tutorials (BASIC + ADVANCE) - Learn From Scratch With Examples
1,016 pages
Python Essentials Cisco Net Academy
PDF
No ratings yet
Python Essentials Cisco Net Academy
13 pages
Python Function
PDF
No ratings yet
Python Function
22 pages
Python For Education
PDF
No ratings yet
Python For Education
110 pages
Python Tuples
PDF
No ratings yet
Python Tuples
15 pages
Notes Functions in Python 2022 23
PDF
No ratings yet
Notes Functions in Python 2022 23
26 pages
O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python
PDF
No ratings yet
O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python
128 pages
GE8151 Problem Solving and Python Programming - 03 - by LearnEngineering - in
PDF
No ratings yet
GE8151 Problem Solving and Python Programming - 03 - by LearnEngineering - in
100 pages
GE3151 - Python - QB Final12-New
PDF
No ratings yet
GE3151 - Python - QB Final12-New
41 pages
GE3151- PSPP Notes All Units
PDF
No ratings yet
GE3151- PSPP Notes All Units
168 pages
PSPP UNIT 1
PDF
No ratings yet
PSPP UNIT 1
31 pages
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
Complete Python With Numpy and Panadas
PDF
Complete Python With Numpy and Panadas
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
PDF
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
Python CheatSheet - CodeWithHarry
PDF
Python CheatSheet - CodeWithHarry
Advance Python Programming
PDF
Advance Python Programming
Python Notes 2020
PDF
Python Notes 2020
Functions Python
PDF
Functions Python
Python Tkinter Gui Projects - Removed
PDF
Python Tkinter Gui Projects - Removed
Python Programming
PDF
Python Programming
230 Programming in Python
PDF
230 Programming in Python
35 Python Programming Exercises and Solutions - Pythonista Planet
PDF
35 Python Programming Exercises and Solutions - Pythonista Planet
Unit 1
PDF
Unit 1
Python Revision Tour
PDF
Python Revision Tour
Xii Cs Question Bank For Bright Students Chapter Wise Set-II
PDF
Xii Cs Question Bank For Bright Students Chapter Wise Set-II
Introduction To Programming With Python
PDF
Introduction To Programming With Python
Python Data Types
PDF
Python Data Types
Mastering Python Design Patterns Sample Chapter
PDF
Mastering Python Design Patterns Sample Chapter
Selenium With Python
PDF
Selenium With Python
Python Data Structures Cheat Sheet
PDF
Python Data Structures Cheat Sheet
Python Workbook v1 0 en
PDF
Python Workbook v1 0 en
Learn Python With Examples
PDF
Learn Python With Examples
12th Phython Unit-1 PDF
PDF
12th Phython Unit-1 PDF
Python GUI Programming With Tkinter - Real Python
PDF
Python GUI Programming With Tkinter - Real Python
Chris Ford - Learn Python Programming Quickly (2021)
PDF
Chris Ford - Learn Python Programming Quickly (2021)
80+ Python Coding Challenges For Beginners
PDF
80+ Python Coding Challenges For Beginners
Introduction To Programming Using Python
PDF
Introduction To Programming Using Python
Python W3school
PDF
Python W3school
ECS 32B: Winter 2019 Homework Assignment 3: Due Date: No Later Than Saturday, February 16, 9:00pm
PDF
ECS 32B: Winter 2019 Homework Assignment 3: Due Date: No Later Than Saturday, February 16, 9:00pm
Python UNIT III-Part-1
PDF
Python UNIT III-Part-1
Python Question Solution
PDF
Python Question Solution
File Handling in Python
PDF
File Handling in Python
Ultimate Python Guide 1721491488
PDF
Ultimate Python Guide 1721491488
Python MCQs
PDF
Python MCQs
Oop in Python Best Resources
PDF
Oop in Python Best Resources
Python Basics to Advanced by Sardar Azeem (1)
PDF
Python Basics to Advanced by Sardar Azeem (1)
My Lecture in W3school1
PDF
My Lecture in W3school1
Python Programming
PDF
Python Programming
Advance Python
PDF
Advance Python
Python Practice 200+
PDF
Python Practice 200+
Python Practice Problems List
PDF
Python Practice Problems List
Zerotohero Python3 170809030243
PDF
Zerotohero Python3 170809030243
Python Programming Lab Manual
PDF
Python Programming Lab Manual
Python Programming
PDF
Python Programming
Python Advance Programming Course Outline
PDF
Python Advance Programming Course Outline
Python 3 Beginner's Reference Cheat Sheet: by Via
PDF
Python 3 Beginner's Reference Cheat Sheet: by Via
Python Tutorial
PDF
Python Tutorial
Python Essentials
PDF
Python Essentials
File Handling in Python
PDF
File Handling in Python
Python Workbook For Absolute Beginners (Part 1) (BooksRack - Net)
PDF
Python Workbook For Absolute Beginners (Part 1) (BooksRack - Net)
Modul Python 1
PDF
Modul Python 1
Python Programming Tutorials (BASIC + ADVANCE) - Learn From Scratch With Examples
PDF
Python Programming Tutorials (BASIC + ADVANCE) - Learn From Scratch With Examples
Python Essentials Cisco Net Academy
PDF
Python Essentials Cisco Net Academy
Python Function
PDF
Python Function
Python For Education
PDF
Python For Education
Python Tuples
PDF
Python Tuples
Notes Functions in Python 2022 23
PDF
Notes Functions in Python 2022 23
O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python
PDF
O_Level_Module_3_M3_R5_Programming_&_Problem_Solving_Through_Python
GE8151 Problem Solving and Python Programming - 03 - by LearnEngineering - in
PDF
GE8151 Problem Solving and Python Programming - 03 - by LearnEngineering - in
GE3151 - Python - QB Final12-New
PDF
GE3151 - Python - QB Final12-New
GE3151- PSPP Notes All Units
PDF
GE3151- PSPP Notes All Units
PSPP UNIT 1
PDF
PSPP UNIT 1