0% found this document useful (0 votes)
2 views23 pages

Review Python 1

The document provides an overview of Python programming, covering its features, execution modes, character set, tokens, operators, and data types. It emphasizes Python's simplicity, readability, and versatility as a high-level programming language. Additionally, it explains various programming concepts such as control flow statements, typecasting, and operator precedence.

Uploaded by

jenniferbeomgyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Review Python 1

The document provides an overview of Python programming, covering its features, execution modes, character set, tokens, operators, and data types. It emphasizes Python's simplicity, readability, and versatility as a high-level programming language. Additionally, it explains various programming concepts such as control flow statements, typecasting, and operator precedence.

Uploaded by

jenniferbeomgyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Review Python | Chapter Highlights PETALS) The students will be able to: @ understand the features of Python and its execution modes. @ know about the character set, tokens, operators, punctuators, delimiters, and comments in Python. © acquire knowledge about various data types used in Python 1.1. Features of Python 1.2. Execution Modes in Python 1.3 Character Set 1.4 Tokens 1.5 Operators and know how to do typecasting. 1.6 Operator Precedence @ understand expressions and errors in programs. 1.7 Punctuators and Delimiters @ know about various control flow statements and jump 18 Comments statements. va with ee a é 1.9 Data Types work with st . Seta ne ee eee ey 1.10. Mutable and Immutable Data Types LAL Typecasting Python is a general-purpose, high-level programming language. 1.12 Python Expressions. Python was developed by’ Gaidaea poe et atthe 415 crrorsin Programs fational Research Institute for Mathematics and Computer [0 | Flow Si Science in the Netherlands. Python was named after the +14 Control Flow Statements British comedy show "Monty Python's Flying Circus" ass) Jume, aes 116 Nested L Python is derived from many other languages, including") eee ‘ABC, Modula-3, Unix shell, and other scripting languages, | 17°78 : You learnt about Python in the previous grade. Let us 1.18 Built-in String Functions : first review the basics of Python programming before proceeding further. 1.1 Features of Python Python is designed to be simple, readable, and capable of handling complex problems with ease. The followir, are the different features of Python: Feature E Easy Python is simple and easy to learn and almost English-like. Simple syntax constructs help you to concentrate on the solution to the problem rather than the language itself. Basy syntax and fewer syntectical constructions make Python an expressive Expressive language. Python is a free and open source language, as you can download and install it ‘on your computer without paying any fee. It is developed under an open source license, which means that you can freely distribute copies of this software, read its source code, make changes to it, and use its modules in your programs. eee Free and Open Source ms can run on Python is a platform-independent language. Gala es as platform without making any changes to them. Python programs to Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, ae ; fs ing object orient Object Oriented Python supports multiple programming paraigns inclading 0 al cane " imperative, functional programming, and pt i oriented programming is based on objects and procedures (also known as methods or functions), Portable Extensible Extensible means to extend or expand the initial state of a Programming fanguage to build new semantics. Extensible languages allow you to either add or i ify the syntax ofthe language and associate the new syntactical constructs with logic, You can write Python code in other languages, like C or C++. Embeddable Embedding means adding functions or modules from the Python library toa program, written in another programming language, such as C or C++. This way, you can take advantage of the strengths of both the languages. Interpreted Python is an interpreted language. It uses an interpreter to convert the source code into bytecode, which can run on any platform. Extensive Library The Python library sa collection of functions that you can use in your program, K makes Python programs simple and easy. It also reduces the time that you spend on writing long Python programs. Dynamically-typed Python isa dynamical ly-typed language. It means you do not need to declare the Language type of the variables b efore their use while programming. 1.2 Execution Modes in Python In Python, there are two workin ig modes through which you can execute Python programs: interactive mode and script mode. ¢ interactive mode, you write the code next to the Python, Prompt (>>>). This modeis code or getting a quick result of a line of code. 'n contrast, if you have a block of code in Python, [i Sen ne the scape sone, Yu thts cds, yn wiles Program in a file (called a script) and save it with the ‘PY extension. The Python interpreter reads the file, executes it, and provides the desired result. 1.3 Character Set can be used to ols that are u: lowing character set: Write a source program. Avalid sed to construct words, sentences =O" 8H cao, tabs, carriage return, newline Blank space, tab space, ‘arriage return, newline, form feed » "Python has the following types of tokens: 1.4.1 Keywords Keywords are the reserved words that express a be used as ordinary identifiers. They must be spell are the different keywords in Python: special meaning to the Python interpreter. Keywords cannot led as they are defined in the Python library. The following Faise et WT ise Let's Know More None det import return] . True elif fa try Execute the following command to fend else is while lis * las except onbde with check the list of Python keywords: sre an rte ele >>> Import keyword eioss a , {continue Stabe | >>> print (keyword. kwist) " Figure 1.1: Keywor 1.4.2 Identifiers ‘An identifier is a name given to a variable, function, class, module, or any other object. It helps to identify different entities in a program. To name an identifier, there are some rules to be followed: + Anidentifier starts with a letter A to Zor ato zor an underscore (_) followed by zero or more letters and digits (0 to 9). For example, My_name, my_file, account, _age, and agel are valid identifiers. + An identifier cannot start with a digit. For example, Lage, 123, and 12add are invalid identifiers. + Python keywords cannot be used as identifiers. For example, else = 5. + You cannot use special symbols, like - !, @, #,%, etc., in the identifiers. 1.4.3 Variables ‘A variable is the name given to a memory location used by a computer program to store values. This ‘memory location contains values, like numbers, text, ete. Declaring a variable means binding it to a data type. In the following line of code, the value 50 is assigned to the variable 'a' >opa=50 1.4.4 Literals or Values In Python, literals or values represent the data items that have a constant or fixed value. Literals can be defined as data or value that is given to a variable or constant. ‘There are many types of literals/values in Python as listed below: String Literals: String literals are enclosed by either single quotation marks or double quotation marks. + Single-line String Literals: Single-line strings will end in one line only. + Multiline String Literals: If you want to add multiple lines for specifying a string, then it becomes a multiline string literal. Numeric Literals: Numeric literals are immutable. They cannot be modified once created, The following table summarises the three main types of numeric literals used in Python: int ‘Numbers can be either positive or negative. In Python, integers can be assigned to a variable. Sr opp piz ld float Floating point means real numbers with e = 734. both integer and fractional parts. They ca" >> a be positive or negative. complex ‘A complex number is a pair of real and por iz l5j ; imaginary numbers, in the form,a+bp — >p>a=1+) where 'a' denotes the real part and’'b’ sop beat 3i denotes the imaginary part. ich do not have a fractional part. Integers cay + Integer Literals: These include whole numbers, whi ¥ the + and ~ signs will be used ¢ positive or negative. To identify the sign of an integer in Python, Python, there are three types of integer literals: 0 to 9. The first digit CANMOt by + Decimal Integer Literals: A decimal integer literal contains digits 231, -76, +23, 2 are devin, 0. They can be positive numbers or negative numbers. For example, integer literals. + Octal Integer Literals: An octal integer literal contains digits 0-7. It is written by prefixing 00 belay, the number where the first digit is 0 (zero) followed by the letter ‘o'. For example, 0035 is equiva, to 29 in the decimal number system (2919 = 35,). Some more examples of octal integer literals w 0045, 0026, 00345, etc. + Hexadecimal Integer Literals: A hexadecimal integer literal contains 16 digits from 0-9 and lettes ALE The sequence of digits is preceded by 0x or OX. For example: 0x19E, 0x3C, OXEA. + Boolean Literals: There are only two Boolean literals in Python. They are True and False. In Pythen, ‘True represents the value as 1 and False represents the value as 0, +. Special Literals (None): In Python, None is a special literal, which is used to define a null variable. indicates the absence of a value. If ‘None’ is compared with anything else other than ‘None’, it will ret. False. 1.5 Operators Operators are special symbols that are used to perform some specific tasks on values or variables. The val or variables on which operations are performed using the operators are called operands. Operators further classified as Unary and Binary operators. 1.5.1 Unary Operators ‘These operators need only one operand to work with. The following are the different unary operato™! + Unary Plus . Unary Minus ~ Bitwise Complement Ifa bit is 1, it will change it to 0. Ifthe bit is 0, it will change it to 1. not Logical Negation not (True) returns False | gi * 1.5.2 Binary Operators Binary operators need two values to work with, Let us know about various types of binary operators, Arithmetic Operators Arithmetic operators are used to perform mathematical. operations like addition, subtraction, multiplication, and so on. Proper ee EggEEE eo] + ‘Adds two operands - Subtracts the right operand from the left = ‘Multiplies two operands ! Divides the left operand by the right one % Returns the remainder of the division of the left operand by the Modulus right u Provides the division result in the whole number adjusted to the Floor Division left on the number line Exponentiation second operand Relational Operators Returns the result of raising the first operand to the power of the >>>l6-3 >e> 2410 ppol2 >>>12%2, >>osil2, >ooa"4 "Output | 13 60 16 Relational operators are used to compare values. They either return True or False according to the condition. Operator ‘Name Usage > Greater than Returns True ifthe eft operand is greater than the right < Less than Returns True if the left operand is less than the right > Greater than Returns True if the left operand is greater than or orequalto equal to the right Po Less than or Returns True if left the operand is less than or equal to equal to the right Logical Operators There are three logical operators, and, or, and not. | Operator Usage and Returns True if both the operands are true or Returns True if either of the operands is true not Returns True if the operand is false (complements the operand) Equal to Returns True if both the operands are equal Not equal to Returns True if the operands are not equal Example 355305 >o>3<5 >eo34>=105 >>> 34c=105 Example >>> True and. True >>> False or ‘True >>> not True Output False ‘True False ‘True False True Output True True False } i} Assignment Operator In Python, the assignment operator ‘=’ is used to assign value to an identifier. If you say a= 2, it means thy? value 2 has been assigned to the identifier ‘a’. You can assign and perform operations simultaneous, ; Python. Such a type of assignment is called a compound assignment. For example, a-+= I can be injerpy" asa=a+ 1. The following table shows different compound statements: =) Identity Operators In Python, an identity operator is used to check whether two objects are the same or not. xample | is Returns True if two operands are identical (refer to the same object) xis True is not Returns True if two operands are not identical (do not refer to the same. object) x is not True Membership Operators A membership operator checks whether an element is present in the sequence or not. in Returns True if a value/variable is found in the sequence notin Returns True if a value/variable is not found in the sequence Bena Bitwise Operators Ree on a QI. Which type of Python tokens are these? Idert A bitwise operator isused to compare (binary) numbers a and —— © The do <= Ans. a. Keyword b. enifes © Boolean literals 4. Relational ope Q2. Determine the type of literals below. a Bitwise XOR a 19 b, 0012 c._OXFACE BS Bitwise right shift Ans. a. Decimal integer literal << Bitwise left shift b. Octal integer literal © Hexadecimal integer literal On - ao - Il Write a program to convert kilometers to miles kilometers = float(input(‘How many kilometers?: ')) ®.621371 miles = kilometers * conv_fac print(kilometers, ‘KM = ', miles,’ Miles) Write a program to perform arithmetic operations numt = float(input Output: How many kilometers?: 10 10.0 KM = 6.21371 Miles conv_fac Please Enter the First Value Number 1: ")) num2 = float(input(" Please Enter the Second Value Number 2: ")) # Add Two Numbers add = num + num2 Output: # Subtracting num2 from num Please Enter the First Value Number 1: 10 sub uml ~ num2 Please Enter the Second Value Number 2: 2 Multiply numi with num The Sum of 10.0 and 2.0 multi = num * numa The Subt 12.0 action of # Divide num by num2 div = num / num2 # Modulus of numl and num2 mod = num % num2 # Exponent of num1 and num2 0 trom 10,0 = 8.0 The Multiplication of 10.0 and 2.0 = 20.0 The Division of 10,0 and 2.0 = 5.0 ‘The Modulus of 10.0 and 2.0 = 0.0 The Exponent Value of 10.0 and 2.0 = 100.0 expo = numi ** num2 print("The Sum of ", num, " and", num2, “= ", add) print("The Subtraction of ", num2, " from", num, "=", sub) print("The Multiplication of ", num, “ and“, num2, "=", multi) Print(“The Division of “, num, "and", num2, "=", divy Print("The Modulus of ", numl, “ and “, num2, ", mod) Print("The Exponent Value of *, num, “ and", num2, * =", expo) 1.6 Operator Precedence Precedence means priority. If multiple determines the order in which they should be executed. The followi high to low for the operators in Python: 0 4X, -X, =X “11% — operators are used in a Python expression, the precedence rule ing table gives the precedence order from SRT RE "arentheses Exponentiation Unary plus, Unary minus, Bitwise NOT Multiplication, Division, Floordivision, Modulus Addition, Subtraction Bitwise shift operators Bitwise AND 4 Bitwise XOR | | Bitwise OR : Deas Relational, Identity, Membership operators | IS, IS NOT, IN, NOTIN { NOT Logical NOT | AND Logical AND OR Logical OR ebb 1.7 Punctuators and Delimiters Punctuators are symbols that are used to implement the syntax and structure of a program. These are ty tokens that indicate some specific purpose in the syntax. Commonly used punctuators in Python are: Oo NS OT. % All punctuators or special symbols act as delimiters, These are the characters or symbols that separate the values. Space, tab, comma, and colon are the most commonly used delimiters. 1.8 Comments In Python, comments are the text notes added to the the program. The interpreter and compiler will ignore code easy to understand. program to provide explanatory information abou the comments in the program. Comments make the There are two types of comments: Single-line Comments: A single-line comment starts with the hash (#) symbol. Open the script mode snd then try the below written example to understand the use of single-line comments, #this will print Hello! User print("Hello! User" Multiline Comments: You need to apply a hash(#) at the be multiline Python comment. Example: #welcome note for user beginning of code ginning of every line of code to make th fprint statement to print the welcome note print (“Hello! User, Welcome to Online Game Show") However, manually commenting each line can be a very tedious process. Another w comments is 1 use triple-quotes, The triple quotes ate also use for string formatting, Example: aay to add mati? this is multi line comment second line third line print (“Hello! User") a +” 1,9 Data Types Python's built-in (or standard) data types can be grouped into several classes as per the official Python documentation, These are number, boolean, sequence, sets, none, and mapping. Some of the data types are only available in certain versions of the language, Figure 1.2: Classification of Data Types 1.9.1. Number Data Type In Python, the number data type represents the data that has a numeric value. The numeric value can be integer, decimal, or a complex number. These values are defined as int, float, and complex, respectively. Integers: Integers are whole numbers that do not contain a decimal part. For example, 34, 56, ~65, and -12 are integers. They can have positive or negative values. There is a limit on how lengthy an integer value can be in Python. Float: Float values or floating-point numbers are real numbers. The integer part and the decimal part are separated by a decimal point. These numbers can be positive or negative. For example, 32.145, -78.0, and -11.54. Complex Numbers: It is specified as (real part) + (imaginary part) j. Example: - 2439 1.9.2 Boolean Data Type ‘The Boolean data type provides two built-in values, True and False, The truth values of an expression are stored as a Python data type called bool. True can be represented by a non-zero value 1, whereas false can be represented by 0. Example: Output: >>> print (type(True)) 1.9.3 Sequence Data Type [A sequence is an ordered collection of similar or different data elements, having the same or different data types. There are three types of sequence data types: string, list, and tuple, Let us discuss them one-by-one. {A string can be defined as a collection of one or more characters enclosed in a single quotation, String: quotation marks, Its represented by the str class. Some of the valid strings in double-quotation, or triple Python are: "xyz", "name", '$$8'. List: Lists in Python contain items of different data types. The items stored in the list are separated by @ comma (,) and are enclosed using square brackets []. A list stores elements in sequence, one after another. Syntax: clist name> = [ ‘item 1", ‘item2", ...] I iam See Example: Output: student= ['Radha’, "18", ‘XI’, ‘A'] ['Radha’, ‘18, "X1''A'] print (student) 18 print(student(1]) Tuple: A tuple is also an ordered data type like a list. It can also contain items of different elements in a tuple are separated by a comma (,) and are enclosed in parentheses () The only difference between a tuple and list is that a tuple is a read-onlk you to modify the size and value of the items of a tuple, ‘That is why, However, you can easily modify the elements in a list. That is why, Syntax: = (‘item 1', ‘item2', ...) Example: student data types. The ly data structure. 1t does not alloy known as an immutable data type, known asa mutable data type, ‘Radha’, ‘18', "X1','A’) print(student) 1.9.4 Set Data Type A set is an unordered collection of unique elements. The order o} may consist of elements of various data types. Output: (Radha, 18, 'X1,,'A’) f elements in a set is undefined, though it Syntax: = (‘item 1', ‘item2', ...) Example: = {3, 5, 1, 6, 7, ‘apple’, 5, 7} Output: print(a) {1, 3, 5, 6, 7, ‘apple’} 1.9.5 None Data Type None is a Python keyword that defines null values or no value. None is string, None is a data type. | Example: not the same as 0, False, or an empty >>> a= None >>> type(a) | A variable assigned to None in Python points to an instance of the 'None'Type' class. 1.9.6 Mapping Consider a telephone directory, Here, a phone number is associated with a Particular person, This is called mapping. A key is there to map a particular data item. In Python, a dictionai a key is mapped to its corresponding value. It isa collection of key- be of any data type and can be duplicated. However, sensitive too. The mapping or dictionary data just need to know the key to retrieve the data, ry isa mapping data type, where value pairs. Values in a dictionary can the keys of a dictionary must be unique. They are case- type is best suited when you have a large amount of data. You = {"item 1’, ‘item2', ...} {'Name': 'Madhur', "Rol1No': '15* print (d) Output: ‘Name’: Madhur’, ‘RollNo':'15 » ‘Class*: '10"} An the Co Ex bet : *” 1.10 Mutable and Immutable Data Types A mutable object can be modified after it is created, whereas immutable objects cannot be modified after their creation in Python. Consider the following examples and observe the mutable property of the list data type. Examplel: >>> 1 = ['a', 'b', 'c', ‘d"] Example2: >>> 1[2] = 4 >>> print(1) >>> print(1) Output: Output: (a,b, 'c,'d] (a,b; 4,'d'] Notice in the given examples, the list named '! has been created with the values [a, b, c, d]. However, in the statement I[2] = 4, the value stored at index 2 in the list is changed. An immutable object can never be modified after itis created, Consider int and string data types to see the immutable property of data types. Example: s = ‘Hello world!" s[1] = ‘a’ print(s) You will get an error as output that shows the string is immutable. 1.11 Typecasting ‘The process of converting the value of one data type (integer, string, float, etc.) to another is called type conversion. Python supports two types of data type conversion: + Implicit Type Conversion + Explicit Type Conversion You can convert different datatypes implicitly and explicitly by using different type conversion functions, like int(), float(), str(), ete. 1.11.1. Implicit Type Conversion Python automatically converts one data type to another. It promotes the conversion of lower data types to higher data types. Example: a=4 5.6 ‘hit [1, 2, 3] type(a) Python automatically associates variable withthe data type class type(b) when itis created. This is known as | Implicit typecasting. type(c) Example 2: Observe the conversion from string to int data type: “8 Stiga string literal, which holds a a string value ‘18 I type(n) i) eg —— Soe Beets) (thas been converted into int, which) holds integer value 23 now, st = int(st) —____— type(st) dec = 344. Print(*The value of", dec, "in other number systems is print(bin(dec), "in binary") Print(oct(dec), “in octal") ) Print(hex(dec), "in hexadecimal") Output: ‘The value of 344 in other number systems is: 0b10101 1000 in binary 00530 in octal. 0x158 in hexadecimal 1.42 Python Expressions An expression is a combinat expression and displays the assigns the result of an expre tion of operators, literals, "sult An expression appears on the righ i s t-hand ause i “Son 0 the Identifier on the lefthand side, “N® Peeause it evaluates and (aeezit9)} evaluates and produces the Product of I*b, assigns the value to area and variables. The Python interpreter evaluates the efthandside Right hand side hit #~ The evaluation of an expression produces a value, which is why expressions can appear on the right hand side of the assignment statement. In an expression, the operators of higher precedence are executed first Once those results are obtained, operators of the next precedence are executed. This process continues, until the expression is completely evaluated. Any operators of equal precedence are executed according to the operators associativity rule. Example: >>> 38 +2410 50 >>> (30 + 2) * 10 320 1.13 Errors in Programs An error in a program can be observed by an unexpected behaviour unintended by the programmer. It can also be called a bug, defect, failure, or a fault. Often, your program does not work as planned. Sometimes, it will not compile properly, or it compiles but produces the wrong output or abrupt shutdown of the application, All are examples of errors. Errors can occur at compile time or at run time, Debugging is the process of locating and fixing errors in a computer program code. The following are different types of errors: Logical Errors: Logical errors are the most difficult to debug, which give wrong or undesired output. Linking Errors: These errors occur during the linking process after compilation. For example, if you forget to import the math module in the program and you are using the math . sqrt function, then an error message will be displayed in the window. Run Time Errors: Errors can also occur during the execution of a program. Successfully compiling and linking a program does not mean that you will get the desired output. Some errors cause the shutdown of the application. The following are examples of run time errors: + Ifdivided by zero occurs. + If there is a logarithm of a negative number. +. If there is a square root of a negative integer. ‘An ordered set of instructions executed by a computer to carry out a specific task is called a program. Python is a general-purpose, high-level programming language. it was developed by Guido van Rossum in 1990. Python is a free language, as you can download and install it on your computer without paying any fee. Python uses an interpreter to convert the code and run on any platform. Interactive mode and script mode are the two program execution modes in Python. ee ee oe The interactive mode allows you to write a single-line code and execute the instruction immediately to provide the result. The script mode allows you to write multiple lines of code and run the module. ‘A character set defines the valid characters that can be used to write a source program. The smallest unit in the Python program is called a token. A Python token is also called a lexical unit. Keywords are reserved words that express a special meaning to the Python interpreter ‘An identifier is the name given to an element of a program. J.) oe ooo A literal isa value that is given to either a variable or a constant. In Python, there are numeric literals, string literals, Boolean literals, and special literals, variable s the name given to a memory location used by a computer program to store values, Astring itera is formed with a characte, letter, word, or sentence enclosed in quotes. ooo 6% 'n Python, there are two ways to specify string literals: single-line string literal and multiline string literal, An escape sequence is a sequence of characters that does not re present itsetf in declaring a string literal and character or in output but is tran slated into another character and meaning, Numeric literals contain int, float, and complex values, Boolean literals contain True and False values, Operators are tokens that trigger some specific task to Punctuators are the symbols that are used to implement the syntax and structure of the Python Program, The process of changing one data type into another data type is called typecasting, A comment in Python is text that doesn't affect the outcome of a code, It starts with the # symbol, Comments can be single-ine or multiline be performed on values or variables oOo ° An expression i @ combination of operators, literals, and variables. Debugging sth process of locating and fixing ers ina Program code. 1.14 Control Flow Statements CROGe eee Iterative Figure 1.2: Classification of Control Flow Statements 1.14.1 Sequential Statements, 1.14.2 Conditional Statements Conditional statements are desi re designed to add coy inst X = ‘ instructions in Our progra rt area Ce ee ee ee ro fabled Pine Structure of a prograne Hers tothe whitespaces gece BPE ores Hl of eiteecaray. rhe stateme, ee a OF set of instructios ndition-based used at ‘nts with the same ind, orem T tioned ao" belong to the same block a 8 are the different types of conditional statemente; + if-else * if-elif-else + nested if a - bet * ‘The following table shows the syntax and examples of conditional statements: ifstatement: It is used to decide if expression: Whether a_ certain statement or block of statements will be ‘executed on the given condition. if-else statement: It checks for the expression given with the if if expression statement(s) block Ifthe expression returns 4. true, the statements written in °S®* the if block will be executed. Statement (s) Otherwise, the else block will be executed, ifelif-esestatement:Itallows you to check multiple expressions. If theexpression is true, it executes the subsequent statements, Otherwise, it checks for the next expression given with the lif block, and so on. If all the expressions are false, the body of else is executed. if expression: block_of_code_1 elif condition_2 block_of_code_2 elif condition 3: block_of_code_3 else: block_of_code_n Nested if: An if statement inside another if statement is referred toas.a nested if. An if statement can be nested when you want to check for another expression after an expression evaluates to true. if expression: if condition: statement else: statement else: statement Ise block inside if or num = int(input ("enter any number: “)) if (num>=1) and (num <= 18): print (num, “Lies inbetween numbers 1 and 1@.") print ("This Line is not the part of if block.) num = int (input("Enter the number to check: ")) num = int (input(“Enter the number to check: ")) iF ((num% 2 )== 0): print("The number is even.") else: print("The number is odd. “) num = int(input ("enter any number: ")) 4 (num > 0 print("Number is positive.) elif (num<@): print (“Number is negative.") else: print ("Number is zero. num = float(input ("Enter a number: ")) if num >= @: if num == 9: print("Zero") else: print(“Positive nunber™) else: print ("Negative number") year = if (year % 4) if (year % 100) int(input("Enter a year: e: ») if (year % 400) == @: print("Leap year") else: print("Not a leap year") else: print (“Leap year") else: print("Not a leap year") ee Output Enter a year: 2024 Leap year 1.14.3 Iterative Statements | An iterative statement is used to repeat a block of statements or set of instructions for a specific number times until the defined condition is met. Repeating a code section is called iteration or looping, ‘There al two types of looping statements: + for loop | + while loop ‘The following table shows the syntax and examples of looping statements: for loop: It is used to iterate over the for in for items in a sequence, such as a list or : string of characters, performing the | same action on each item in the list. number in range(5): print("Welcome") # body_of loop that has a set of statements # which requires | repeated execution loop: Itis an entry-controlled while test_expression: num = 1@ loop. it executes a set of statements body of vite based on a condition. Wf the test oe) or ergs _ ine expression evaluates to true, then jcremeny yeaacr)) the body of the loop gets executed. Otherwise, the loop stops iterating and the control comes out of the int ("Le ids" body of the loop. Pe ou on ends) while nun >= 6: hum = num-1 else: Print("Out of loop and out of else") jo >quences can be using the looping statements, The rang, Enter a number: 497 temp = num 407 is an armstrong number while temp > @: digit = temp % 10 sum += digit ** 3 ‘temp //= 10 | if nu sum: Print(num,"is an armstrong number") else: Print(num,"is not an armstrong number" ) ~ 1.15 Jump Statements Jump statements allow you to change the flow of the loop. It can be used to terminate a loop, skip a part of a loop, or exit from the loop at a specific condition. There are three types of jump statements as listed below: + break + continue + pass 1.15.1 The break Statement ‘break’ is a keyword that terminates the loop and transfers control out of the while or for loop. It helps you to stop iteration in between its execution. Example: for txt in "python Language": Output: if txt == "n": P break y print (txt) t print("The end") h ° The end 1.15.2 The continue Statement ‘continue’ is a keyword, Itis used to skip the current iteration and transfers control to the top of the loop. The condition of the loop evaluates again and resumes the loop from the next iteration. Example: a-e Output: while a <5: a ata 2 if ass 3: 4 continue 2 print(a) 1.15.3 The pass Statement ‘pass! is a keyword. It is a null statement. The difference between a comment and a pass statement is that while the interpreter ignores a comment entirely, pass is not ignored. It allows you to create loops, function, etc., and you can define the body of the loop or function later, However, you cannot leave the body of the function or loop empty, In such case, the pass statement is useful. It does nothing but makes the code syntactically correct. Example: sequence = "Python" Output: for val in sequence: Out of loop pass print("Out of loop") 1.16 Nested Loops A loop inside a loop is called a nested loop. For example, you have a task to perform in 5 steps. Each step Contains three more steps to accomplish one step. This is called a loop inside a loop or nested loops. Nested loops are commonly used to print pattern and mathematical matrix operations. OE ae Example: for i in range(1, 4): for j in range(1, 3): 7 print(‘outer loop = ', i, ', inner loop = ', 4) L,innerloop =, 5 | 1, inner loop = 4 2, inner loop = | 2, inner loop = 4 outer loop = 3,, inner loop = | outer loop = 3, inner loop = 7 55555 Code: 4444 rows = 5. 333 # reverse loop 22 for i in range(rows, @, -1): 1 num = for 3 in range(o, i print(num, end = print("\n") eee Code: 21 rows = 6 321 for i in range(1, rows): 4321 for j in range(i, @, -1): 54321 print(j, end=" *) print(*") rows = 5 wane k= 2* rows -2 tee for 4 in range(rows, -1, -1); a for j in range(k, @, -1); . Print(end=" ") keked for j in range(a, i 41): Print("*", ends" ») print(™) am is th Jesigne ® Indentation refers to the whitespaces or tabs that are used to place at the beginning of a block of statements, ‘© Aniterative statement is used to repeat a block of statements or set of instructions for a specific number of times. ‘© There are two types of looping statements: for and while. © The range() function is a built-in function in the Python library. It creates a sequence of numbers. ‘© Jump statements allow you to change the flow of the loop. There are three types of Jump statements: break, continue, and pass. 1.17 String A string is a data type used in Python to represent text. It is a collection of characters or symbols. It can be enclosed using any type of quotation marks, either single, double, or triple. Strings can be single line or in multiline. The following are some valid s A= "Green", name = "Radha", mob = "123456789", rollno 5", entry = "#1" 1.17.1. String Indexing The string data type is an ordered sequence of character data. Elements of a string can be accessed by using index values. The process of storing and retrieving elements of an ordered data type using an index or key values is called indexing, Index values are numeric, either positive or negative. Observe that whitespace also holds a memory space and h The positive index starts from 0 to (last—2) - and is assigned from left to [The Negative index starts from —1 to ( and is assigned from right to left an index value EeeeaIl| Write a program to check ifa character is alphabet or digit. ch = input("Please enter your own character: ) if((ch >= ‘a! and ch <= 'z') or (ch >= ‘A* and ch <= '2")): print("The given character ", ch, “is an alphabet") elif(ch >= '@' and ch <= '9"): print("The given character ", ch, "is a digit") else: print("The given character » ch, “is not an alphabet or a digit") 1.17.2 String Concatenation String concatenation means joining two or more strings together to create a new str ing. The plus (+) operator is used to perform string concatenation. For example, one string stores boot" and another string stores “camp”, When you perform concatenation as: “boot” + "camp’, it returns "bootcamp" | 1.17.3 String Repetition ific number of times using the repetition operator (¥), 1) ¢ ar vealed the multiplication operator, which is used to multiply two numeric values and dig the el On ating iat nd mulls the sequence en numberof tines and dp on the output screen, For example, ‘welcome’ *3 returns 'welcomewelcomewelcome’, spay aySit 1.17.4 String Membership Operators Membership operators are used to test the Presence of an element in a string. There are two types o membership operators as discussed below: " operator: The membership operator ‘in’ is used to check if val the element in the sequence, then it returns True, ‘p'in ‘Apple, it returns True, lue exists in a sequence or not. Ifit find otherwise it returns False, For example, if you search fy ‘not in' operator: The ‘not in’ operator returns True ifit doe it returns False, or example, if you search for'c in ‘Apple 1.17.5 String Slicing A slice means "a part of" something, Similarly, P substring or a part ofthe string can be accessed Nats cam coptider tan jaa string, An exmraton of tha form S{m:n) returns the substring or a part ofthe String S starting with index m, and displays up to n-1 (not including the character at index n). Example: snot find the element in the sequence, otherwise it returns True. ython allows you to fetch a substr ‘ng from a string. The by using the si i Operator colon (:). S = "Honest" print(S[1:4]) Output; One 1.17.6 String Traversing ‘Traversing means visiting the characters on the Strings atleast once. The traversal starts at the beginning, selects each character, performs the operation, and continues doing so until the end This pattern of processing is called traversal. The index value, either Positive or negative, can be used to traverse the string either from left-to-right or right-to-left 1.18 Built-in String Functions The following are the different built-in string functions: len() Syntax: len(stringy fame = tis used to fi “Bill Gates" dthe length ofa given string, 1 = len(name) print(1) Output: 10 capitalize, Syntax: string. capitalize, , 5 = "yeli = "yellow" Reonverts the fist {converts th Aestlewter ofthe string toa capital Print([Link]()) Output: Yellow index() isalnum() isalpha() isdigit() Lower) upper) islower() isupper() Istrip() Pstrip() Syntax: [Link](sub[, start[, end]}) It checks whether a substring is present in the string or not, It returns the lowest index in the string where the substring is found, or -1 ifthe substring is not found. Syntax: [Link](subl, start{, end}}) It returns the index of the first character of the substring in the string, i found. Ifthe substring is not found, it gives an error. Syntax: string. isalnum( ) Itfinds the presence of alphanumeric characters (like A-Z, a-z, 0-9) in the given string. Ifat least one character is found, then it returns True, otherwise it returns False. Syntax: [Link]( ) Ik finds the letters (A-Z, a-2) in the given string only. It returns True if character(s) ofthe string is alphabet, otherwise it will return False. Syntax: str. isdigit( ) It finds the digits (0-9) in the given string only. It returns True if all the values in the string are Aigits, otherwise it returns False. Syntax: [Link]( ) It converts the characters of a given string to the Towercase. Syntax: [Link]( ) It converts the characters of a given string to uppercase, Syntax: [Link]( ) It checks whether all the characters of a given string are in lowercase or not, It returns True if all the characters are in lowercase, otherwise it returns False, Syntax: str-isupper( ) It checks whether all the characters of a given string are in uppercase or not. It returns True if all the characters are in uppercase, otherwise it returns False. Symtax: str.1strip([chars}) It trims the specified characters from the beginning of the string, By default, it trims the whitespaces, if any. Syntax: [Link]({chars]) It trims the specified characters from the end of the string, By default, it trims the whitespaces from the end, if any. s = “be happy" f= [Link]('a", ®, Len(s)) print(f) Output: 4 be happy” sindex('a', @, len(s)) print(f) Output: 4 regnum = "ACL2x4" print ([Link]()) Output: True Status = ‘Pass’ print ([Link]()) Output: True addr = “Garden avenue-37" print(addr. isdigit()) Output: False name shYan™ print ([Link]()) Output: shyan addr = "Valley View -34 " print (addr. upper()) Output: VALLEY VIEW ~34 fruit = “apple” print (fruit. islower()) Output: True fruit = "APPLE* print (Fruit. isupper()) Output: True str = “nest* print(str.1strip()) Output: nest sti estttttt” print(strerstrip(‘t")) Output: ee strip() isspace() istitle() Joint) Feplace() split() Partition() count() startswith() endswith(y Syntax: [Link]( ) ao Iteliminates characters from the string's beginning and end, By default, it removes the leading spaces. (spaces at the beginning) and trailing spaces (spaces atthe end) from the string, Syntax: strisspace() checks whether the string consists of whitespaces only. It returns True, if there are only whitespace characters in the string, otherwise it returns false Syntax: ste. istitie() Teretums ‘True if the first character of each substring. in a given string is in uppercase and rest of the characters are in lowercase. Otherwise, it returns False, Syntax: str. join(sequence) Itreturnsa tring in which thee (list, tuple, dictionary) string separator, lements of sequence have been connected by a Syntax: str. replace(old, newL, It replaces the occurrences of old cl ‘henew character(s) ofthe string, max]) aracters with Syntax: Str. split(stra"", fum=string. count(str)) {breaks upa given string atthe specified separator and returns alist of sul bstrings, It splits the ‘Striz the parameter a » start, end) Syntax: str. startswith Wchecks ifthe given str Substring or character (value, start, Syntax: Str endswith(value s = "Dream Big” print([Link]()) Output: Dream Big theme: print([Link]()) Ontput: True s="I Love India" print([Link]()) Output: True stre " Seq=("apple", “banana”, Print(str. join(seq)) Output: “orange") apple-banana-orange = "I am learning python" Print([Link]( ‘learn’, ‘us')) Output: T am using Python, txt = "welcome top Print([Link]()) Output: Cwelcomes, 4, 'ython world" ‘Oo, ‘Python’, “world'] Terguee 22" 45 a progranming language” str2 = Strpartition("isny Print(str2) Output: (Python - » ‘a programmin, language: ) ae . 5 = "Best Wee) Print(s. count Output; ee), Write a program to remove odd characters in a String, str] = input(“Enter your string: ") str2 =" ied Output: while(i <= len(str1)): Enter your string: Python Programs if(i % 2 == 0): Original string: Python Programs str2 = str2 + stri[i - 1] Final. string: yhnPorm ieieta print("Original string: ", str1) print("Final string: ", str2) zal Write a program to toggle characters case in a String. string = input("Enter your string : ") stringl = '' for i in range(len(string)): if(string[i] >= ‘a’ and string[i] <= ‘z‘): stringl = stringl + chr((ord(string[i]) ~ 32)) elif(string[i] >= ‘A’ and string[i] <= 'Z' stringl = stringl + chr((ord(string[i]) + 32)) else: string] = stringl + string[i] print("\nOriginal string = ", string) print("The given string after toggling case = Output: Enter your string : Hell0 WOrlD Original string = Hell0 worlD The given string after toggling case = hELLo woRLd » string2) ® A string is a data type used in Python to represent text. Itis a collection of characters or symbols, © The process of storing and retrieving elements of an ordered data type using index or key values is called indexing. String concatenation refers to joining two strings or joining characters one after another. ° In Python, strings or characters can be repeated for a specific number of times by using the repetition operator (*). Membership operators are used to test the presence of an element in a string, The substring or a part of the string can be accessed by using the slicing operator colon () Traversing means visiting the characters in the strings at least once. ooo Python has a wide range of built-in functions or methods that can be used with the string data type Oe

You might also like