Python Programming Languages - First Unit - RJ First Unit F.ppt PDF

Summary

This presentation provides a basic introduction to programming languages, compilers, interpreters, and an overview of Python programming language. It covers introductory topics such as data types, and functions and the history of Python and its development.

Full Transcript

WHAT IS PROGRAMMING LANGUAGE?  A programming language is a formal computer language or constructed language designed to communicate instructions to a machine, particularly a computer.  Programming languages can be used to create programs to cont...

WHAT IS PROGRAMMING LANGUAGE?  A programming language is a formal computer language or constructed language designed to communicate instructions to a machine, particularly a computer.  Programming languages can be used to create programs to control the behavior of a machine or to express algorithms. COMPILER VS INTERPRETER  An interpreter is a program that reads and executes code. This includes source code, pre-compiled code, and scripts.  Common interpreters include Perl, Python, and Ruby interpreters, which execute Perl, Python, and Ruby code respectively.  Interpreters and compilers are similar, since they both recognize and process source code.  However, a compiler does not execute the code like and interpreter does.  Instead, a compiler simply converts the source code into machine code, which can be run directly by the operating system as an executable program.  Interpreters bypass the compilation process and execute the code directly.  interpreters are commonly installed on Web servers, which allows developers to run executable scripts within their webpages. These scripts can be easily edited and saved without the need to recompile the code.  without an interpreter, the source code serves as a plain text file rather than an executable program. INTRODUCTION OF PYTHON  Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming language.  Python is easy to learn yet powerful and versatile scripting language which makes it attractive for Application Development.  Python's syntax and dynamic typing with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas.  Python supports multiple programming pattern, including object oriented programming, imperative and functional programming or procedural styles.  Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.  We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to declare an integer value in a variable.  Python makes the development and debugging fast because there is no compilation step included in python development and edit-test-debug cycle is very fast.  It is used for GUI and database programming, client- and server-side web programming, and application testing.  It is used by scientists writing applications for the world's fastest supercomputers and by children first learning to program. HISTORY OF PYTHON  Python was conceptualized by Guido Van Rossum in the late 1980s.  Rossum published the first version of Python code (0.9.0) in February 1991 at the CWI (Centrum Wiskunde & Informatica) in the Netherlands , Amsterdam.  Python is derived from ABC programming language, which is a general-purpose programming language that had been developed at the CWI.  Rossum chose the name "Python", since he was a big fan of Monty Python's Flying Circus.  Python is now maintained by a core development team at the institute, although Rossum still holds a vital role in directing its progress. PYTHON VERSIONS Release dates for the major and minor versions: Python 1.0 - January 1994  Python 1.5 - December 31, 1997  Python 1.6 - September 5, 2000 Python 2.0 - October 16, 2000  Python 2.1 - April 17, 2001  Python 2.2 - December 21, 2001  Python 2.3 - July 29, 2003  Python 2.4 - November 30, 2004  Python 2.5 - September 19, 2006  Python 2.6 - October 1, 2008  Python 2.7 - July 3, 2010 PYTHON VERSIONS Release dates for the major and minor versions:  Python 3.0 - December 3, 2008  Python 3.1 - June 27, 2009  Python 3.2 - February 20, 2011  Python 3.3 - September 29, 2012  Python 3.4 - March 16, 2014  Python 3.5 - September 13, 2015  Python 3.6- December 23,2017  Python 3.7.3- March 25, 2019  Python 3.7.4- July 8, 2019  Python 3.9.4 April 4, 2021  Python 3.10.0 January 14, 2022  Python 3.11.0 October 24,2022  Python 3.12.0 February 10,2023 PYTHON FEATURES  Easy to learn, easy to read and easy to maintain.  Portable: It can run on various hardware platforms and has the same interface on all platforms.  Extendable: You can add low-level modules to the Python interpreter.  Scalable: Python provides a good structure and support for large programs.  Python has support for an interactive mode of testing and debugging.  Python has a broad standard library cross-platform.  Everything in Python is an object: variables, functions, even code.  Every object has an ID, a type, and a value. MORE FEATURES..  Python provides interfaces to all major commercial databases.  Python supports functional and structured programming methods as well as OOP.  Python provides very high-level dynamic data types and supports dynamic type checking.  Python supports GUI applications  Python supports automatic garbage collection.  Python can be easily integrated with C, C++, and Java. INTERNAL WORKING OF PYTHON  We know that computers understand only machine code that comprises 1s and 0s.  Since computer understands only machine code, it is imperative that we should convert any program into machine code before it is submitted to the computer for execution.  For this purpose, we should take the help of a compiler.  A compiler normally converts the program source code into machine code.  The role of Python Virtual Machine (PVM) is to convert the byte code instructions into machine code so that the computer can execute those machine code instructions and display the final output.  To carry out this conversion, PVM is equipped with an interpreter.  The interpreter converts the byte code into machine code and sends that machine code to the computer processor for execution.  Since interpreter is playing the main role, often the Python Virtual Machine is also called an interpreter. The Basic Elements of Python  A Python program, sometimes called a script, is a sequence of definitions and commands.  These definitions are evaluated and the commands are executed by the Python interpreter in something called the shell.  Typically, a new shell is created whenever execution of a program begins. In most cases, a window is associated with the shell.  A command, often called a statement, instructs the interpreter to do something.  For example, the statement print 'Yankees rule!' instructs the interpreter to output the string Yankees rule! to the window associated with the shell.  The sequence of commands  print ('Yankees rule!‘)  print ('But not in Boston!' )  print ('Yankees rule,', 'but not in Boston!' )  causes the interpreter to produce the output  Yankees rule!  But not in Boston!  Yankees rule, but not in Boston!  Notice that two values were passed to print in the third statement.  The print command takes a variable number of values and prints them, separated by a space character, in the order in which they appear. Objects, Expressions, and Numerical Types  Objects are the core things that Python programs manipulate.  Every object has a type that defines the kinds of things that programs can do with objects of that type.  Python has four types of scalar objects:  int is used to represent integers. Literals of type int are written in the way we typically denote integers (e.g., -3 or 5 or 10002).  float is used to represent real numbers. Literals of type float always include a decimal point (e.g., 3.0 or 3.17 or -28.72). (It is also possible to write literals of type float using scientific notation. For example, the literal 1.6E3 stands for 1.6 * 10 , i.e., it is the same as 1600.0.) You might wonder why this type is not called real.  Within the computer, values of type float are stored in the computer as floating point numbers. This representation, which is used by all modern programming languages, has many advantages. However, under some situations it causes floating point arithmetic to behave in ways that are slightly different from arithmetic on real numbers.  bool is used to represent the Boolean values True and False.  None is a type with a single value.  The == operator is used to test whether two expressions evaluate to the same value, and the != operator is used to test whether two expressions evaluate to different values.  The symbol >>> is a shell prompt indicating that the interpreter is expecting the user to type some Python code into the shell.  The line below the line with the prompt is produced when the interpreter evaluates the Python code entered at the prompt, as illustrated by the following interaction with the interpreter:  >>> 3 + 2 5  >>> 3.0 + 2.0 5.0  >>> 3 != 2 True  The built-in Python function type can be used to find out the type of an object:  >>> type(3)   >>> type(3.0)  Variables and Assignment  Variables provide a way to associate names with objects. Consider the code.  In Python, a variable is just a name, nothing more.  An assignment statement associates the name to the left of the = symbol with the object denoted by the expression to the right of the =.  Remember this too. An object can have one, more than one, or no name associated with it.  In Python, variable names can contain uppercase and lowercase letters, digits (but they cannot start with a digit), and the special character _.  Python variable names are case-sensitive e.g., Sankul and sankul are different names.  Finally, there are a small number of reserved words (sometimes called keywords) in Python that have built-in meanings and cannot be used as variable names.  Different versions of Python have slightly different lists of reserved words.  The reserved words in Python 2.7 are and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or,pass, print, raise, return, try, with, while, and yield. (31). PYTHON KEYWORDS  Total 35 Reserved Keywords in python 3.10.2.  Python allows multiple assignment.  The statement  x, y = 2, 3  binds x to 2 and y to 3.  All of the expressions on the right-hand side of the assignment are evaluated before any bindings are changed. This is convenient since it allows you to use multiple assignment to swap the bindings of two variables.  For example, the code  x, y = 2, 3  x, y = y, x  print( 'x =', x)  print('y =', y) will print x = 3 y = 2 OPERATORS IN PYTHON  Operators in Python are special symbols used to perform operations on values or variables.  Arithmetic, Comparison, Logical, and Assignment operators are the most commonly used.  Objects and operators can be combined to form expressions, each of which evaluates to an object of some type. We will refer to this as the value of the expression.  For example, the expression 3 + 2 denotes the object 5 of type int, and the expression 3.0 + 2.0 denotes the object 5.0 of type float. ARITHMETIC OPERATORS  Arithmetic operators are used for mathematical computations like addition, subtraction, multiplication, etc.  They generally operate on numerical values and return a numerical value.  They’re also referred to as mathematical operators. Operator Description Syntax + Addition – Adds two operands. x+y Subtraction – Subtracts the right operand from – x-y the the left operand. * Multiplication – Multiplies two operands. x*y Division – Divides the left operand by the right / x/y one. Results in a float value. Integer Division – Divides the left operand by // x//y the right one. Results in an integer value. Modulus – Gives the remainder on dividing the % x%y left operand by the right one. Exponent – Raises the left operand to the power ** x**y of the right one. COMPARISON OPERATORS  Comparison operators are used for comparing two values. As an output, they return a boolean value, either True or False. Operator Description Syntax == Equal to – True if both operands are equal x==y != Not equal to – True if operands are not equal x!=y Greater than – True if the left operand is greater > x>y than the right operand. Less than – True if the left operand is less than < x= x>=y is greater than or equal to the right one. == Equal to – True if both operands are equal x==y != Not equal to – True if operands are not equal x!=y LOGICAL OPERATORS  These operators are used to perform logical and, or, and not operations.  They operate on boolean values and return a boolean value. Operator Description Syntax and Logical AND – True if both the operands are true x and y Logical OR – True if either of the operands are or x or y true not NOT – Boolean compliment of the operand not x  print(x>3 and x Signed right Shift right by pushing copies of the leftmost bit in shift from the left, and let the rightmost bits fall off A B A&B A|B A^B 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 IDLE  Typing programs directly into the shell is highly inconvenient. Most programmers prefer to use some sort of text editor that is part of an integrated development environment (IDE).  The IDE that comes as part of the standard Python installation package.  IDLE is an application, just like any other application on your computer.  Start it the same way you would start any other application, e.g., by double-clicking on an icon.  IDLE provides  a text editor with syntax highlighting, auto completion, and smart indentation,  a shell with syntax highlighting, and  an integrated debugger, which you should ignore for now.  When IDLE starts it will open a shell window into which you can type Python commands.  It will also provide you with a file menu and an edit menu (as well as some other menus, which you can safely ignore for now).  The file menu includes commands to  create a new editing window into which you can type a Python program,  open a file containing an existing Python program, and  save the contents of the current editing window into a file (with file extension.py).  The edit menu includes standard text-editing commands (e.g., copy, paste, and find) plus some commands specifically designed to make it easy to edit Python code (e.g., indent region and comment out region). Basic Syntax  Indentation is used in Python to delimit blocks. The number of spaces is variable, but all statements within the same block must be indented the same amount.  The header line for compound statements, such as if, Error! while, def, and class should be terminated with a colon ( : )  The semicolon ( ; ) is optional at the end of statement.  Printing to the Screen:  Reading Keyboard Input:  Comments  Single line:  Multiple lines:  Python files have extension.py Branching Programs  Python programming language provides following types of decision making or branching statements in Python.  if statement  An if statement consists of a boolean expression followed by one or more statements.  if else statement  An if statement can be followed by an optional else statement , which executes when the boolean expression is false.  if elif else statement (nested if statement)  You can use one if elif else statements as nested if statements in other programming languages. IF CONDITION  This statement is used to test the condition only. EXAMPLE a=int(input("enter a number : ")) if a>0: print('postive values') password = "qwerty" attempt = input("Enter password: ") if attempt == password: print("Welcome") IF ELSE CONDITION  This statement is used to test the condition.  When the condition is true, then a true statement is executed.  When the condition is false, then a false statement is executed. EXAMPLE num=int(input("enter the age : ")) if (num>18): print('you can vote') else: print('you are not eligible') mark1 = int(input("\nEnter First mark : ")) mark2 = int(input("Enter Second mark : ")) mark3 = int(input("Enter Third mark : ")) if (mark1 == mark2) and (mark2 == mark3): print("All marks are same") else: print("NOT all Three are same") PYTHON IF...ELIF...ELSE STATEMENT  The elif is short for else if. It allows us to check for multiple expressions.  If the condition for if is False, it checks the condition of the next elif block and so on.  If all the conditions are False, the body of else is executed.  Only one block among the several if...elif...else blocks is executed according to the condition.  The if block can have only one else block. But it can have multiple elif blocks. SYNTAX OF IF...ELIF...ELSE if test expression: Body of if elif test expression: Body of elif else: Body of else FLOWCHART OF IF...ELIF...ELSE EXAMPLE age=int(input('enter the age is : ')) if age = 13 and age < 20: print('Now you are officially a teenager') else: print('Welcome to the real world')  Finger exercise: Write a program that examines three variables—x, y, and z— and prints the largest odd number among them. If none of them are odd, it should print a message to that effect. Strings and Input  Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −  var1 = 'Hello World!'  var2 = "Python Programming"  Objects of type str are used to represent strings of characters.11 Literals of type str can be written using either single or double quotes, e.g., 'abc' or "abc".  The literal '123' denotes a string of characters, not the number one hundred twenty- three.  Try typing the following expressions in to the Python interpreter (remember that the >>> is a prompt, not something that you type):  >>> 'a'  >>> 3*4  >>> 3*'a'  >>> 3+4  >>> 'a'+'a'  The operator + is said to be overloaded: It has different meanings depending upon the types of the objects to which it is applied.  For example, it means addition when applied to two numbers and concatenation when applied to two strings. The operator * is also overloaded. It means what you expect it to mean when its operands are both numbers. When applied to an int and a str, it duplicates the str. For example, the expression 2*'John' has the value  'JohnJohn'. There is a logic to this. Just as the expression 3*2 is equivalent to  2+2+2, the expression 3*'a' is equivalent to 'a'+'a'+'a'.  Now try typing  >>> a  >>> 'a'*'a'  Each of these lines generates an error message.  The first line produces the message  NameError: name 'a' is not defined  Because a is not a literal of any type, the interpreter treats it as a name.  However, since that name is not bound to any object, attempting to use it causes a runtime error.  The code 'a'*'a' produces the error message  TypeError: can't multiply sequence by non-int of type 'str' Escape Characters  An escape character lets you use characters that are otherwise impossible to put into a string.  An escape character consists of a backslash (\) followed by the character you want to add to the string. (Despite consisting of two characters, it is commonly referred to as a singular escape character.)  For example, the escape character for a single quote is \'. You can use this inside a string that begins and ends with single quotes. To see how escape characters work, enter the following into the interactive shell:  >>> spam = 'Say hi to shubham\'s mother.'  Python knows that since the single quote in shubham\'s has a backslash, it is not a single quote meant to end the string value.  The escape characters \' and \" let you put single quotes and double quotes inside your strings, respectively. `  >>> print("Hello there!\nHow are you?\nI\'m doing fine.")  Hello there!  How are you?  I'm doing fine. Raw Strings  You can place an r before the beginning quotation mark of a string to make it a raw string.  A raw string completely ignores all escape characters and prints any backslash that appears in the string.  For example, type the following into the interactive shell:  >>> print(r'That is Carol\'s cat.')  That is Carol\'s cat.  Because this is a raw string, Python considers the backslash as part of the string and not as the start of an escape character.  Raw strings are helpful if you are typing string values that contain many backslashes, such as the strings used for regular expressions described in the next chapter. Multiline Strings with Triple Quotes  While you can use the \n escape character to put a newline into a string, it is often easier to use multiline strings.  A multiline string in Python begins and ends with either three single quotes or three double quotes.  Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.  Python’s indentation rules for blocks do not apply to lines inside a multiline string.  print('''Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob''') Indexing and Slicing Strings Strings use indexes and slices the same way lists do. You can think of the string 'Hello world!' as a list and each character in the string as an item with a corresponding index. ' H e l l o w o r l d ! '  0 1 2 3 4 5 6 7 8 9 10 11  The space and exclamation point are included in the character count, so 'Hello world!' is 12 characters long, from H at index 0 to ! at index 11.  >>> spam = 'Hello world!'  If you specify an index, you’ll get  >>> spam the character at that position in  'H‘ the string..  >>> spam  If you specify a range from one  'o‘ index to another, the starting  >>> spam[-1] index is included and the ending  '!' index is not.  >>> spam[0:5]  That’s why, if spam is 'Hello  'Hello' world!', spam[0:5] is 'Hello'.  >>> spam[:5]  The substring you get from  'Hello' spam[0:5] will include  >>> spam[6:] everything from spam to  'world!' spam, leaving out the space at index 5.  Note that slicing a string does not modify the original string. You can capture a slice from one variable in a separate variable.  Try typing the following into the interactive shell:  >>> spam = 'Hello world!‘  >>> fizz = spam[0:5]  >>> fizz 'Hello'  By slicing and storing the resulting substring in another variable, you can have both the whole string and the substring handy for quick, easy access. The in and not in Operators with Strings  The in and not in operators can be used with strings just like with list values.  An expression with two strings joined using in or not in will evaluate to a Boolean True or False.  Enter the following into the interactive shell:  >>> 'Hello' in 'Hello World'  True  >>> 'Hello' in 'Hello'  True  >>> 'HELLO' in 'Hello World'  False  >>> '' in 'spam'  True  >>> 'cats' not in 'cats and dogs'  False  These expressions test whether the first string (the exact string, case sensitive) can be found within the second string. upper(), lower(), isupper(), and islower() String Methods  The upper() and lower() string  Note that these methods do not methods return a new string change the string itself but return where all the letters in the new string values. original string have been  If you want to change the original converted to uppercase or string, you have to call upper() or lower-case, respectively. lower() on the string and then assign  Nonletter characters in the the new string to the variable where the original was stored. string remain unchanged.  This is why you must use spam =  Enter the following into the spam.upper() to change the string in interactive shell: spam instead of simply spam.upper().  >>> spam = 'Hello world!' (This is just like if a variable eggs  >>> spam = spam.upper() contains the value 10.  >>> spam 'HELLO  Writing eggs + 3 does not change the WORLD!' value of eggs, but eggs = eggs + 3  >>> spam = spam.lower() does.)  >>> spam 'hello world!'  The upper() and lower()  The isupper() and islower() methods will return a Boolean True value if methods are helpful if the string has at least one letter and you need to make a case- all the letters are uppercase or insensitive comparison. lowercase, respectively. Otherwise, the method returns False. Enter the The strings 'great' and following into the interactive shell, 'GREat' are not equal to and notice what each method call each other. But in the returns: following small program,  >>> spam = 'Hello world!' it does not matter  >>> spam.islower() False whether the user types  >>> spam.isupper() Great, GREAT, or   False grEAT, because the  >>> 'HELLO'.isupper() string is first converted  True to lowercase.  >>> 'abc12345'.islower()  print('How are you?')  True feeling = input()  >>> '12345'.islower() if feeling.lower() == 'great':  False print('I feel great too.')  >>> '12345'.isupper() else:  False print('I hope the rest of your day is good.') The isX String Methods  Along with islower() and isupper(), there are several string methods that have names beginning with the word is. These methods return a Boolean value that describes the nature of the string. Here are some common isX string methods:  isalpha() returns True if the string consists only of letters and is not blank.  isalnum() returns True if the string consists only of letters and numbers and is not blank.  isdecimal() returns True if the string consists only of numeric characters and is not blank.  isspace() returns True if the string consists only of spaces, tabs, and new-lines and is not blank.  istitle() returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters.  >>> 'hello'.isalpha()  True  >>> 'hello123'.isalpha()  False  >>> 'hello123'.isalnum()  True  >>> 'hello'.isalnum()  True  >>> '123'.isdecimal()  True  >>> ' '.isspace()  True  >>> 'This Is Title Case'.istitle()  True  >>> 'This Is Title Case 123'.istitle()  True  >>> 'This Is not Title Case'.istitle()  False  >>> 'This Is NOT Title Case Either'.istitle()  False The startswith() and endswith() String Methods  The startswith() and endswith() methods return True if the string value they are called on begins or ends (respectively) with the string passed to the method; otherwise, they return False. Enter the following into the interactive shell:  >>> 'Hello world!'.startswith('Hello')  True  >>> 'Hello world!'.endswith('world!')  True  >>> 'abc123'.startswith('abcdef')  False  >>> 'abc123'.endswith('12')  False  >>> 'Hello world!'.startswith('Hello world!')  True  >>> 'Hello world!'.endswith('Hello world!')  True The join() and split() String Methods  The join() method is useful when you have a list of strings that need to be joined together into a single string value.  The join() method is called on a string, gets passed a list of strings, and returns a string.  The returned string is the concatenation of each string in the passed-in list.  For example, enter the following into the interactive shell:  >>> ', '.join(['cats', 'rats', 'bats'])  'cats, rats, bats' `  >>> ' '.join(['My', 'name', 'is', 'Simon'])  'My name is Simon‘  >>> 'ABC'.join(['My', 'name', 'is', 'Simon']) 'MyABCnameABCisABCSimon'  Notice that the string join() calls on is inserted between each string of the list argument. For example, when join(['cats', 'rats', 'bats']) is called on the ', ' string, the returned string is ‘cats, rats, bats’.  The split() method does the opposite: It’s called on a string value and returns a list of strings. Enter the following into the interactive shell:  >>> 'My name is Simon'.split()  ['My', 'name', 'is', 'Simon']  The length of a string can be found using the len function.  For example,  the value of len('abc') is 3. Input  Used to get input directly from a user.  Each takes a string as an argument and displays it as a prompt in the shell. It then waits for the user to type something, followed by hitting the enter key.  For input, the input line is treated as a string and becomes the value returned by the function;  input treats the typed line as a Python expression and infers a type.  >>> name = input(“Enter your name: “)  Enter your name: George Washington Iteration  This kind of a for loop iterates over an enumeration of a set of items.  It is usually characterized by the use of an implicit or explicit iterator.  In each iteration step a loop variable is set to a value in a sequence or other data collection.  Syntax of the For Loop  the Python for loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables.  The Python for loop starts with the keyword "for" followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through.  Syntax  for iterating_var in sequence: statements(s)  If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted. Example Iterating by Sequence Index  An alternative way of iterating through each item is by index offset into the sequence itself. Following is a simple example −  fruits = ['banana', 'apple', 'mango']  for index in range(len(fruits)):  print (“Current fruit :”, fruits[index] )  print ("Good bye!" )  The len() built-in function, which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over.  # Prints out the numbers 0,1,2,3,4  for x in range(5): print (x)  for x in range(3, 6): print (x)  for x in range(3, 8, 2): print (x) Using else Statement with Loops  Python supports to have an else statement associated with a loop statement  If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.  If the else statement is used with a while loop, the else statement is executed when the condition becomes false. while Loop  A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.  Syntax  The syntax of a while loop in Python programming language is −  while expression:  statement(s)  Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.  When the condition becomes false, program control passes to the line immediately following the loop.  In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code.  Python uses indentation as its method of grouping statements.  Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. count = 0 while (count < 9): print ('The count is:', count) count=count + 1 print ("Good bye!" ) count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5" "break" and "continue" statements  break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement.  # Prints out 0,1,2,3,4 count = 0 while True: print (count) count += 1 if count >= 5: break for x in range(10): if x % 2 == 0: continue print (x) "else" clause for loops # Prints out 0,1,2,3,4 and # Prints out 1,2,3,4 then it prints "count value for i in range(1,10): reached 5" if(i%5==0): count=0 break while(count

Use Quizgecko on...
Browser
Browser