0% found this document useful (0 votes)
3 views65 pages

GettingStartedwithPython 11 45PM

Uploaded by

Sandhya Kumari
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)
3 views65 pages

GettingStartedwithPython 11 45PM

Uploaded by

Sandhya Kumari
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
Teaching Exams ‘Supercoaching > Merge sort > Selection sort >» Heap Tree > Heap Sort Recap: ‘Supercoaching Introduction To Python: > Python is a widely used general-purpose, high level programming language. > Itwas designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. » Python is a programming language that lets you work quickly and integrate systems more efficiently. — > There are two major Python versions: Python 2 and Python 3. Both are quite different. > Python is a case-sensitive programming language, which means that the language treats uppercase and lowercase characters différentl Ga) That Pr gouh ‘Supercoaching Beginning with Python programming: '44\ ——— Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software downloaded from hitpy/[Link]/- Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you're running, type “python” in the terminal emulator. The interpreter should start and print the version number. » macOS: Generally, Python 2.7 comes bundled with macOS. You'll have to manually install Python 3 from [Link] ‘Supercoaching ifference between Python 2 and Python 3 > With Python 2, division between integers always returned another integer — so if you divided 7 by 5, you'd get 1. With Python 3, the same formula will return the actual value of 1.4 as a float. » The print keyword in Python 2 becoming the print() function in Python 3. print "Hello World: ///9. 2 Bint (Hello World) 7p. nl T=] Lately 7 ‘Supercoaching ifference between Python 2 and Python 3 > Python 2 is an untyped language. This means you can create a variable as a string, ke a name, and later assign itto an integer, like 2. Python 3 supports typing but doesn’t enforce it This means that developers can still write Python 3 code in the same style they wrote Python 2 code, but they can also choose 10 use type hints to write code that is more understandable, useable, and efficient. ae &, —— Nag. G2 £6 Cynon 23st e ee ee (asctBos) allowedfor the use of ISEtS, digits, and. © BURST uation (Georgi sean on the other hand, use: whicl ea et oe more. a ” iD antalle-na ‘eat Sap os slog 22s Sut [tock — har II we Gupercoaching Reason for increasing popularity Emphasis on code readability, shorter codes, ease of writing. Y Programmers can express logical concepts in fewer lines of code in comparison to languages Bl concepis In fewer Ikies ot cg peel ad such as C++ or Java. Y V Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural > There exists inbuilt functions for almost all of the frequently used concepts. Philosophy is “Simplicity is the best’. Y aun LANGUAGE FEATURES 1. Interpreted «There are no separate compilation and execution steps like C and C++. * Directly run the program from the source code. 7 . Internally, Python converts the source code info an intermediate form called bytecodes which is then translated into native language of specific computer to run it. a * No need to worry about linking and loading wi 2, Platfor (independent) Python programs can be developed and executed on multiple operating system platforms. * Python can be used on Linux, Windows, Macintosh, Solaris and many more. * Free and Open Source; Redistributable High-level Language _ «In Python, no néed fo take care about low-level details such as managing the memory used by the program. —! ‘Supercoaching LANGUAGE FEATURES 3. Simple * Closer to English language; Easy to Learn * More emphasis on the solution to the problem rather than the syntax See 5 4. Embeddable Python can be used within C/C++ program to give scripting capabilities for the program's users. 5. Robust: Exceptional handling features Memory management techniques in built ‘Supercoaching LANGUAGE FEATURES + The Python Standard Library is very vast. * Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many riiore. + Besides the standard library, there are various other high-quality libraries such as the Python hich is an amazingly simple image manipulation Tbrary. ‘Supercoaching oben AWALR Pros: * : — L | He & ve dione fee- Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics, etc.) ae Open source and large active community base : SaaS Versatile, Easy to read, learn and write — User-friendly data structures Hightevellanavase Dynamically typed language(No need to mention data type based on the value assigned, i takes data type) ” Object-Oriented and Procedural Programming language Portable and Interactive Ideal for\prototypes } provide more functionality with less codin, p ionalty ing Portable across Operating systems i oko Cy YO bO Supereoaching Aa . Gone: y ae tok Sumy =o + Absence fromriiodTis computing and browsers = For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable hames commonly used like amare TungionSin python. So, C, C++ programmers have to look out for these. = Performance: Python is an interpreted language, which means that it can be slower than compiled languages like C or Java. This can be an issue for performance-intensive tasks. iled languages [Link] Java. | {20 Global Interpreter Lock: The Global Interpreter Lock (GIL) is a mechanism in Python that prevents multiple threads from executing Python code at once. This can limit the parallelism eee OM ae (eg paratels and concurrency of some applications. ia T fehange LWS% (REV LS 10 os ele) ~ wis’, wetlo), NE cc oute PREG UALS”, Guobnitntng) taint If oak of pr Dep Supereoaching Cons: * Memory consumption: Python can consume a lot of memory, especially when working with large datasets or running complex algorithms. ed: Python is a dynamically typed language, which means that the types of variables can change at runtime. This can make it more difficult to catch errors and can lead to bugs. * Packaging and versioning: Python has a large number of packages and libraries, which can sometimes lead to versioniiig issues and package conilicts. S Supereoaching G Vw ications OR, GUL based desktop applications top application Graphic design, image processing applications, Games, and Scientific/ computational Applications Web frameworks and applications Enterprise and Business applications Operating Systems Education Database Access Language Development Prototyping Software Development Data Science and Machine Learning Scripting ‘Supercoaching Google(Components of Google spider and Search Engine) Yahoo(Maps) YouTube Mozilla Dropbox Microsoft Cisco + Spotify © Quora. © Facebook ‘ Supercoaching Execute Python Syntax 1) Python syntax can be executed by writing directly in the Command Line: 2) Or by creating a python file on the server, using the .py file extension, and running it in the Command Line: ious Supereoaching a hon Indentation: » Indentation refers to the spaces at the beginning of a code line. » In other programming languages the indentation in code is for readability only, the indentation in Python is very important. pees ak ee > Python uses indentation to indicate a block of code. » Python will give you an error if you skip the indentation. » The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one. » You have to use the same number of spaces in the same block of code, otherwise Python will give you an error Supercoaching Python Comments: » Comments can be used to explain Python code. » Comments can be used to make the code more readable. » Comments can be used to prevent execution when testing code. > Comments starts with a #, and Python will ignore them. = » You can add a multiline string (triple quotes) in your code, and place your comment inside it . ‘Supercoaching thon Keywords ) 45 Ne Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier. All the keywords in python are written in lowercase except True and False ard) as assert Greak) class continue det del elif else \ except nae Gassy yore finally from global Ge : : lambda | Hone) nonlocal not ease == [aw |__ Gimied) ty while with yield ‘syne await ‘Supercoaching Code to get all the keyword names # importing "keyword" for keyword operations noon Kew wots ba # printing all keywords at once using "kwlist()" ie print("The list of keywords is : ") pad 1 print([Link]) Output: The list of keywords is : [False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def, ‘del’, ‘elif, ‘else’, ‘except’, ‘finally’, ‘for, ‘from’, ‘global’, ‘if, import’, ‘in’, ‘is’, ‘ambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’] Gupercoaching Python Keywords(True, False, None): a > True: This keyword is used to represent a boolean true. If a statementis true, “True” is printed. > False: This keyword is used to represent a boolean false. If a statement is false, “False” is printed. » None: This is a special constant used to denote a{null valud or a void. It's important to remember, 0, any empty container(e.g empty list) does not compute to None. itis an object of its datatype — NoneType. Itis not possible to create multiple None objects and can assign them to variables. engl eects: | Falor +0 Nora = NUL Supereosching sok (Golan = = 0) a we pater (awe == 1) H Wot i a pate (Coe Tint Tee) Ho IES Lima Colon Gober) 4 | were patek (nove = = 0) # alae ot (tones 1) tr Felon rene ERS Python Keyword: ; snern Fink, vio, iby » and: This a logical operator in python. “and” Return the first false value. If not found return . oe Se ee ia ¢ = ik to Ht GeVian Kurd trie hairy. > OF; This a logical operator in python. “or” Return the first True [Link] not found return last v Not: This logical operator inverts the truth value. The truth table for “not” is depicted below. This keyword is used to check if a container contains a value. This keyword is also used to Toop through the container. Tred zao volut —> Colo Oand jo # phon 0 ‘Supercoaching fates: Cte wv Gola) HE tekoan Tan po (Foloe and True) $ Attar Fale peat C not Thue) 4 sulin Flor oukbut Ta w fol beak ok Isabtol. _— q = San? Oke Coun oe oe daisy ip to dick object idetet be hans ae 'o sik Sp cz Oe it a ae aay bean ‘Supercoaching Iteration Keywords - for, while, break, continue: Y for: This keyword is used to control flow and for looping. Qrerskive frokowe nko while: Has a similar working like ‘for’, used to control flow and for looping y V break: “break” is used to control the flow of the loop. The statement is used to break out of the loop and passes the control to the statement folowing inn iately after loop. — oy > gontinue: ‘continue’ is also used to control the flow of code. The keyword skips the current iteration of the loop but di tend the | = iteration of the loop but does not énd the loop. ‘Supercoaching for, witle, eo , conbmwas wotdle, bo | conbsnud Lin fargo: Pant (i, Ci ed ix 9) 48 st fatet( “Sa ip seo tse6: Cte, i Ses i= J 73 al I] ) ‘Supercoaching Conditional keywords - if, else, el 1 Itis a control statement for decision making. Truth expression forces control to go in “if” statement block. > else : Itis a control statement for decision making. False expression forces control to go in “else” statement block It is a control statement for decision making. It is short for “else if* ‘Supercoaching Python Keywords: def: def keyword is used to declare user defined functions. ‘Supercoaching Return Keywords : > return : This keyword is used to return from the function. > Yield : This keyword is used like return statement but is used to return a generator. ‘Supercoaching Class Keyword : » class keyword is used to declare user defined classes. ‘Supercoaching with Keywor with keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used much in day to day programming ‘Supercoaching As Keyword as keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as mymath. ‘Supercoaching Pass Keyword pass is the null statement in python. Nothing happens when this is encountered. This is used to prevent indentation errors and used as a placeholder. ‘Supercoaching lambda Keyword Lambda keyword is used to make inline returning functions with no statements allowed internally. ‘Supercoaching Python Keywords: > import: This statement is used to include a particular module into current program. > from: Generally used with import, from is used to import particular functionality from the module imported, > del: del is used to delete a reference to an object. Any variable or list value can be deleted using del. ‘Supercoaching Exception Handling Keywords » ty: This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in “try” block is checked, if there is any type of error, except block is executed. >» except: As explained above, this works together with “try” to catch exceptions. > finally: No matter what is result of the “try” block, block termed “finally” is always executed. » raise: We can raise an exception explicitly with the raise keyword > assert: This function is used for debugging purposes. Usually used to check the correctness of code. If a statement is evaluated to be true, nothing happens, but when it is false, “AssertionError’ is raised. One can also print a message with the error, separated by a comma. ‘Supercoaching Python Keywords: > global: This keyword is used to define a variable inside the function to be of a global scope. >» nol cal: This keyword works similar to the global, but rather than global, this keyword declares a variable to point to variable of outside enclosing function, in case of nested functions. GSupercoaching identifiers » Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good programming practice to give meaningful names to identifiers to make the code understandable. » We can also use the Python string isidentifier() method to check whether a string is a valid identifier or not. Supercoaching Rules for Naming Python Identifiers: » It cannot be a reserved python keyword. » It should not contain white space. » It can be a combination of A-Z, a-z, 0-9, or underscore. » It should start with an alphabet character or an underscore (_ ). » It should not contain any special character other than an underscore (_ ). Supercoaching Variables Variables are containers for storing data values. Creating Variables » Python has no command for declaring a variable. > Avariable is created the moment you first assign a value to it. » Variables do not need to be declared with any particular type, and can even change type after they have been set. ‘Supercoaching Variables Casting If you want to specify the data type of a variable, this can be done with casting. Get the Type You can get the data type of a variable with the type() function. ‘Supercoaching Variables Single or Double Quotes String variables can be declared either by using single or double quotes Case-Sen: le Variable names are case-sensitive. ‘Supercoaching Data types > Variables can store data of different types, and different types can do different things. > Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: _ int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview None Type: NoneType ‘Supercoaching Getting the Data Type: You can get the data type of any object by using the type() function ‘Supercoaching Setting the Data Type: In Python, the data type is set when you assign a value to a variable: Supercoaching Y v Operators Operators are used to perform operations on variables and values. Python divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators Supercoaching Python Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example + Addition xey - Subtraction x-y : Multiplication xy 7 Division x/y % Modulus x%y ™ | Exponentiation | Bl iW Floor division xily Supereoaching Python Assignment Operators Assignment operators are used to assign values to variables: ‘Operator Example Same As = x=5 x=5 = X+=3 X=x4+3 x-=3 x=x-3 * x*= x=x"3 x/=3 x=x/3 X %= 3 X=X%3 Xia 3 x= x3 oe aa ~g b= x &=3 =x&3 IF xie3 x=x/3 Supercoaching Python Comparison Operators Comparison operators are used to compare two values: [Operator] Name —_ | Example Equal y Not equal xy > Greater than xoy < Less than x= _ | Greater than or equal to xy <= Less than or equal to x> | Signed right shift | Shift right by pushing copies of the leftmost] x >> 2 bit in from the left, and let the rightmost bits fall off ‘Supercoaching Operator Precedence » Operator precedence describes the order in which operations are performed. > Iftwo operators have the same precedence, the expression is evaluated from left to right Supercoaching Operators If two operators have the same precedence, the expression is evaluated from left to right. ‘Operator Description 0 Parentheses ~ Exponontation oe ‘nary plas, unary minus, and bitwso NOT Ti % Mutation, dion, floor division, and madulve + ‘Addon and subtraction = Bice land ight ite @ wise AND = Bitwise XOR Bitwise OF in > be << Is isnot ih notin ‘Comparisons, ientiy, and membership operaiow: Tot Togical NOT and AND or OR ‘Supercoaching Expressions An expression is a combination of operators and operands that is interpreted to produce some other value. In any programming language, an expression is evaluated as per the precedence of its operators. So that if there is more than one operator in an expression, their precedence decides which operation will be performed first. We have many different types of expressions in Python. a) Constant Expressions b) Arithmetic Expressions ©) Integral Expressions d) Floating Expressions ©) Relational Expressions ) Logical Expressions 9) Bitwise Expressions h) Combinational Expressions ‘Supercoaching a) b) °) d) Different Types Of Expressions Constant Expressions: These are the expressions that have constant values only. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in these expressions are arithmetic operators like addition, subtraction, etc. Integral Expressions: These are the kind of expressions that produce only integer results after all computations and type conversions. Floating Expressions: These are the kind of expressions which produce floating point numbers as result after all computations and type conversions. ‘Supercoaching Different Types Of Expressions e) Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides of relational operator (> , <, >= , <=). Those arithmetic expressions are evaluated first, and then compared as per relational operator and produce a boolean output in the end. These expressions are also called Boolean expressions. f) Logical Expressions: These are kinds of expressions that result in either True or False. It basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also come across some logical operators which can be seen in logical expressions most often. ‘Supercoaching Different Types Of Expressions g) Bitwise Expressions: These are the kind of expressions in which computations are performed at bit level. h) Combinational Expressions: We can also use different types of expressions in a single expression, and that will be termed as combinational expressions. Glimpse of Next Session: ke - Flow Of Contro Cokin Supercoaching Any Queries???? @rls WH222? upercoaching THANK YOU! BEST OF LUCK!

You might also like