You are on page 1of 70
726888 SSR okt | R= Taam ea aaa leln Introduction Python is a general purpose, dynamic, high level and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures. 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, makes it an ideal language for scripting and rapid application development. Python supports multiple programming pattern, — including object oriented, imperative and functional or procedural Ul O < 7:38 3B Mire ll 54% 0 webandcraPts = CHANGING TRENDS. DISTINCT DESIGNS Disadvantages Of Python Programming ah, 1, Poor Memory Efficiency fr make it simple for the developer, Python needs a lot of memory space) this can be a tad problematic if you want to develop apps where you need to optimize memory. 2. Slow Speed After the high memory usage, it’s lack of speed is one of the biggest disadvantages of Python. s it executes the code one line at a time, speed of execution often is hampered. speed is important for the project, Python III O < 3. Database Access Though it is easy to program with nythonithe database access layer is eaten cos compared to other technologies like ODBC. For enterprise apps, it’s imperative that there is hassle-free interaction of complicated legacy data, and hence it is not an ideal language for such apps. 4. Weak in Mobile Computing Python is used for backed programming due its high memory usage and slow speed, it is generally not used for frontend programming or mobile app development. 6. Runtime Errors ) The data types of variables in Python can change suddenly, as it is a dynamically typed language. A variable holding a string may contain an integer later, and this can lead to runtime errors. Python provides lots of features that are listed below. Easy to Learn and Use - Python is easy to learn and use. It is developer- friendly and high level programming language. Expressive Language - Python language is more expressive means that it is more understandable and readable. UNIQUE STYLES - Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes debugging easy and thus suitable for beginners. Cross-platform Language - Python can run equally on_ different platforms such as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a_ portable language. eo GUI Programming Support - Graphical user interfaces can be developed using Python. © Integrated - It can be easily integrated with languages like C, C++, JAVA etc. IDLE is Python’s Integrated Development and Learning Environment. It allows programmers to easily write Python code. Just like Python Shell, IDLE can be used to execute a single statement and create, modify, and execute Python porlste PROPERTIES IN YELLOW MARKED! ! DLE provides a fully-featured text editor to create Python scrip include features like syntax highlighting, autocompletion, with stepping and breakpoints features. This makes debugging easier. a Dynamic typing means that the »ct = “neck type of the variable is — “ determined only during ; runtime. | S a . For example, if you want to define an integer variable in Java, you will have to explicitly specify it in the definition. On the other hand, types in Python are determined during run-time as opposed to compile-time and thus programmers are not required to declare variables before using them in the code. Method name in Python e Use only lowercase in method names. e An underscore should separate words in a method name. e Non-public method name should begin with a single underscore. e Use two consecutive underscores at the beginning of a method name, if it needs to be mangled. Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character (_). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit. _ strings in Python are arrays of Strings can be created by enclosing characters inside a single quote or double- quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrinas. Example : a = “Hello" b= 'Java' print(a+" "+b) output of above example : Hello Java Python Strings Operators To perform operation on string, Python provides basically 3 types of Operators that are given below. * Basic Operators. * Membership Operators. e Relational Operators. 1. Basic Operators There are two types of basic operators in Strina + and *. stri="Java" str2="Notes" print(stri+str2) Python String Replication Operator (*) Replication operator uses two parameters for operation, One is the integer value and the other one is the String argument. The Replication operator is used to repeat a string number of times. The string will be repeated the number of times which is given by the integer vate.) ff or Example: LF 2. Python String Membership Operators Membership Operators are already discussed in the Operators section. Let see with context of String. There are two types of Membership operators : 1.in - "in" operator returns true if a character or the entire substring is present in the specified string, otherwise false. 2. not in - "not in" operator returns true if a character or entire substring does not exist in the specified string, otherwise false. lets see the example : ets see the example str1="JavaNotes” str2="Java" str3="Notes" str4="Users” print('Exmple of in operator ::') print(str2 in str) print(str3 in str1) print(str4 in str1) print¢) print(str2 not in str1) print(str3 not in str1) print¢str4 not in stri1) output Exmple of in operator eats True False 3. Python Relational Operators All the comparison (relational) operators i.e., (<,><=,>=,==,l=,<>) are also applicable for strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order). Example: Explanation: The ASCII value of ais 97, bis 98, cis 99 and so on. The ASCII value of Ais 65, Bis 66, C is 67 and so on. The comparison between strings are done on the basis on ASCII value. Python String Slice Notation Python String slice can be defined as a substring which is the part of the string. Therefore further substring can be obtained from a string. to. 1 example : s="Monty Python" print(s[6:10]) print(s[-12:-7]) print(s[-1: :=-1]) # print(s[2: 10: 2]) print(s[ : : -1]) # print(s[ : 5]) #f print(s[3 : ]) #1 print(s[ : ]) #cop) output : ae a) Monty nohtyP ytnoM ahs nohtyP ytnoM Monty yA alele Monty Python Numeric Type in Python consists of, e Integer e Floating Point e Complex Integer Tey These are 3 tennis balls. Not 2.9 or 31. A whole number ue. 3 y The type of numeric data that is either positive or negative whole number, falls under the Integer type. The integer type is represented as ‘int’ For Example, number = 5 age = 26 Here, number and age, both variables are of type ‘int’ or ‘Integer’ or also can be said as these variables hold ‘int’ value. Floating Point Floating-point type is also called ‘float’. These are the variables that hold real numbers and are written with a decimal point dividing the integer and fractional parts. (n sirnpe words, a number that has a decimal falls under the floating-point type. For Example, temperature = 35.6 rateOfInterest = 2.5 Python allows us to store and manipulate complex numbers. In Python, the complex number can have the following form, at+bj, where a and b are real numbers, and ‘j’ is the imaginary part. Complex numbers are not used much in Python programming unless we talk about scientific computing. Here’s how we define a complex number, number = 5 + 3] print(number) Conversion In this article, we will learn about the Python Type conversion with the help of examples. (In programming, type conversion is the process of converting data of one type to another. For example: converting integer data to string. There are two types of type conversion in Python. « Implicit Conversion - automatic type conversion « Explicit Conversion - manual type conversion D Python Implicit Type Conversion In certain situations, Python automatically converts one data type to another. This is known as implicit type conversion. Example 1: Converting integer to float Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss. integer_number = float_number = new_number = integer_number + float_numbey # display new value and resulting data ty print¢"\ ,new_number ) print( , type(new_number )) Output Value: 124.23 fa Data Type: Python Control Flow Statements and Loops Updated on: July 25, 2021 | +10 Comments In Python programming, flow control is the order in which statements or blocks of code are executed at runtime based on a condition. A program's control flow is the order in which the program's code executes. The control flow of a Python program is regulated by conditional statements, loops, and function calls. This section covers the if statement and for and while loops; functions are covered later in this chapter. What is a syntax in Python example? “A The syntax of the Python programming language is the set of See eee ee rules which defines how a Python pcos congas program will be written. Python Line ——— a Structure: A Python program is divided into a number of logical lines and every logical line is terminated by the token NEWLINE. A logical line is created from one or more physical lines. 19-Aug-2022 Python if statement The Python if statement is a statement which is used to test specified condition. We can use if statement to perform conditional operations in our Python application. The if statement executes only when specified condition is true. We can pass any valid expression into the if parentheses. There are various types of if statements in Python. 1. if statement 2. if-else statement 3. Else if statement 4. nested if statement If Statement Syntax If Statement Syntax if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true. if(condition): statements Start | Statements If(condition):——-»_ Execute if block | else/elif block/ regular flow Example of if statement: grade if grade rey wane With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >=) to 65. If it does meet this condition, we are telling the program to print out the string Passing grade. output of above example : Passing grade Again, if we change the grade to 50 ora< 65 number, we will receive no output. Logical operators Logical operators are the and, or, not operators. Logical operators in Python Op. Meaning Exp. and True if both the operands x and are true y or True if either of the xory operands is true not Trueif operand is false not x (complements the operand) Example : Logical Operators in Python Example : Logical Operators in Python Bitwise operators Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. For example, 2 is 10 in binary and 7 is 111. Operators are special symbols that al, - . ; = nea eS perform operations on variables and values. For example, print( RunCode » Here, + is an operator that adds two numbers: 5 and 6. 1. Python Arithmetic Operators Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc, For example, What are bitwise operators in Python? Python bitwise operators are used to perform bitwise calculations on integers. The integers are converted into binary format and then operations are performed bit by bit, hence the name bitwise operators. A= 10 => 1010 (Binary) B=7 => 111 (Binary) A&B = 1010 a ont «0010 = 2 (Decimal) Bitwase AND Operator Python bitwise operators work on integers only and the final output is returned in the decimal format. 03-Aug-2022 Python While Loop In Python, while loop is used to execute number of statements or body till the specified condition is true. Once the condition is false, the control will come out of the loop. while loops are constructed like so: [a condition [do something] Here, loop Body will execute till the expression passed is true. The Body may be a single statement or multiple statement. Python While Loop Example : Lists in Python Lists in Python is a type of variable which allows us to store multiple values of various data types in a single variable. In this section, let’s dive deep into the concept of Lists and see how to work with them in Python. Lists in Python can be created by just placing the sequence inside the square brackets[]. The elements inside the sequence are comma- separated. It can have any number of items and they may be of different types (integer, float, string, etc.) Example - #below is an example of creating an empty List list1 =[] #List with values of same data type list2 = [1,4,6,3,9] #list with values of different data types list3= [“John”, 23, 56.0, True] What is a List? abo List is yet another data type/data structure in Python. It is a sequence type data structure just like a string. A list allows us to store multiple values of different data types in a single variable. Some of the important features of the List are, e Lists are ordered collections of multiple values Lists are mutable, that means values of lists can e be changed and manipulated over a period of time e Lists allow us to store duplicate values Just like Lists, Tuples is also a data type/structure in Python. Tuple also comes under the category of sequence data types. It also allows us to store multiple values of different data types in a single variable. Some of the important features of the Tuples are, e Tuples are ordered collections of multiple values Tuples are immutable, which means values of the @ tuple cannot be changed and manipulated over a period of time e Tuples also allow us to store duplicate values Sets in Python Just like List, Tuples, and Dictionaries, Set is a data structure in Python that is used to group and store multiple elements. Let's dive into this section, and learn about how the concept of Sets can be used in Python. An empty set can be created using the set() function data = set() print(type(data)) Output Bitwise operators Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. For example, 2 is 10 in binary and 7 is 111. In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary) Op. >> << Bitwise operators in Python Bitwise AND Bitwise OR Bitwise NOT Bitwise XOR Bitwise right shift Bitwise left shift Exp. x& y = 0 (0000 0000) x|y=14 (0000 4110) =x = -11 (1111 0101) x“ y=14 (0000 1110) x>> 2 = 2 (0000 0010) x<< 2 = 40 (0010 1000) Python dictionary is an ordered collection (starting from Python 3.7) of items. It stores elements in key/value pairs. Here, keys - are unique identifiers that are associated with each value. Let's see an example, If we want to store information about countries and their capitals, we can create a dictionary with country names as keys and capitals as values. Keys Values Nepal Kathmandu Italy Rome England London Create a dictionary in Python Here's how we can create a dictionary in Python. capital_city = { print(capital city) RunCode » Output {'Nepal': 'Kathmandu', 'Italy': 'Rome', In the above example, we have created a dictionary named capital_city . Here, 1. Keys are "Nepal" |,.| “Italy” |, |“England" 2. Values are "Kathmandu", “Rome”, "London" Using the sorted() Function The critical function that you’ ll use to sort dictionaries is the built-in sorted() function. This function takes an iterable as the main argument, with two optional keyword-only arguments—a key function and a reverse Boolean value. To illustrate the sorted() function’s behavior in isolation, examine its use on a list of numbers: Python >>> >>> numbers, = [5, 3, 4, 3, 6) F, 3, Ze as # >>> sorted(numbers) iby 2p os Sy oy oy O45 Aa; De oe Te As you can see, the sorted() function takes an iterable, sorts comparable elements like numbers in ascending order, and returns a new list. With strings. it sorts them in alphabetical Essentially, sometimes you may want to have the original values unchanged and only modify the new values or vice versa. In Python, there are two ways to create copies: 1. Shallow Copy 2. Deep Copy Shallow Copy A shallow copy creates a new object which stores the reference of the original elements. So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects. This means, a CS. copy process does not recurse or create copies of nested objects itself. Example 2: Create a copy using shallow copy import copy pld_Vist = [{t, 2, 3], [4; 5; new_list = copy.copy(old_list) print( , Old_list) fe] aan a , new_list) be: Old list: [[1, New list: [[1, ed a nested list In above program, we crec and then shallow copy it using copy() method. This means it will create new and independent object with same content. To Deep Copy A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements. Let’s continue with example 2. However, we are going to create deep copy using deepcopy() function present in copy module. The deep copy creates independent copy of original object and all its nested objects. Example 5: Copying a list using deepcopy() import copy old_list = [[1, 1, 1], (2, 2, 21, new_list copy. deepcopy(old_list) print¢" ; Old_list) print ("N , new_list) When we run the program, it will output: Old list: [[1, 1, New list: [[1, 1, In the above program, we use deepcopy( ) function to create copy which looks similar. in Python, data type boolean also called bool is used to store two values i.e True and False Booleans in Python Boolean is used to compare two values or work with some conditions. For example, isLoggedIn = False Here, isLoggedin is the variable name, and False is a boolean value Some more examples Let’s say we want to compare two values, 5 and 10, then, print(5>10) print(5<10) Output False True To conclude, Boolean also called ‘bool’ holds two values - True and False. They are generally used when we want to compare some values or work with some conditions. Python Indentation Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code. Example TT & # 2: print("Five is greater than two!") Python break Statement The break statement is used to terminate the loop immediately when it is encountered. The syntax of the break statement is: . For example, for i in range(5): a break print (1) Run Code » Output In the above example, we have used the for loop to print the value of i . Notice the use ofthe break statement, Python continue Statement LEARN PYTHON Get started with Python one step at a time. The continue statement is used to skip the current iteration of the loop and the control flow of the program goes to the next iteration. The syntax of the continue statement is: For example, for 1 in range(5): if i continue print(1) RunCode » Output In the above example, we have used the for loop to print the value of i . Notice the use of the continue statement, Python for Loop In Python, the for loop is used toruna block of code for a certain number of times. It is used to iterate over any sequences such as list, tuple, string, etc. Flowchart of Python for Loop Enter Loop Body of for Loop Loop Terminates Working of Python for loop Example: Loop Over Python List languages = ['Swift’, 'Python', 'Go', # access items of a list using for loop language He] F404 GE Tey=i0 rst Run Code » =) Python Go JavaScript

You might also like