Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Class 9 Chapter 7 Python Programming

The document provides an introduction to programming with Python, covering key concepts such as data types, variables, and operators. It explains the differences between low-level and high-level programming languages, with a focus on Python's features, installation, and execution process. Additionally, it discusses various number systems, including decimal, binary, octal, and hexadecimal, and their relevance in programming.

Uploaded by

suchi.marts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
16 views

Class 9 Chapter 7 Python Programming

The document provides an introduction to programming with Python, covering key concepts such as data types, variables, and operators. It explains the differences between low-level and high-level programming languages, with a focus on Python's features, installation, and execution process. Additionally, it discusses various number systems, including decimal, binary, octal, and hexadecimal, and their relevance in programming.

Uploaded by

suchi.marts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 24
‘INTRODUCT] ONT PROGRAM 0 DATA AND ING WITH PYTHON! TARNING OBJECTIVES ‘faniaization with Python as object-oriented programming _ Tounderstand data types and variables in Python 4, Tounderstand various types of operators in Python ee eee “WRODUCTION l {programming language is a formal system used to instruct a computer to perform specifié tasks, it acts) as an intermediary between humans and computers, enabling us to communicate our instructions in a way that the computer can understand and execute. Programming languages provide a set of rules and syntax for writing code, which is then translated into machine-readable instructions by a compiler or interpreter. There are various programming languages available, each with its own strengths, purposes, and characteristics. Programming languages can be broadly categorized into low-level languages and high-level languages: 1, Low-Level Languages: These languages are closer to the hardware and provide direct control over computer resources. They include machine language and assembly language, which are specific to the architecture of the computer's hardware, Low-level languages are difficult to read and write for humans but offer efficient control over hardware resources. 2, High-Level Languages: These languages are designed to be closer to human language, making programming more intuitive and readable. High-level languages include Python, Java, C++, JavaScript, Ruby, and more, They abstract the complexity of machine-level operations and provide built-in features and libraries for various tasks. Tounderstand the concept and role of a programming language we will consider an example. Have you ever tried making a dish or pasta on your own. In that case you take one recipe from internet or a cooking manual where there are instructions on how to: 1. Input (What are the ingredients, how to use them and what are utensils required to cook) 2. Processing (What is the order and cooking time of each ingredient, full flame or just simmering) 3. Output (How to serve and present whatever you have made) Something similar happens in case of a computer. You have to enter raw data through an input device like a keyboard (input), the computer operates on that data that is called as processing and then desired result of the peration is obtained called as output. To get the desired output from the computer we give instructions to the computer using various programming languages. A computer can understand binary language (01). So, before we proceed to the coding part let us Understand various number systems which can help us to identify as well as interpret what are various options in Which we can represent data. Robotics and Aro @= | NEE) <4 number system. Decimal number isthe most, The technique to represent and work with numbers is calle a, used number system. For Example: fs have INR 725 in your pocket it simply means Seven Hundred: Twenty - five rupees, 72510 = 7*102 + 2*10'+5* 10° = 700 +20+5 As you can clearly see the base is 10 here. Other number systems include binary number system, octal number sy! study these number systems one by one, stem, hexadecimal number system er DeciMAL NUMBER SYSTEM Decimal number system is a base 10 number system having 10 digits from 0 to 9, This means that any num, quantity can be represented using these 10 digits. Decimal number system is also a positional valued system 1, means that the value of digits will depend on its position. Now suppose we have three numbers: 725, $71 and 2077, value of in all three numbers is dependent on the base value, Let us consider an example: 72510 =7* 107 +2* 10'+5*10° 700 + 20+5 Tees) Se: 10? | 10! | 1070 Binary NUMBER SYSTEM In this system we have only two digits 0 and 1, thus it is called binary number system. Each binary digit is also cales a bit. Binary number system is also positional value system, where each digit has a value expressed in powers of2,25 shown in the figure below. 1fofoflofofofo|1 2 | 2 | 25 | 24 | 23 | 22 | ai | 20 In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit is called most significart bit (MSB). The weightage of each position can be represented as follows: t[ToToTofoJfofo]i msB LsB ‘And decimal equivalent of this number is sum of product of each digit with its positional value having a base of 2. 10000001, = 1x27 + 0* 2° + 0x2° + 0* 24 + 0x23 + O* 22 + Ox2! + 1* 20 28 +04+0+0+04+04+041= 1295 OCTAL NUMBER SYSTEM Ithas eight digits - 0, 1,2, 3, 4, §, 6 and 7. Octal number system is also a positional value system where each digit its value expressed in powers of 8, as shown here: Decimal equivalent of any octal number is the sum of product of each digit with its positional value having @ base 324, = 3x8?+ 2x8)+ 4x8° =192 +16 +4 = 2129 ics and A = swat NUMBER SYSTEM “gto 9 and A to F where jgjtst 010 see A =10, Ben c=2 D=13 E=14 F=15 al number system is also a positional value system where each digit has its value expressed in powers of tasspown here: 16? | 16? | 16' | 16° equivalent of any hexadecimal number is sum of product of each digit with its positional value having a base TTAD yg = 1X16 + 7 x 162 + 10 x 16! + 13x16° = 4096 + 1792 +160 +13 = 60619 tonputer memory is measured in terms of how many. stsand bytes. it can store. Here is a chart to explain the relation between + thyte(B) = 8 bits + 1 Kilobytes (KB) = 1024 bytes + 1Megabyte (MB) = 1024 KB + 1Gigabyte (GB) = 1024 MB + Terabyte (TB) = 1024 GB + 1 Exabyte (EB) = 1024 TB + 1Zettabyte(ZB) = 1024 EB + 1Yottabyte (YB) = 1024 2B Niweek SYSTEM RELATIONSHIP Tetelowing table depicts the relationship between decimal, binary, octal and hexadecimal number systems. Hexadecimal | Decimal Octal Binary 0 0 0 (0000 1 1 1 0001 2 2 2 0010 3 3 3 oon 4 4 4 0100 5 5 5 o101 6 6 6 onto r 7 7 7 om 3 8 10 1000 2 9 1 1001 A 10 2 1010 B 1 13 100 c 2 4 1100 D 3 6 m0! E 4 16 mo F 15 7 m hs Ss & Robotics a” os ina language the com, er pier eocrarinaig Whguspes low ute ghelnamuetenstemcoMTettat 10! Putt Undertang For Example: C, C++, Java, Javascript, PHP, Python and many More: to a compu! Jhine understandal ‘iting a program and Let us understand how a programmer feeds instruction ter Ce a ae ait, Ha ‘hat prog is treated by the compiler or interpreter to generate mac ey SNSUTE Wal hep, D4 understand this, Binary Code Instructions oats (Machine Pret ie _cs_ Mac (omel understandable) coder) ATS Language fer can understand is called a "binary code" (computer understandable cay, The process of translating programming language code(human understandable) into binary code is known . “compilation” Each language, from C Language to Python, has its own distinct features, though many times thers, Similarities among programming languages. (There are other tools like interbr=ter assembler, linker and loader), a list of randomized numbers ranging from one it will take a sizable amount of time and in‘ The part of the language that a comput to ten thousand and is asked to pre For example: Ifa personis gj \clude some errors, them in ascending order, are that Code gets executed Steps involved when you run your Python code, 1. The compiler receives the source code, 2. The compiler checks the syntax of each line in the source code, 3, Ifthe compiler encounters an error, it halts the translation process with an error message (Syntax erro") 4, Else if the instruction is well formatted, then it translates the source code to Bytecode. 5, Bytecode is sent to the Python Virtual Machine (PVM) \,kep J \) N\ 6. Bytecode along with the inputs and Library modules is given as the input to the PVM. 7. PVM executes the Bytecode and if any error occurs, it displays an error message (Runtime error). 8, Otherwise, if there is no error in execution, it results in the output. Scan QR Code ! jons: to Download gate te tollowing otal numbers into decal om Oe |, 00! Pe | ove (b) 022 ! 087 (d) 025 / omert the following binary numbers into decimal form: tga (b) 10000001 @ 9000001 (d) coon camert the flowing hexadecimal numbers into decimal form: 90d (b) oxe3 (ae? (@) Off «cower the following decimal numbers into octal binary and hexadecimal frm: pecimal Binary Octal Hexadecimal % oooonn v7 Oxt 25 amin a7 oxtf 18 10000000 200 0x80 00001100 14 oxe 1 Keyboard is an output device. {— 2. CPUis responsible for processing an input request.) 4 Money works with decimal number system. | 4, Binary number system comprises of 4 digits. => § Octal number system comprises of 8 digits. "T 6 Hexadecimal number system comprises of 10 digits. 7 Decimal number system comprises of 10 digits. "F ® Shits can give a maximum value of 255. “[ \ § Binary number system consists of only two values, ie. 0 and 1. AF ' ; 16s equivalent to 1000 MB. {~ } > 12 yoo’ Oe yu | \G sand aL | PEIN cual 5 reated by "Guido van Rossum" in Nethay } Pythonisa high-level object-oriented programming language that wascmT ost is used in al : It was officially released in 1991. Itis also called general-purpose programming [ang Mea domain, Python is used by Professionals like: Python developers, Somvtr™ programmers. The python program is first compiled and then interpreted. T! programmer. Thus, compilation is an implicit process in python. andy oP engineers, back-end developers, p, ty : thy 1e compilation part is hidden frop, TT Features oF PYTHON 4, Simplicity and consistency 2, Flexibility 3. Access to great libraries 4, Platform Pissed War sairinio Sipser Supports a variety of databases Al these features add to the overall popularity and evolution of the language : 1. Simple and consistent: Python offers concise and readable code. While complex algorithms and versaig sworeleurs tana behlad machine earning ane aveyinor'e smmpacwy alowsceveopers (2.87 reliable sofa thas few keywords, simple structures and a well defined syntax. 2, Flexibility: I's generally accepted that Python is suitable for collaborative implementation when muitge developers are involved, Since Python isa general-purpose language, itcan do a set of complex machine leery tacks and enable you to build prototypes quickly that llow you to test your product for machine earring ania purposes. t supports an interactive mode in which testing and debuaging of code can be done eas! 4 Extensive access to libraries and frameworks: A software library is pre-written code that developers use solve common programming tasks. Python, with its rich technology stack, has an extensive set of libraries xa and ML (Artificial Intelligence and Machine Learning). 44, Platform independence: Platform independence refers to @ programming language or framework along developers to implement things on one machine and use them on another machine without any (or with en) minimal) changes. 5, Extendable and great community Support: Low level modules can be added to Python interpreter which o= help programmers to customize their tools for better efficiency. In the Developer Survey 2018 by Stack Overflow, Python was among the top 10 most popular progremmie languages. Python is the language that people Google more than any other. 6. Supports a variety of databases: Python provides interfaces to all major open source and high end datobess Database can be Relational Database (SQL that supports Tables) like MySql, MSAccess, ete. which are not®™ to scale and update as the project size increases and on the other hand Non-Relational database like Mongod® HBase , Cassandra store data in documents similar to JSON (JavaScript Object Notation) objects. INSTALLATION Select the latest version of python from www.python.org/downloads ae You can download python according to the type of OS you have: et ° & (Scan the QR code) i & poboticsa™" | you may goto all releases and then nsoose the suitable version as per vet you have to choose the type ale suitable for your system, if you geamac((0S) user then you can use ‘qac0S 64-bit installer” or if you are Windows user you can download the ecutable installer as shown in the fue Download and save this executable ‘nalocal drive and install it by double cicking the set up.Once you do that, 4 prompt will appear asking you to “stall Now" , along with this also click the ‘Add Python 310(version name) to aT Mots and AI-9 Python 2»Downloads > Windows Python Releases for Windows atest Python 3 Release Python 3100, Pr onar18 Install Python 3.10.0 (64-bit) Suctnga Nowa Pyten with dt tings 0 aoe Sere toe te ore. @ Install Now Intl NOW essere ent Ince LE pit docameration (pee eres an ie sccm customize installation Choose actin and ees The Setup will progress and will take a few seconds to install.Just Go to start menu and type "python' Setup Progress Pyben 330 + rym ntti) > 2 ben arts -— a onning Pyhon 3100 aaa (64-080) yD emt Ifyou get the right output it means all is well , “Welcome to the World of Codin WITH PYTHON INTERPRETER thon interpreter has two phases: (ey Source code is compiled into byte code, 1 Byte code is executed on the Python Virtual Machine. Byte code is regenerated every time source code OR the python version on the machine changes. Byte code generation saves repeated compilation time. Source code Byte code Execution by PVM. “fm can be written in a python script that is interpreted as a block. ‘Code can also be entered into the Python command line interface, __(You can exit the command line with Ctrl-z on Windows and Ctrl-d on Unix) if you want to save your script you can always go for the Script Mode, 3) Robotics and A Click on Start All Programs Python IDLE(Python GUI) as shown in the figure. a print 0:18) tse visas | [PFene (™HO2) mn wins? eight", "credic: F more information. TD Save Before Run or Check Step-3: You can save the file first, but if directly try to run the program it will prompt eso _juto save the file fist. suse Eo) Goa} After saving the file you will get the output as shown in the following figure Ta Fescheckpy-Dimmptho. — OC ™ | [id wresretsi00 - o x ‘Fle Eat Shell Debug Options Window Help Oct 4 2021, 19:00:18) (Msc v.1929 “| 64 bie (AMD64)] on win32 |Type “help”, "copyright", “credits” Jor “liconse()" for more information. Fae Est Format fun Options Window Hs [print ("Hell >>: ‘= RESTART: D: /aypython/Firstcheck.py Hello b>>l _ tee cto Toxens inPython, each logical line nce of elementary lexical components known as tokens. Each 'oken corresponds to a substring of the logical line, - Thenormal token types argidentifier’keywords operators, Yelimiters, ‘and literals, Whitespace separation is necessary between adjacent identifiers or Keywords; otherwise, Python would parse them as a single identifier. For example: ClassSixth is a single identifier; to write the keyword class followed by the identifier Sixth, you need to 'sert some whitespace (eg, class Sixth). Yobotics and Al-g & \ egstiaddress2) used tO identify i Variable, func ry, : ployee Sa oa alettet (AtoZ0L8 toz)or an underscore followed by zn ifier mat nt ig case sensitive which means: lowercase and Uppercase jeg.” . Python: y ICES ti, ie “ 9 within identifiers.) Normal Pyt Note: Python does not allow punctuation characters such a6 @, + Os eevee caches fees a is to start class names with an uppercase letter (such as Sn i ie hs FH sd laa cor Withs rowercase letter (such as roll, fee, balance). Starting 2” identifier with a sing! Venicn that the identifier is meant to be private. sy aewactio a cial reserved words that ave Keywords: Python keywords are spe aia uel always available, no need to import them into Your code. expect True, False and None: addr Identifiers: An identifier is a name (Em roll_no class, module, or other object: An identi more letters, underscores, and digits (0 to 9) are different. eanings and purpose. The keywords 5 .d as a function or variable name, ay Phy keywords in python are written in lower cas it False else import its a ; None break except in se ‘True class finally is ; i and continue for lambda va a def from nonlocal while assert del global not with elif if or yield asyne Point To REMEMBER You can't assign something to Python keywords. if you try to assign something to a built-in function or type: Variables: Variables are the basic unit of storage for a program. Spa de-allocated when required, ‘Another definition: A variable is a reference to a location in memory which can hold Programs perform operations on variables and alter or fillin their values, Solet us understand how many differen types of values we can assign toa variable, if you try, then youll get a Syntax error. You won't get a Syntax err but it sil isn't a good way of coding. ce can be allocated for variables and can be a value of a specific type. For Example: gender = ‘Mt message = “be happy” price = 450 Exercise: Solution: bookname =" Intro to python” print("Book name is: bookname) a program to display the values of variables in python. price = 450 print("The price of the book is: ", price) ‘Output: Book name is: Intro to python The price of the book is: 450 In the above program, the variable bookname is holding a string type value that is why the contents are assigned!» the variable with the help of double quotes( single quotes can also be used). On the other hand the variable price is given a value without any single or double quotes because it is a numeric value. Variable declaration is implicit in python , means variables are automatically declared and defined when they ae assigned a value first time. So it is important to Understand that we must define a variable before using t it®" expression, else it wil result in compile time error(Syntax error). We will learn about operators in the next class : © Robotics and Sean QR Code to Download http://epilin/X3EO) inthe blanks: 1, Compiler is used to convert high level instructions into binary code. 2 Binary code is called computer understandable code, 3, Python was officially released in the year 1991 ‘ 4, Write once run anywhere means Platform independence 5, Source code is compiled into byteCode 6. Smallest individual element of a program is called as token . 7, Python keywords are special reserved words. 8, Keywords in Python are written in lowercase case. 2 variables: are the basic unit of storage for a program, Assignment __operator can be used to assign a value to a variable. n is evaluated to either True or False. Boolean expres: 2, Space can be allocated for variables and can be de-allocated when required, 4, False, True and None are keywords in Python. 5, print function is used to display output with a string. *ebotics and Alo HOU DATA TYPES IN PYTHON The data stored in a variable can be of many types: We can sti address can be stored as alphanumeric characters. Operators are special symbols or tokens in Python that carry out various ty} arithmetic or logical, the value that the operator operates on is called the operand. For example: >>> 445 9 o Here, 4 and 5 are operands and + is an operator, where operands can be stored to a type of variable. Let's learn mo, about them. f Python has various standard data types that are used to define the operations: possible on them and the Storage method for each of them. ore student’ roll number a8 a numeric Value any, it pes of computation. Computations may Python has five standard data types— 1. Numeric 2, Set 3. Boolean 4, Sequence 5. Dictionary 1. Numeric Type Number data types store numeric values. Number objects are created when you assign a value to them. For example var =1 = x=30 var2 = 10 y=25 You can also delete the reference to a number object by using the del statement. The syntax of the del statement is— del vert delx,y [PYTHON SUPPORTS FOUR DIFFERENT NUMERICAL TYPES: int(signed integers) Jong (long integers, they can also be represented in octal and hexadecimal) float (floating point real values) ‘complex (complex numbers) ‘Some values that can be assigned to each type: int long float complex 32 89924361L Cs) 2.73) 200 -0x17823L 78.20 55j -67 o197L “519 3.322e-36) ¥) Robotics and AY? progra! write a program to find the area of a rectangle having 10 unit length and 20 unit breadth. | program Output | Fomit_Run_Optons Window Help er Fe Est Set Debvy_Options ie Hreagth=10 ‘ ee eS + 08:53:46) (MSC v.1916 64 bit (AMDE4)] on wind? prea ‘Type "help", “copyright, “credits” or “license () fea= length * breadth ltrine ("Area of the rectangle ie: " area) "for more yormation. >>> sennenn RESTART: D: /mypython/AreaofRect .py ====== of the rectangle is: 200 = a 2,Set Type setis an unordered collection of data that is iterable, mutable and has no duplicate elements. The order of elements ina set is undefined though it may consist of elements of various types. Program Output [Fa tan_Sh_Detag Opes Wdom_T — ESTAR: D:/mypbn/ 300-97 ———mmmmm [izee tn + cctaas ‘ase. frmaie eoseces (40, 20, 20, 30) lise wn coece for aupitcates in a sets jso'aupaScases (10, 20? if we want to represent a group of unique values as a single entity, then we should go for set. We can represent set elements within curly braces and with comma separation, Insertion order is not preserved. But we can sort the elements. Program Output [ie Gk fom fan Options Window Help [insertion order in nor preserved! losi~ (10, 20,30, 409 lease(rey cefacie outpuc: * , seta) [itor we can sort che elements using sorted function feist (soreed (oeei)) rae, 20, 30, 40) stasc 49 creaced fist wo cnece for aupticetes in Ine eapiicates (10, 20) RESTART: Di/mypyenen/Setordez.py —— Joy azeaate oncpat® (40, 10, 20, 30) tHe, 20, 30, 401 psd Both Homogeneous (same type) and Heterogeneous (different type) elements are allowed. Set objects are mutable once we create set object we can perform any changes in that object based on our requirement. 3.Boolean Type While designing a logic you often need to know if an expression is True or False, You can evaluate any expression in Python to two values: True or False (Remember they are keywords as well). Ifwe compare two values, the expression is evaluated and Python returns the Boolean answer: Output Program, RESTART: D: /mypython/uyBoolean.py =—=—=——= fNorking of boolean data type (Checking the type: Result o€ 10> 3 ist True Remult of 10 = 9 emule of 10> 9 in 4. Sequence Type Sequence is the ordered collection of similar or different data types. Sequences allow storing multiple values in. organized and efficient fashion. There are several sequence types in Python - String -List qe ‘String: String in Python is identified as a contiguous set of characters represented in the quotation marks, Represented as: str = 'Hello World!’ or str = “Hello World” Python allows for either pairs of single or double quotes. In python there is no character data type, a character is a string of length one. Itis represented by str class. But by using single quotes or double quotes we cannot represent multiline string literals. Such as, s1="Hello World” #This will not compile For this requirement we should go for triple single quotes (") or triple double quotes (""") st=""Hello st=""Hello World” # Triple quotes for multi-ine string (°" World" # Triple-double quotes for multiline string String Operations: slice means a piece/part [ operator is called slice operator, which is used to retrieve parts of String, In Python Strings follows zero based index. The index can be either +ve or ~ ve. +ve index means forward direction from Left to Right -ve index means backward direction from Right to Left print("at 1 andex:", stringl{1]) print("et 3 index:", stringl[3)) print("et ¢ index:", stringli4]) the blanks ae Compiler _ is used to convert high level instructions into binary code. Be » ton wes officially released in the year 1901 c ay sourcecode compiled into____byteCode , |g smalls 1 thon Keywords are special reserved words. py Keywords n Python are written in lowercase 9 —_——-vatiables _are the basic unit of storage for a program. y Assignment operator can be used to assign a value to a variable. ‘true False 1, Set is an unordered collection of data having duplicates 2. Listis an unordered collection of data that may have duplicates 3. Boolean expression is evaluated to either True ofr False 4, Strings in python belongs to class. 5, Space can be allocated for variables and can be de-allocated when required. & While doing coding spaces have no significance. 1. False, True and None are keywords in Python. 8. print function is used to display output with a string. inary code __is called computer understandable code, nce run anywhere means Platform independence + individual element of a program is called as token Scan QR Code to Download http://epil.in/5ROXL case. UUJULUUL 7.4 CLASSIFICATION OF OPERATORS IN PYTHON [Ey Arithmetic operators Assignment operators [ER comparison operators Logical operators Identity operators Membership operators Bitwise operators Working sample for practice and use of each type of operator is given as follows: 7.4.1 ARITHMETIC OPERATORS They are used to perform mathematical operations, Detailed use and examples are given as follows: + ‘Addition x : Subtraction xy. : Multiplication Uhl L Division XLV %. Modulus XY * Exponentiation XAEY. WI. Floor division xily Program Output Fle Edt Format _Run Options Window Help [Fie tat Set Debug Options Window Help = [= RESTART: D:/Book10-Chap-3/Arith.py 4| print ("add (xty))# basic addition print ("Sub (x-y))# basic subtraction [print ("Mul (xty))# basic multiplication jprint ("Div :", (x/y))# float answer jprint ("Modulus :", (xty))# remainder print ("Exponential :", (x**y))# raise to power jprint ("Floor Divisio: (a/7y))# integer ans y| 7.4.2 ASSIGNMENT OPERATORS They are used to assign values to variable. Detailed use and examples are given as follows: r Robotics and A? s Output: ee File tat shel Debug Options Window Fassig Help 2 thand Addition i rai acataeTT bv print 15+ 3= 18 shorthand: D: /Book10-Chap pein’ Fenorthand Modulus rT “PY geet (fygwil) print 16% 4= 2 / }peins shorthand Exponential lee ee int 2 raise to power 2 ISON OPERATORS ye used to compare twO variables, detailed use and examples ar given as follows: Equal Not equal > Greater than xy Less than x=y Less than or equal to xy) # True True rint (x>1 # one bit will drop from right side print ("after 1 bit right shift”, x)#00000010=2 yey<>> Output: File Edit Shell Debug Options Window File Edit Format Run Options Window Help x=5 # 0000 0101 Help y=10 # 0000 1010 SS ee See zl=xsy # any zero is zero = RESTART: D:/Book10-Chap- iprint ("AND operation: ",z1) 3/Bitwisesimple.py z2=xly # any one is one iprint ("OR operation", z2) z3=x*y Iprint ("XOR operation:",z3) AND operation: 0 OR operation 15 XOR operation: 15 >>>] Pages komo The combination of values, variables, operators, and function calls is termed as an expression. The Python interpreter can evaluate a valid expression, For example: 33> 15-7 8 Here 15 -7 is an expression, There can be more than one operator in an expression, To evaluate these types of expressions there is a rule of precedence in Python. It guides the order in which these operations are carried out. For example, multiplication has higher precedence than subtraction. >>>10-3*2 4 #output Here, 32 will be evaluated first then 10-6 will result into 4 as the final answer. But we can change this order using parentheses () as it has higher precedence than multiplication. >>> (10 - 3) * 2# Parentheses () has higher precedence 14 #output Following is a diagram explaining how operators can precede each other when used together in an expression, Mobotics and al-g =a jeaning eee Lh Highest : What is the output of this expression, 3°1"*3? rst this expression will solve 1"3 because exponential has hi 13 = 1and 3" = 3, Final answer is 3. Q.2. : What's the output of this expression, 3*(7+3) 2? Explanation : First this expression will solve 7+3 because parenthesis has highé 743 = 10, 3410 = 30 and 30 2=28. Final answer is 28. Qi Explanation : igher precedence than multiplication, so fer precedence than multiplication, so PAT ULE hee bacon Python has become increasingly popularintt that make it well-suited for robotic applications: 4. Ease of Learning and Readability: Python has a clean an and experienced developers alike, This ease of learning can be field of robotics without a strong programming background. 2. Large Ecosystem and Libraries: Python has a vast ecosystem of libraries and frameworks that simplify various aspects of robotic development, Libraries such as ROS (Robot Operating System) provide @ ‘comprehensive set of Paneer bulding robotic systems, including communication between components, sensor integration, and more 3, Community Support: Python has a large and active community of developers. This means that there sbundant resources, tutorials, and forums where developers can seek help and share knowledge. This communty support can be invaluable for robotics projects, especially for troubleshooting and finding solutions to commen he field of robotics, andits adoption can beattributed to several advantages \d readable syntax, making it accessible for beginners particularly advantageous for those entering the challenges. 4. Versatility: Python is a versatile language that can be used for a wide range of applications, including date analysis, machine learning, and web development, This versatility is beneficial in robotics, where integrating different technologies and functionalities is often required. Integration with Hardware: Python has libraries and tools that facilitate the integration of hardware ‘components ‘commonly used in robotics, such as sensors, actuators, and communication interfaces. This makes it easier ‘© interface with the physical world in robotic applications. Machine Learning and Al Integration: Python has become a dominant language in the field of machine learning ‘and artificial intelligence. This is beneficial for robotics applications that leverage these technologies for tess such as computer vision, natural language processing, and decision-making. Cross-Platform Compatibility: Python is a cross-platform language, meanin { ‘, 4 meethe 1 1g that code written in Python can run on different operating systems without modification, This flexibility is advantageous in robotics, Rie divers? hardware platforms and operating systems may be encountered. : Robotics and A‘? ie. Toms Scanancode LAr w/a] to Download y 3 Attp://epil.in/EWMTU fal Fill in the blanks 1 Membership operators are used to check test if a sequence is presented in an object or not 2 _is _and is not called as identity operators, 3. Arithmetic...» operators are used to perform mathematical operations. 4. Bitwise Operators return the resultin___decimal format. 5. Exponential operator is denoted by ” 6. What is the symbol used for floor division MW. 7, What is the symbol used for bitwise XOR a True /False ‘1. Comparison operators are used to allocate value to a variable. 2. Assignment Operators are used to test the remainder of an expression. 3. Ider Operators are used to determine whether a value is of a certain 4. Operator precedence guides the order in which the operators in the same expression are evaluated. Not, is and is not are identity operators. 6 Membership operators are used to test if a sequence is present in an object or not. 7, x+=13 is not a valid statement, 8, %is an arithmetic operator which returns remainder of an expression. LOO UOU Wobotics and alo & | Multiple Choice Questions: x=2 y=3 x=xty yt=t print(x, y) (a) 54 (b) 64 c=38 f= (c8)+32 print("f =") fa) 1004 (b) f= 1004 num = 15 num2 = 12 sum = numl + num2 print("Sum of 16 and 12 is sum) {a) Sum of 15 and 12 is 27 (©) error P=1 R=1 T=1 Si=(P*R*T) /100 print(‘simple interest is’ Sl) {e) simple interest is" SI {c) simple interest is 0.01 a= ‘Sachin’ b="Tendulkar’ print(e +" "+b) (2) SachinTendulkar () a+b a= ‘hello’ b = ‘world’ c=a-b print(c) (2) hello-world (c) Type€rror: unsupported operand 6 print 8/b (a) 4.3 (b) 4.0 (c) 53 (d) 63 (c) error (d) none of these (b) Sum of 15 and 12 is sum (d) none of these (b) simple interest is’ 0.01 (d) none of these (b) Sachin Tendulkar (d) Sachin + Tendulkar (b) helloworld (d) None of the above (cl. (a) Syntax Error Robotics and Al? g. X==19%2 print (x) (a) 9 name="Hello World” print(type(name)) (a) Hello World (b) hello world (0) (4) str 3 (b) 2 () 1 (d) Error 10. What is the output of this expression, print(x) ? (eeee () 9 (c) 3 (1 [True and Fals 1. A programming language serves as a bridge between humans and computers, allowing instructions to be ‘communicated in a way the computer can understand, 2. Low-level languages, such as machine language and assembly language, are closer to hardware and provide direct control over computer resources, 3. High-level languages like Python and Java are designed to be closer to human language, making programming and readable. more intui 4, The decimal number system is a base-10 system, where any numerical quantity can be represented using the digits 0 to 7 5, In Binary number system each digit (bit) has a positional value expressed in powers of 4. 6, Octal is a base-8 number system, and each digit has its value expressed in powers of 8. 7, Hexadecimal is a base-16 number system, and it includes digits 0-9 and letters A-F, representing values 10-15. 8, Python is a high-level object-oriented programming language created by James Gosling and officially released in 1995. 9, Python is known for its simplicity, flexibility, and extensive access to libraries, making it suitable for various domans. 10. The binary code, which is the part of the programming language that a computer can understand, is generated through the process of compilation. 11. Python keywords, such as “and and “or,' cannot be assigned as variable names, time errors, ‘2, Variables in Python must be explicitly declared before use to avoid compil Python supports various data types, including numeric types (int, float, complex), set, boolean, sequence types (string, list, tuple), and dictionary. 14. Logical operators in Python, such as “and” and “or” are used on conditional statements and return either True or False, 15. Bitwise operators in Python, like “&" and “|” perform operations on binary representations of integers, | manipulating individual bits. Fobotics and AL-9 & [Flin the blanks | 1. Decimal number system comprises of ____ values: 2, number system comprises of 8 digits. 3 number system comprises of only 0 and 1, 4, Computer memory is measured in terms of _____ it can store. 5, are smallest individual elements of a program. 6 ‘and___ are two possible values for boolean data type: 7, In Python True, False and None are ____s well as values. & _____ variable is defined inside the function only. 8 Setis an unordered collection of no _ ___ elements. 10. Python Strings are of type. 1, ___are smallest individual elements of a program. eee ena are two possible values for boolean data type. 13. In Python True, False and None are as well as values. 14, Setis an unordered collection of elements. 15. Python Strings are of type. 1. What are various data types in Python. 2. What do you mean by a 3. What do you mean by d with example, 4, Explain the working of +ve and -ve string indexing. 5. What do you mean by operators? 6. What are various types of operators? 7. Explain arithmetic operators with the help of program. 8. What do you mean by logical operators? Explain with an example. 9. Explain the operator precedence in Python. 10. Howa list is different from a set? Robotics and A’?

You might also like