0% found this document useful (0 votes)
5 views35 pages

Python Programming Ch-2

The document provides an introduction to Python, covering its features, applications, and installation process. It highlights Python's ease of use, readability, and versatility in various domains such as web development, data science, and artificial intelligence. Additionally, it outlines the basic structure of a Python program and includes instructions for running a simple Python code.

Uploaded by

dp8260264
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)
5 views35 pages

Python Programming Ch-2

The document provides an introduction to Python, covering its features, applications, and installation process. It highlights Python's ease of use, readability, and versatility in various domains such as web development, data science, and artificial intelligence. Additionally, it outlines the basic structure of a Python program and includes instructions for running a simple Python code.

Uploaded by

dp8260264
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
Python Introduction 2.1 Introduction to Python Python features Applications of Python Programming 22 Python installation 2.3 Basic Structure of Python Program First Python Program Keywords Identifiers and variables Data types Operators 24 Type Conversion 11 Solved Questions 7 Exercise J Questions Program Exercise -2.1 Introduction to Python — ‘Python is an open-source (free) programming language that is used in web programming. dats science, artificial intelligence, and many scientific applications. Learning Python allows the programmer to focus on solving problems, rather than focusing on [Link] was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. +— Python Features 1. Easy Language Python is an easy language. It is easy 0 read, write, learn and understand + Python has a smooth learning curve. It is easy to learn + Python has a simple syntax and Python code is easy to understand, + Since it’s easy to understand, you can easily read and understand someone else's code + Python is also easy to write because of its simple syntax. 2. Readable ‘The Python language is designed {0 make developers life easy. Reading a Python code is like reading an English sentence. This is one of the Key reasons that makes Python best for beginners Python uses indentation instead of eurly braces, unlike other programming languages. This makes the code look clean and easier to understand 3. Interpreted Language Python is an interpreted language. It comes with the IDLE. (Interactive Development Environment). This is an interpreter and follows the REPL structure (Read-Evaluate-Print-Loop). It executes and displays the output of one line at a time, Python Programming -(1T) / 2021/4 26 | Python Programming: So it displays errors while you're running a line and displays the entire stack trace for the error 4. Dyngmically-Typed Language You don’t need to declare data type while defining a variable. The interpreter determines this at runtime bused on the types of the parts of the expression. This iy easy for programmers bul can create runtime errors, 5. Object-Oriented Python is object-oriented but supports both functional and object-ori Everything in Python is an object 6 Open-Source ed programming Python is open-source and the community is always contributing to it to improve it. It is free and its source code is freely available to the public. You can download Python from the official Python Website. 7, Large Standard Library The standard library is large and has many packages and modules with common and important = functionality. If you need something that is available in this standard library. you don't need to write ~ it from scratch. Because of this, you can focus on more important things. 8 Platform-Independent Python is platform-independent. If you write a program, it will run on different platforms like Windows, Mac and Linux. You don't need to write them separately for each platform. 9 Extensible and Embeddable Python is extensible. You can use code from other languages like C++ in your Python [Link] is also embeddable. You can embed your Python code in other languages like C++. 10. GUI Support You can use Python to create GUI (Graphical User Interfaces). Applications of Python Programming Python can be used for various domains : [Domain Desktop and Web | A Desktop application is one that runs stand-alone in a desktop or laptop | Applications computer for example BitTorrent, Blender, Juice while a Web application | requires a Web browser to run, for example Mailman, Plone, MoinMoin. hms. Data Science It is a field that uses scientific methods such as data collection; alg and machine learning techniques to extract, analyze and process. insights | from raw data Machine Learning | It is an application of artificial intelligence (Al) that gives systems the ability to automatically learn and improve from experience and data without being explicitly programmed | Roboties It is a branch of engineering that deals with the conception, design. manufacture, and operation of robots. Artificial Iis a broad field that deals with enabling machines to demonstrate intelligence Intelligence similar to human's intelligence such as decision-making, facial recognition, etc. Python Introduction “| | Antificial intelligence incorporates other fields like Machine Learning. Robotics, Natural Language Processing(NLP). ete Internet of Things (oT) Gaming tis a field that describes the network of things that are embedded with software, and other technologies for the purpose of connecting and exchanging data with other devices over the internet It is the art of designing and programming games for entertainment, educational, or experimental purposes and that runs on computers and mobile devices. Mobile Applications. It is a computer program or app designed to run on mobile device such as a phone, table, or watch | | | Natural Language processing 3D CAD It is a field that analyses speech in both audible speech, us well as text of a language Python can create a 3D CAD application by using the following functionalities. - Fandango (Popular) = CAMVOX ~ HeeksCNC - AnyCAD : RCAM. Data visualization Data visualization is another popular and developing area of interest. Python | provides a variety of graphing libraries with all kinds of features. You can find a library to create simple graphical representation or even a more | interactive plot in Python. Examples include Pandas Visualization and Plotly. _| Finance Python is increasingly being utilized in the world of finance, often in areas such as quantitative and qualitative analysis. Tt can be a valuable tool in determining asset price trends and predictions, Image Processing Python contains many libraries that are used to work with the image. Some libraries of image processing are given below. ~ Oven CV - Pillow - SimplelTK + Slow speed Some Drawbacks of Python are: + Memory inefficient Ineffective in mobile computing. Undeveloped database layers, © Run time error prompt due to its dynamism. 2.2 Python Installation = |_-~ Before we start Python programming, we need to have an interpreter to interpret and run our Programs. There are certain online interpreters like htips://[Link]/, [Link] 0 [Link] that can be used to run Python programs without installing an interpreter. 28 mh Python Programming | Windows: There are muny imierpisiers available freely to run Python senpis like IDLE (Integrated Development Environment! that comes bundled with the Python software downloaded from hitpy pythonorg + Python 3 Installation on Windows Step 1 : Download Python 3. ick on the button to downioad the latest version of To start. go to python org/downloads and then Python See eet Certo Down. .d the latest version for Windows Looking for Python wath a different 05? Python for Windows Perraieahysus Step 2: Run the -exe file Neat, run the .exe file that you just downloaded vy e python-3.9.0 [ Python Introduction 29 Step 3: Install Python 3.9 You can now start the installation of Python by clicking on Install Now Python 1.36 (ob ba, Setup om } Install Python 3.9.0 (64-bit) Selec toinstal , se cr choose nstallat python Ginstat lavncner for all users (recommenced) _ windows Ciaea Fytnen 39 te Note : that depending on your needs, you may also check the box to add Python to the Path. Your installation should now begin: [Python 38.0 (64-bit) Setup = i Setup Progress 1 Installing: Iritiaizing, | python windows Cancel Python Programming [30 After a short period of time, your setup would be completed + Pythan 3.9.0 (64-ba) Setup = x | \ Setup was successful | N a At your terminal, type “py” to launch Python. | OF Search for Python in your Start menu release. of find more info about i oS 5 > S a fee windows Close Congrats, you just i led Python on Windows! Let's now see how to run a simple code in Python Run a Code in Python You can run a code in Python via the Python IDLE A quick way to find your Python IDLE on Windows is by clicking on the Start menu. You should “then see the IDLE under “Recently added” Deen es | eer ey Deed Vet oe CUCL nam) you'll see the Shell sc Once you click on the Python IDLE. [Python Introduction [LB Python 33.0 shen File Edt Shell Debug Options Window Help Python 3.5.0 (cags/v3.3. 64 Pit (AMDES)} on wins2 Type “help, "copyright", "credits" ox "License ()" for more informact ct67E2, Oct $ 2029, [Link]) (MSC v.4927 | | | Click on File and then select New File (alternatively, you may use the keyboard shortcut of Ctrl+N): “| 0)" (HSC vs a9a7 | ‘se£6752, Oct § 202 woxedice™ ox “License()" for more informari 32 Python Programming | You would now see the following “untitled” box, where you can type ee Python code | Lae unttied - o | File Edit Format Run Options Window Help *| | | | | For example. type/copy the command below. This command will print the famous expression of “Hello World” af tt Cok 0} print (“Hello World") This is how the syntax would look like in the “untitled” box [a vuntitier” i Run Options Window Hi v Ln: 16 Cok 0 Python Introduction 33 Press F5 on your keyboard. You will then get the following message to save your code oT] | [& Save Before Run or Check X | | Source Must Be Saved | OK to Save? | | EZ ome Choose a location where the Python file will be saved on your computer. You'll also need to type a name for your file. For example, type “Test” for your file name: Ud Saves ‘ ot This PC > Desktop > Test vB Seren Test 1 citi | Fucks | mb pettop 47 $ Downloads « Documents # © Pictures ete Install Python Once you're done, press Save, and you'll then see the “Hello World” expression printed on your Python Shell: = . [& Python 3.9.0 Shell File Edit Shell Debug Options Window Help Hello World >>> 2.3 Basie Structure of Python Program > The structure Python Program consists of three files such as :[Link] and [Link]. The file model [Link] is chosen for high level file. it is known as a simple text file of statements. ... Files [Link] and [Link] are modules Python Programming = (FT) / 2021 1 Python Programming Standard library modules oy Im General Python Program Consists of so many text files, which contains python statements Program 1s designed as single main. high file with one or more supplement files Python Statemenis i general. the interpreter reads and executes the statements line by line i.e sequentially. In python high level file has Important path of control of your Program where you can stan your application. The library tools are also known as Module files. These tools are implemented for making collection of top-level files. High level files use tools which are defined in Module files. + Modules : Modules are having top end of code. + Standard library files : Python has large collection of modules known as standard [Link] contains many modules for GUI Design, Internet and network scripting, Text design matching, Operating system Interfaces. First Python Program Let us execute programs in different modes of programming + Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the following prompt ~ Type the following text at the Python prompt and press the Enter “ >55 print “Hello, Python!” If you are running new version of Python, then you would need to use print statement wit parenthesis as in print (“Hello, Python!”);. this produces the following result “ Hello, Python ! * Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and contnis until the script is finished. When the script is finished, the interpreter is no longer nective, Let us write a simple Python program in a script. Python files have extension -py. Type following source code in a [Link] file Hello, Python [Python Introduction 38 We assume that you have Python interpreter set in PATH variable Now. try to program as follows ~ File C&t Format Run Options Yindow Help peine (rHeiin, eye This produces the following result * [ Hello, Python! Python Statements Python programs are typically organized with one statement per line. In other words. each statement occupies a single line, with the end of the statement delimited by the newline character that marks the end of the line. Example : print("Welcome to python programming’) Output : Welcome to python programming Multiple Statements per Line We can also write multiple statements per line, but it 1s not a 800d practice as it reduces the readability of the code. For Example, consider the following code. Example : a= 10: b= 2:cebta Print(a); print(b); print(c) Output fo ; 20 30 x Python Programming Implicit Line Continuation + Any statement containing opening parentheses (*(*), brackets (‘['), oF eurly braces ¢ { ) 18 presume, to be incomplete until all matching parentheses, brackets, and braces have been encountered For example, the nested list definition from above can be made much more readable using impligj line“continuation because of the open brackets >>> >>> as | (23.4, 5), | 16. 7, 8. 9. 10), (11, 12, 13, 14, 15}, U6, 17, 18, 19, 20), (21, 22, 23, 24, 25) >>> a (UL, 2, 3, 4, 5), (6, 7, 8, 9, 10], (11, 12, 13, 14, 15], U6, 17, 18, 19, 20}, (21, 22, 23, 24, 251] A long expression can also be continued across multiple lines by wrapping it in grouping parenthese: PEP 8 explicitly advocates using parentheses in this manner when appropriate : 7 oe >>> >>>someone_is_of_working_age = ( (person|_age >= 18 and person!_age <= 65) or (person2_age >= 18 and person2_age <= 65) or (person3_age >= 18 and person3_age <= 65) >>>someone_is_of_working_age True If you need to continue a statement across multiple lines, it is usually possible to use impli line continuation to do so. This is because parentheses. brackets, and curly braces appear so frequet! in Python syntax Python Introduction [37] Parentheses + Expression grouping + Function call >>> >>>print( “foo’. “bar”, “baz” o) foo bar baz + Method call >>> >>> ‘abe’ center( 9, Ey b Python Programmi * Tuple definition r | >>> >r> t= ( Curly Braces * Dictionary definition >>> >>> d = { * Set definition >>> | >>> xl = ( } “foo”. *bar’, Square Brackets * List definition >>> paras [ “foo”. ‘bar’, *baz’, ‘qux’ Python Introduction [39 * Indexing >>> >>>al 1 | ‘bar’ * Slicing >>> | >>>al - 12 1 bar’) * Dictionary key reference >>> >>>d[ * Comments in Python Symbols used for writing comments include Hash (#) or Triple Double Quotation marks (“""). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment. Example : 1 ‘##tH#H# This example will not print Hello World #¥##### print(Hello World’) # This is a commen {+o | Multiline Comments ™ This example will demonstrate multiple comments The following a variable contains the string “Your age’ a = ‘Your age?” The following statement prints what's insige the variable a _Print(a) Python Programminy, Keywords The following list shows the Python keywords. These are reserved words and you cannot use the as constant or variable or any other identifier names. All the Python keywords contain lowerca letters only. and exe not assert finally on break for pass ‘class from print continue | _ global raise def if return del impor | try elif in while else is with [except lambda | yield Identifiers and Variables A Python identifier is a name used to identify « variable, function, class, module or 0 object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by ze" more letters, underscores and digits (0 (0 9) Python Introduction Python does not allow punctuation characters such as @, $, and % within identifiers. Python [+] isa case sensitive programming language. Thus, name and Name are two different identifiers in Python, Python is not “statically typed”. We do not need to declare variables betore using them or declare their type A variable is created the moment we first assign a value to it. A variable is a name given to a memory location. It is the basic unit of storage in a program. + The value stored in a variable can be changed during program execution + A variable is only a name given to a memory location; all the operations done on the variable effects that memory location. A variable can have a short name (like x andy) or a more descriptive mame (age, carname, total_volume). Rules for Python variables * A variable name cannot start with a number * A variable name must start with a letter or the underscore chat +A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _) + Variable names are case-sensitive (age, Age and AGE are three different variables) Valid Variable Invalid Variable myCountry = “India” my_Country = “India” _my_Country = “India” myCountry = “India” MYCOUNTRY = “India” myCountry2 = “India” 2myCountry = “Ind my-Country = “India” my Country = “India” Example variable creation : # An integer assignment age = 41 # A floating point salary = 1234.5 # A string name = “India” print(age) Print(salary) print(name) LL Python Programming eS 42 | Python Programming Output = fat 1234.5 India _ + Declare the Variable Let's see how to declare the variable and print the variable. (w declaring the var | Number = 100 # display print( Number) + Output : 100 + Variable redectaration: # declaring the var Number = 100 # display print(“Before declare: “, Number) | # re-declare the var Numbejyg. 120.3. | prinAfter re-declare:", Number) We can re-declare the python variable once we have declared the variable already. + Output : Before declare: 100 After re-declare: 120.3 Assigning a single value to multiple variables: For example : print(a) Also, Python allows assigning # single value to several vuriables simultaneously with “ operators Python Introduction print(b) print(c) uu Output : 10 10 10 Assigning different values to multiple variables: Python allows adding different values in a single line with “{” operators a,b, ¢ = 1, 20.2, “India” print(a) print(b) print(c) Output : 1 20.2 India DATA TYPES Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes, Following are the standard or built-in data type. of Python > Numbers > String > List > Tuple > Dictionary aa Python Programming Python - Data Types | t / [- | Dictionary Boolean Set Se + Numbers Python supports four distinct numeric types : integers, long, float and complex numbers. In addition, Booleans are 4 subtype of plain integers. Integers or int are positive or negative whole numbers with no decimal point . Long integers have unlimited precision and floats represent real numbers and are written with a decimal point dividing the integer and fractional parts. Compl numbers have a real and imaginary part, a + bc, where a is the real part and b is the imaginary part. Example : #integer example =9999 Print(“type of x is “, type(x)) #float example ys3.14l Print(“The type of y is“. typety)) #complex example 229945} Print("The type of 2 is”, type(z)) Output : | Type of x is The type of y 1s < class “float” > The type of 2 is < class ‘complex’ > + String A String 1s an array of characters, They are formed by a list of characters, which is really an “array of characters”. They are less useful when storing information for the computer to use. An important characteristic of each string is its length, which is the number of characters in it. There are numerous algorithms for processing strings, including for searching, sorting, comparing and transforming. Python Introduction 45 ‘Tn Python. string is a sequence of Unicode character. Unicode was introduced to include every character in all languages and bring uniformity in encoding. We can create them simply by enclosing characters in quotes. Python treats single quotes the, double qui str = “Hello World” —//double quotes str = ‘Hello World!’//u 1g single quotes Python strings are “im “Characters in a siring can be Example : Hello World” table” which means they cannot be changed after they are created. iccessed using the standard [ ] syntax and zero-based indexing. su print (str{0)) | print (str{6:11]) | print (str + * !!") | print (len(str)) Output : e ¥ World Hello World !! i ra + List Python List is one of the most frequently used and very versatile datatype. Lists work similarly to strings: use the len() function and square brackets [ ] to access data, with the first element at index 0. Example : weekdays = ["Monday", “Tuesday” ‘Wednesday’, “Thursday”, “Friday"] print (weekdays{0)) print (weekdays(4]) Output : Monday + Tuple A tuple is « container which holds a series of comma-separated values between parentheses. A tuple is similar to a list. Since, tuples are quite similar to lists, both of them are_used 1 46 Python Programming | as_well. The only the difference is thal list is_enclosed between square bracket, tuple between parenthesis and List have mutable objects whereas Tuple have immutable objects 7 Example : my_Tuple_l = (1.2,"Hello” 3.14,"world”) | print(my_Tuple_1) print(my_Tuple_1[3}) my_Tuple_2 = (5,"six”) | printimy Tupte_1 + my_Tuple_23) Output : = 1, 2, ‘Hello’, 3.14, ‘world’) 3.14 2, ‘Hello’, 3, * Dictionary Pyhton Dictionaries allow you store and retrieve related information in a way that means something both to humans and computers. Dictionaries are _non-o: a contuin “keys” and “values”. Each key is unique and the values can _be just about anything. bil usually they are string, int, or float, or a listof these_things. Like lists dictionaries can easily be changed. can be shrunk and grown ad libitum at run ume, Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists. Dictionaries belong to the builtin mapping type. Example : # Creating a Dictionarywith Integer Keys ‘world’, 5, ‘six’) Dict = {1: 1, 2: ‘For’, 3: India} print(“\nDictionary with the use of Integer Keys: “) print(Dict) Output : Dictionary with the use of Integer Keys : {1: ‘I’, 2: ‘For’, 3: ‘India’} To tell what the value type is. you can use the buil we use the type() function to display the value type : type() function. In the following examples. >>> x = 42 \ >>> print(type(x)) >>> x = ‘hi’ =I Python Introduction i faz >>> print(type(x)) | po> x= 3.4 >>> print(type(x)) >>> x = False >>> print(type(x)) >>> + Checking for Type Equality While the type() function lets us check which type a variable contains. The is operator used for identity checking, Numeric values may compare as equal to each other using the equality test == yet _not match on their type. Consider this example: 1 pap xsl poe y = 10 >>> x y True >>> x is y False >>> In the above example, x is assigned the integer value | and y is assigned the float value 1.0. When tested using the equality match ==, the result is True. Yet when tested using the object identity operator is, the result is False since float and int are different types. + Operators Operators are used for carrying out operations on values and variables. Python has 7 types of Operators as stated below: lL Arithmetic Operator 2+ Comparison operators 34 Logical operators + Bitwise operators Ss Assignment Operator Python Programming * Identity operators Membership operators 1) Arithmetic Operators Python programming language suppons different kinds of arithmetic operators for both integer an floating point like addition, subtraction, multiplication, division and so on. — a Subtra Operator Type L_ Definition | Ado Addition (+) |_ Addition operator Subtraction () Subtraction operator Muluplication (*) Multiphe: Division (/) |_ Division operator | Modulus (%) | ]On operator Reminder operator Floor division (//) __Divides and returns the value of the remainder. Exponentiation (**) |” Raises the left operand to the power of right y= 10 Print(’x + y =", x+y) Output: x + y = 25 print(’x = y =", x-y) Output: x = y = 5 print(‘x * y =", x*y) Output: x * y = 150 print(*x / y =", x/y) Output: x / y = 1.5 print(’x % y =". x%y) Output: x % y = 5 print(*x // y =", wy) Output: x // y= | prim(-x ™* y =", x**y) Output: x ** 576650390625 on Introduction 49 [[@ Python 364 Shell - ao x File Edit Shell Debug Options Window Help Python 3.6.4 (¥3.6.4:d48eceb, Dec 19 2017, © on win32 Type "copyright", "credits" or *license()" for more information. pp> m= 1S 3) (HSC v.1900 32 bic (1 pop v= 10 p>> print (*x + y =", xy) x ty = 28 po> print(*x - y =", x-y) x-yes >>> primt('x * y =", xty) x * y = 150 >>> prin('x / y =", x/y) x/ yrs >>> print('x t y =", xty) xtyas >>> print (*x // y = ', x//y) x//y= >>> print ('x ** y= ', x**y) x ** y = 576650390625 2) Comparison Operators Comparison operators are used for companng values. It either returns True or False according to the condition. | Operators Definition Greater than (>) ‘True if left operand is greater than the nght Less than (<) True if left operand is less than the right Equal to True if both operands are equal , Not equal to True if operands are not equal , Greater than or equal to (>=) Truc if left operand is greater than or equal to the right | Less than or equal to (<=) ‘True if left operand is less than or equal to the right Example : x=8 ysis Uxpy is’x>y) Output : x > y is False Prinw'x< y is’, x

You might also like