Basics Of Python Programming

3y ago
65 Views
3 Downloads
1.95 MB
31 Pages
Last View : 3d ago
Last Download : 3m ago
Upload by : Angela Sonnier
Transcription

Newsyllabus2020-21Chapter 5Basics ofPythonProgrammingInformatics PracticesClass XI ( As per CBSE Board)Visit : python.mykvs.in for regular updates

Basics of Python ProgrammingStructure of a python programProgram - Module - main program - functios - libraries - Statements- simple statement - compound statement - expressions - Operators - expressions ---- objects - data modelVisit : python.mykvs.in for regular updates

Python basicsPython 3.0 was released in 2008. Although this version is supposedto be backward incompatibles, later on many of its importantfeatures have been back ported to be compatible with version 2.7Python Character SetA set of valid characters recognized by python. Python uses the traditional ASCIIcharacter set. The latest version recognizes the Unicode character set. The ASCIIcharacter set is a subset of the Unicode character set.Letters :– A-Z,a-zDigits :– 0-9Special symbols :– Special symbol available over keyboardWhite spaces:– blank space,tab,carriage return,new line, form feedOther characters:- UnicodeVisit : python.mykvs.in for regular updates

Input and Outputvar1 ‘Computer Science'var2 ‘Informatics Practices'print(var1,' and ',var2,' )Output :Computer Science and Informatics Practicesraw input() Function In Python allows a user to give input to a program from akeyboard but in the form of string.NOTE : raw input() function is deprecated in python 3e.g.age int(raw input(‘enter your age’))percentage float(raw input(‘enter percentage’))input() Function In Python allows a user to give input to a program from a keyboardbut returns the value accordingly.e.g.age int(input(‘enter your age’))C age 2 #will not produce any errorNOTE : input() function always enter string value in python 3.so on need int(),float()function can be used for data conversion.Visit : python.mykvs.in for regular updates

IndentationIndentation refers to the spaces applied at the beginning ofa code line. In other programming languages theindentation in code is for readability only, where as theindentation in Python is very important.Python uses indentation to indicate a block of code or usedin block of codes.E.g.1if 3 2:print(“Three is greater than two!") //syntax error due to not indentedE.g.2if 3 2:print(“Three is greater than two!") //indented so no errorVisit : python.mykvs.in for regular updates

TokenSmallest individual unit in a program is known as token.1. Keywords2. Identifiers3. Literals4. Operators5. punctuatorsVisit : python.mykvs.in for regular updates

KeywordsReserve word of the compiler/interpreter which can’t beused as trydelinwhileelifiswithelselambdayieldexceptVisit : python.mykvs.in for regular updates

IdentifiersA Python identifier is a name used to identify a variable,function, class, module or other object.* An identifier starts with a letter A to Z or a to z or anunderscore ( ) followed by zero or more letters,underscores and digits (0 to 9).* Python does not allow special characters* Identifier must not be a keyword of Python.* Python is a case sensitive programming language.Thus, Rollnumber and rollnumber are two differentidentifiers in Python.Some valid identifiers : Mybook, file123, z2td, date 2, noSome invalid: 2rno,break,my.book,data-csVisit :identifierpython.mykvs.infor regular updates

Identifiers-continueSome additional naming conventions1. Class names start with an uppercase letter. All otheridentifiers start with a lowercase letter.2. Starting an identifier with a single leading underscoreindicates that the identifier is private.3. Starting an identifier with two leading underscoresindicates a strong private identifier.4. If the identifier also ends with two trailingunderscores, the identifier is a language-definedspecial name.Visit : python.mykvs.in for regular updates

LiteralsLiterals in Python can be defined as number, text, or otherdata that represent values to be stored in variables.Example of String Literals in Pythonname ‘Johni’ , fname “johny”Example of Integer Literals in Python(numeric literal)age 22Example of Float Literals in Python(numeric literal)height 6.2Example of Special Literals in Pythonname NoneVisit : python.mykvs.in for regular updates

LiteralsEscape sequence/Back slash character constantsEscape SequenceDescription\\Backslash (\)\'Single quote (')\"Double quote (")\aASCII Bell (BEL)\bASCII Backspace (BS)\fASCII Formfeed (FF)\nASCII Linefeed (LF)\rASCII Carriage Return (CR)\tASCII Horizontal Tab (TAB)\vASCII Vertical Tab (VT)\oooCharacter with octal value ooo\xhhCharacter with hex value hhVisit : python.mykvs.in for regular updates

OperatorsOperators can be defined as symbols that are used toperform operations on operands.Types of Operators1. Arithmetic Operators.2. Relational Operators.3. Assignment Operators.4. Logical Operators.5. Bitwise Operators6. Membership Operators7. Identity OperatorsVisit : python.mykvs.in for regular updates

Operators continue1. Arithmetic OperatorsArithmetic Operators are used to perform arithmeticoperations like addition, multiplication, division etc.OperatorsDescriptionExample perform addition of two numberx a b-perform subtraction of two numberx a-b/perform division of two numberx a/b*perform multiplication of two numberx a*b%Modulus returns remainderx a%b//Floor Division remove digits after the decimalpointx a//b**Exponent perform raise to powerx a**bVisit : python.mykvs.in for regular updates

Operator continueArithmatic operator continuee.g.x 5y 4print('x y ',x y)print('x - y ',x-y)print('x * y ',x*y)print('x / y ',x/y)print('x // y ',x//y)print('x ** y ',x**y)OUTPUT('x y ', 9)('x - y ', 1)('x * y ', 20)('x / y ', 1)('x // y ', 1)('x ** y ', 625) Write a program in python to calculate the simpleinterest based on entered amount ,rate and timeVisit : python.mykvs.in for regular updates

Arithmatic operator continueOperator continue# EMI Calculator program in Pythondef emi calculator(p, r, t):r r / (12 * 100) # one month interestt t * 12 # one month periodemi (p * r * pow(1 r, t)) / (pow(1 r, t) - 1)return emi# driver codeprincipal 10000;rate 10;time 2;emi emi calculator(principal, rate, time);print("Monthly EMI is ", emi)Visit : python.mykvs.in for regular updates

Operator continueArithmatic operator continueHow to calculate GSTGST ( Goods and Services Tax ) which is included in netprice ofproduct for get GST % first need to calculate GST Amount by subtract originalcost from Netprice and then applyGST % formula (GST Amount*100) / original cost# Python3 Program to compute GST from original and net prices.def Calculate GST(org cost, N price):# return value after calculate GST%return (((N price - org cost) * 100) / org cost);# Driver program to test above functionsorg cost 100N price 120print("GST ",end '')print(round(Calculate GST(org cost, N price)),end '')print("%")* Write a Python program to calculate the standard deviationVisit : python.mykvs.in for regular updates

Operators continue2. Relational Operators/Comparison OperatorRelational Operators are used to compare the values.Operators DescriptionExample Equal to, return true if a equals to ba b! Not equal, return true if a is not equalsto ba ! b Greater than, return true if a is greaterthan ba b Greater than or equal to , return true if aa bis greater than b or a is equals to b Less than, return true if a is less than ba b Less than or equal to , return true if a isless than b or a is equals to ba bVisit : python.mykvs.in for regular updates

Operator continueComparison operators continuee.g.x 101y 121print('x y is',x y)print('x y is',x y)print('x y is',x y)print('x ! y is',x! y)print('x y is',x y)print('x y is',x y)Output('x y is', False)('x y is', True)('x y is', False)('x ! y is', True)('x y is', False)('x y is', True)Visit : python.mykvs.in for regular updates

Operators continue3. Assignment OperatorsUsed to assign values to the variables.OperatorsDescriptionExample Assigns values from right side operands to left side operanda b Add 2 numbers and assigns the result to left operand.a b/ Divides 2 numbers and assigns the result to left operand.a/ b* Multiply 2 numbers and assigns the result to left operand.A* b- Subtracts 2 numbers and assigns the result to left operand.A- b% modulus 2 numbers and assigns the result to left operand.a% b// Perform floor division on 2 numbers and assigns the result to left operand.a// b** calculate power on operators and assigns the result to left operand.a** bVisit : python.mykvs.in for regular updates

Operators continue4. Logical OperatorsLogical Operators are used to perform logical operations onthe given two variables or values.OperatorsDescriptionandreturn true if both condition are true x and yorreturn true if either or bothcondition are truex or ynotreverse the conditionnot(a b)a 30b 20if(a 30 and b 20):print('hello')Output :helloVisit : python.mykvs.in for regular updatesExample

Operators continue6. Membership OperatorsThe membership operators in Python are used to validatewhether a value is found within a sequence such as such asstrings, lists, or tuples.OperatorsDescriptionExampleinreturn true if value exists in the sequence, else false.a in listnot inreturn true if value does not exists in the sequence, else false. a not in listE.g.a 22list [22,99,27,31]In Ans a in listNotIn Ans a not in listprint(In Ans)print(NotIn Ans)Output :TrueFalseVisit : python.mykvs.in for regular updates

Operators continue7. Identity OperatorsIdentity operators in Python compare the memory locations of twoExampleobjects. Operators Descriptionisreturns true if two variables point the same object, else falseis notreturns true if two variables point the different object, else falsee.g.a 34b 34if (a is b):print('both a and b has same identity')else:print('a and b has different identity')b 99if (a is b):print('both a and b has same identity')else:print('a and b has different identity')Output :both a and b has same identitya and b has different identityVisit : python.mykvs.in for regular updatesa is ba is not b

Operators Precedence :Operator continuehighest precedence to lowest precedence table. Precedence is used to decide ,whichoperator to be taken first for evaluation when two or more operators comes in anexpression.OperatorDescription**Exponentiation (raise to the power) -Complement, unary plus,minus(method names for the last two are @and -@)* / % //Multiply, divide, modulo and floor division -Addition and subtraction Right and left bitwise shift&Bitwise 'AND'td Bitwise exclusive OR' and regular OR' Comparison operators ! Equality operators % / // - * ** Assignment operatorsis is notIdentity operatorsin not inMembership operatorsnot or andLogical operatorsVisit : python.mykvs.in for regular updates

PunctuatorsUsed to implement the grammatical and structure of aSyntax.Following are the python punctuators.Visit : python.mykvs.in for regular updates

Barebone of a python program#function definitioncommentdef keyArgFunc(empname, emprole):print ("Emp Name: ", empname)Functionprint ("Emp Role: ", emprole)indentationreturn;A 20expressionprint("Calling in proper sequence")keyArgFunc(empname "Nick",emprole "Manager" )print("Calling in opposite sequence")statementskeyArgFunc(emprole "Manager",empname "Nick")A python program contain the following componentsa. Expressionb. Statementc. Commentsd. Functione. Block &n indentationVisit : python.mykvs.in for regular updates

Barebone of a python programa. Expression : - which is evaluated and produce result. E.g. (20 4) / 4b. Statement :- instruction that does something.e.ga 20print("Calling in proper sequence")c. Comments : which is readable for programmer but ignored by pythoninterpreteri. Single line comment: Which begins with # sign.ii. Multi line comment (docstring): either write multiple line beginning with # signor use triple quoted multiple line. E.g.‘’’this is myfirstpython multiline comment‘’’d. Functiona code that has some name and it can be reused.e.g. keyArgFunc in aboveprogramd. Block & indentation : group of statements is block.indentation at same levelcreate a block.e.g. all 3 statement of keyArgFunc functionVisit : python.mykvs.in for regular updates

VariablesVariable is a name given to a memory location. A variable canconsider as a container which holds value. Python is a type inferlanguage that means you don't need to specify the datatype ofvariable.Python automatically get variable datatype dependingupon the value assigned to the variable.Assigning Values To Variablename ‘python' # String Data Typesum None # a variable without valuea 23# Integerb 6.2# Floatsum a bprint (sum)Multiple Assignment: assign a single value to many variablesa b c 1 # single value to multiple variablea,b 1,2 # multiple value to multiple variablea,b b,a # value of a and b is swapedVisit : python.mykvs.in for regular updates

VariablesVariable Scope And Lifetime in Python Program1. Local Variabledef fun():x 8print(x)fun()print(x) #error will be shown2. Global Variablex 8def fun():print(x) # Calling variable ‘x’ inside fun()fun()print(x) # Calling variable ‘x’ outside fun()Visit : python.mykvs.in for regular updates

Dynamic typingData type of a variable depend/change upon the valueassigned to a variable on each next statement.X 25# integer typeX “python” # x variable data type change to string on justnext lineNow programmer should be aware that not to write like this:Y X / 5 # error !! String cannot be devidedVisit : python.mykvs.in for regular updates

ConstantsA constant is a type of variable whose value cannot be changed. It ishelpful to think of constants as containers that hold information whichcannot be changed lat

* Python is a case sensitive programming language. Thus, Rollnumber and rollnumber are two different identifiers in Python. Some valid identifiers : Mybook, file123, z2td, date_2, _no Some invalid identifier : Visit : python.mykvs.in for regular 2rno,break,my.book,data updates-cs. Identifiers-continue Some additional naming conventions 1. Class names start with an uppercase letter. All other .

Related Documents:

Python Basics.ipynb* Python Basics.toc* Python Basics.log* Python Basics_files/ Python Basics.out* Python_Basics_fig1.pdf* Python Basics.pdf* Python_Basics_fig1.png* Python Basics.synctex.gz* Python_Basics_figs.graffle/ If you are reading the present document in pdf format, you should consider downloading the notebook version so you can follow .

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

Python Programming - This is a textbook in Python Programming with lots of Practical Examples and Exercises. You will learn the necessary foundation for basic programming with focus on Python. Python for Science and Engineering - This is a textbook in Python Programming with lots of Examples, Exercises, and Practical Applications

CR ASH COURSE PY THON CR ASH COURSE 2ND EDITION ERIC MATTHES SHELVE IN: PROGRAMMING LANGUAGES/ PYTHON 39.95 ( 53.95 CDN) LEARN PYTHON— FAST! COVERS PYTHON 3.X Python Crash Course is the world's best-selling guide to the Python programming language. This fast-paced, thorough introduction to programming with Python will