0% found this document useful (0 votes)
9 views23 pages

Python Programming Fundamentals

This is the PDF of Python Programming of class 11th IP Students . this is the UNIT--2 Chapter--3 . This PDF is made by Bhavya Bansal
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)
9 views23 pages

Python Programming Fundamentals

This is the PDF of Python Programming of class 11th IP Students . this is the UNIT--2 Chapter--3 . This PDF is made by Bhavya Bansal
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
"The only way to learn a new programming language is by writing programs in Peta 1 Python Character Set 2 Tokens > Keywords » Identifiers / Variable > Literals / Values »> Delimiters »> Operators > Variable Concepts of L-Value and R-Value Comments Statement Clarity and simplicity of expression Blocks and Indentation The input ( ) function wlo si alu|alw The print ( ) function 10 Program Testing and Debugging 11 Errors and Exceptions 12 A) Compile — Time errors 13 A) Syntax Error 14 B) Semantic Errors Pages of 23 Unit Introduction to Python OTR are Carat teen te tte tei A character can represents any letter, digit, or any other sign. Following are some of the python character set. LETTERS AtoZandatoz Dy SPECIAL SYMBOLS 7 i 1 & #, under score(_} etc, Blank space, horizontal tab (- > ), carriage return , Newline, Ae es Form feed. Chita’ Python can process all ASCII and Unicode characters as part rer T NT Nei tds) of data or literals. The smallest individual unit in a program is known as token or lexical unit. Keywords are special identifiers with predefined meanings that cannot change. As these words have specific meaning for interpreter, they cannot be used for any other purpose. Page2 of 23, Unit Introduction to Python OTR are Carat teen te tte tei and | exec | not | continue if return | except| else as_| finally | or | def | import | try | class | lambda assert for_| Pass | del in| while | global | yield break | from | print elif is with raise class Identifiers are names given to identify something. Identifiers are fundamental building blocks of a program and are used as general terminology for the names given to different part of the program that is variables, objects, classes, functions, lists, dictionaries etc. INOTE: An ident Te eon keke el There are some rules you have to follow for naming identifiers: > An identifier starts with a letter A to Z or a to z or an underscore (_) 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, Sname and sname are two different identifiers in Python. Page3 of 23, Unit Introduction to Python OTR are Carat teen te tte tei Some valid identifiers: Mybook, file123, z2td, date_2,_no Some invalid variable name which produces syntax errors are as follows >>> 98Sep_sco syntaxError: invalid syntax because variable start with a digit, >>> Your Age ‘SyntaxError: invalid syntax because variable contains space >>> while ‘SyntaxError: invalid syntax because variable is a reserve word >>> myname@ _ syntaxError: invalid syntax because variable contains a special character Literals in Python can be defined as number, text, or other data that represent values to be stored in variables. The data items which never change their value throughout the program run. There are several kinds of literals: > String Literals > Numeric Literals > Boolean Literals > Special Literal None > Literal Collections Paged of 23, Unit Introduction to Python OTR are Carat teen te tte tei ls fo Numeric Literals : The numeric literals in Python can belong to any of the following different numerical types: int Used to integer value |Age = 20 float Used for real value Perc =98.5 ‘complex Used to part of complex number [x= 1+0i bool: It is logical literal |Used to logical /Boolean Result = True Text Literals: is a sequence of letters surrounded by either by single or double or triple quotes. String Literal Used to Unicode/Text/String __ [Name = Johni, fram bytes ASCII test/string "[Link]’ None Type : It is special|No - value None(and no other object) Used to implement the grammatical and structure of Syntax. johny" Delimiters are used in various areas of the Python language. They are used to build expressions, string literals, tuples, dictionaries or lists. Following are the python delimiters. DS ed feeb ceuel Grouping "/_# _|Punctuation Bit-wise assignment we Arthmetic assignment Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Pages of 23, Unit Introduction to Python OTR are Carat teen te tte tei Operators (Jeary Grouping Relational Operators a | ~ A cc > Bit-wise Operators Variable is an identifier whose value can change. For example variable age can have different value for different person. Variable name should be unique in a program. > Variables must always be assigned values before they are used in the program, otherwise it will lead to an error. > Wherever a variable name occurs in the program, the interpreter replaces it with the value of that particular variable. > Value of a variable can be string (for example, ‘A’, ‘Excellent’), number (for example 98.5) or any combination of alphanumeric (alphabets and numbers for example ‘B10’) characters. In Python, we can use an assignment statement to create new variables and assign specific values to them. The basic assignment statement has this form: = Here, is an identifier and is an expression. Pages of 23, Unit Introduction to Python OTR are Carat teen te tte tei For Example: Class = 12 # Variable created of numeric (integer) type Remark="Keepitup!" —_# Variable created of string type Percentage = 98.5 # Variable created of numeric (floating point) type Multiple Assignments: > Assigning same value to multiple variables: It will assign value 100 to all three variables x, y and z. > Assigning multiple value to multiple variables Pp, q, r= 10, 20, 30 It will assign the value order wise that is value 10 assign to variable p, value 20 assign to variable q and value 30 assign to variable r. Example: Write a Python program to find the sum of two numbers. numl = 100 num2 = 200 result = numl + num2 print (result) Output: 300 Example: Write a Python program to find the area of a triangle given that its base is 20 units and height is 40 units. base = 20 height = 40 Page? of 23, Unit Introduction to Python OTR are Carat teen te tte tei area = 0.5 *base * height print (area) Output: 400 > Lvalue refers to object to which you can assign value. It refers to memory location. It can appear LHS or RHS of assignment > Rvalue refers to the value we assign to any variable. It can appear on RHS of assignment For example: Numi = 10 # Numl is an L-value Num2 = 20 # Num2 is an L-value sum = Numl + Num2 # (Numl +Num2) is an R-value print (sum) Output: 30 > Comments are used to add a remark or a note in the source code. > Comments are not executed by interpreter. > In Python, a single line comment starts with # (hash sign). Python supports 3 ways to enter comments: Pages of 23, Unit Introduction to Python > Full line comment OTR are Carat teen te tte tei > Inline comment > Multiline comment Example: #This is program of volume of cylinder Example area = length*breadth # calculating area of rectangle Example: A. adding in the beginning of every line (using #) # Program name: area of circle # Date: 20/07/18 #Language : Python Example : B. Multiline comment (using ') triple quotes Created by: [Link] Date : 07/11/2020 Topic : Use of triple — qouted multi line string Pages of 23, Unit Introduction to Python > Itis a programming instruction that does something i.e. some action takes place, > Instructions that a Python interpreter can execute are called statements OTR are Carat teen te tte tei Example: print (“Welcome to python”) The above statement call print function Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) at the end of the line to continue the statement onto the next line. For example, # Assigns more values to the variables Mark1, Mark2, Mark3, Mark4, Mark5 = 70, 80, 87, 89, 78 Total = Mark1 +\ Mark2+\ Mark3 + \ Mark4 + \ MarkS print ("Total mark is:”, Total) Output: Total mark is: 404 Pagei0 of 23, Unit Introduction to Python OTR are Carat teen te tte tei NOTE: Statements contained within the [ ], { }, or ( ) brackets do not need to use the line continuation character. For example: ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday'] Parenthesis should be used to show the precedence of the operators and to enclose a sub-expression. This removes the ambiguities and misinterpretation leading to wrong outputs. Example, Z=(a*a)+(3*a*b)—(c*) / No two operators occur one after the othe For example, The operators should have ine operands before and after them. In case there are many sub-expressions_in an expression, then we eak it up into individual Root = (-b + D)/ X Paget of 23 Unit Introduction to Python ee Aaa rr b ebm et btn Ey A group of statements which are part of another statement or a function are called block or code — block or suite in Python. It’s best to use four spaces of indent for each code block level. If you use another number of spaces (2, 6, 8), that’s fine. The important thing is that all the code in the code block must have the same number of spaces. Note: You cannot unnecessarily indent a statement; Python will raise error for that. Consider the following Example: en erate Block of if statement with all its statements Tv eraes at same indentation level veal (ears NOC esa tc a) Example: Write a program to input a number (N) and find the sum of all numbers till N and its average. Also, find the sum of all even and odd numbers till N. The program also justifies the indentation for both looping and branching to find the correct result. Solution: Pageszof 23 ee Aaa rr b ebm et btn Ey Ey er yes) eugene ear a Cerca ers Sc Perens’ o lines body in true part eT ee reg] HES it part indentation SOS Unc cus Teves] jee else part indentation Ero est Eula eerie felt ears Berea Bear ae eT restre avg = sum /n; prey Rue eRe oes ae print ("The avg of natural numbers is =>", avg) Re ee ee me) NOR Cn cee ey) print ("The avg of even numbers is => ", avel) print ("The avg of odd numbers is =>", avg2) fin Ghecncerer cr reee errr r reer Secor ecerereay uF sduction to Python: ee Aaa rr b ebm et btn Ey Function indentation Indent the function body when a function starts. # Function to find sum of two numbers # Multiline in a block using function Function body statements result =a +b print("Sum of two numbers is:”, result) The input () function > The input () function prompts the user to enter data. > It accepts all user input as string. > The user may enter a number or a string but the input { ) function treats them as strings only. The syntax for input () is: input ({Prompt]) > Prompt is the string we may like to display on the screen prior to taking the input, and it is optional. For example, Pagei4 of 23 Unit Introduction to Python OTR are Carat teen te tte tei File Edit Format Run Options Window Help # Use of input () name = input("Enter your name: .") marks = input ("Enter your marks: ") print ("Your Name is print ("Your Marks i: Enter your marks Your Name is : Ahil Your Marks is: 98 Suppose we want to find sum of two numbers and the program i: Fe tat Fomat un Options Window Help # Use of input () #For example, suppose we want to #find sum of two numbers numl = input ("Enter first numbe: num2 = input ("Enter second number: *) sum = numi + num2 print ("The sum of ', numl, ' and ', num2, ' is ',sum) a Prnon365 Set Fle at_She_eug Options Window Heb Enter first number: 10 Enter second number: 20 The sun of 10 and 20 is 1020 Pages5 of 23 Unit Introduction to Python OTR are Carat teen te tte tei When we execute the above program, the program doesn’t add the two numbers together; it just puts one right after the other as 1020 The solution to the above problem is: Python offers two functions int () and float ( ) to be used with input () to convert the values received through input ( ) into int and float types. PXece yee eo wre Ker OR ow We need to convert an input string value into an integer using a int{ } Both input values are num? = int(input("Enter second number: ")) _Converted into integer type sum = num1 + num2 print (‘The sum of ', num1, ‘and ', num2, ’ is ';sum) function. num1 = int (input("Enter first number: ")) OUTPUT: Enter first number: 10 Enter second number: 30 The sum of 10 and 30 is 40 Accept an fl at input from User You need to convert user input to the float number using the float() function as we did for the integer value. oat (input("Enter first number: num2 = float(input("Enter second number: sum = num1 + num2 Both input values are converted into float type print (‘The sum of ', num1, ' and ', num2, ‘is 'sum) OUTPUT: Enter first number: 10.5 Enter second number: 30.5 Unit luction to Python OTR are Carat teen te tte tei The sum of 10.5 and 30.5 is 41.0 In Python, we can accept two or three values from the user in one input{) call. om i MON ER ag oT ey Rn TRO 2 ES) 155, Marks = input ("Enter your Name, Class, Marks separated by space: ")-split() petails: ", name, Class, Marks) oot at Enter your Name, Class, Marks separated by space: Ashaz 4th 99 User Details: ashaz 4th 99 | > The print () function allows you to print out the value of a variable and strings in parenthesis. The general form of print () function is: print () print (value/expr) print (value, ...., sep="', end="\n’, file=[Link], flush=False) > The print () function prints a blank line. For example: >>> print () Page37 of 23 Unit Introduction to Python OTR are Carat teen te tte tei > The print () function prints the value of variable or expression. For example: >>> N1=20 >>> N2 = 30 >>> Sum = N1+N2 >>> print (Sum) # prints a value 50 >>> print (N1+N2) # prints a value of an expression i.e., N1+N2 50 >>> Ver = 3.6 >>> Prog = "Python" >>> print (Prog, Ver) # prints two values separated with comma (,) Python 3.6 > The print() function contains number of options. You can use either one, two or all at once. For example: = Print a message. >>> print ("The sum is") # prints a message The sum is >>> print ("My Python") Pages8 of 23, Unit Introduction to Python OTR are Carat teen te tte tei My Python ~ Print a value, message or both message and values and vice versa. >>> print ("The sum is", Sum) _ # prints a message with a value The sum is 50 >>> print (Sum, “is the sum of", N1, “and", N2) # print is alternate way 50 is the sum of 20 and 30 > The sep separator is used between the values. It defaults into a space character. For example: >>> print (10,20,30,40,sep="*') # prints a separator * 10*20*30*40 > After all values are printed, end is printed. It defaults into a new line. >>> print (10, 20, 30, 40, sep = '*', end = '@') # Anew end is assigned @ 10*20*30*40@ Let us take other examples, where a print() function can output multiple things at once, each item separated by a comma. # The following code prints: The answer to 10+10 is 20 >>>print (" The answer to 10+10is" , 10410) # The following code prints: The answer to 10+10 is 10+10 >>>print (" The answer to 10+10 is", "10+10") 1 Pagei9 of 23 Unit Introduction to Python OTR are Carat teen te tte tei # The following code does not work and product Invalid Syntax because the comma (,) is inside the quotation marks and not outside. >>>print (" The answer to 10+10 is ,” 10+10) > print () with Concatenate Operator (+) The print() function can print two strings either using comma (,) operator, or a concatenate operator (+). For example, >>> print ("My name is Ahil", "Class-XI A.") # Print with space separator. My name is Ahil Class-X! A. Similarly, by using concatenate operator (+), the print() function is: >>> print ("My name is Ashaz” + "Class-XI B.") # Print without separator. My name is AshazClass-XI A. The general Syntax: % [Link] type-char For example: a=2.45567 print("%.2F" %a) Page200f 23, Unit Introduction to Python A programmer can make mistakes while writing a program, and hence, OTR are Carat teen te tte tei the program may not execute or may generate wrong output. Program Testing: Program Testing means running the program, executing all its instructions or functions and testing the logic by entering sample data in order to check the output. Debugging: Debugging is the process of finding and correcting the errors in the program code. An errors and exceptions both disrupt a program and stop its execution. But Errors and Exceptions are not the same. Errors ina program: An error, also termed as ‘a bug’, is anything in the code that prevents a program from compiling and running correctly. Type of errors: There are two types of errors: 1) Compile — time Errors 2) Runtime Errors Paget of 23 Unit Introduction to Python OTR are Carat teen te tte tei im pile — Time error Errors that occur when you violate the rules of writing syntax are known as compile — time errors. Compiled time errors are broadly classified into two categaries. A) Syntax error: ld Every programming language has its own rules and regulations (syntax). ld If we overcome the particular language rules and regulations, the syntax error will appear (i.e. an error of language resulting from code that does not conform to the syntax of the programming language). > It can be recognized during compilation time. Example ae while a < 10 azati print (a) In the above statement, the second line is not correct. Since the while statement does not end with ‘:’. This will flash a syntax error. B) Semantic Errors: Dit refers the set of rules which give the meaning of statement. Page 22 of 23 Unit Introduction to Python OTR are Carat teen te tte tei For Example: X+Y=A will result in a semantically error as an expression cannot come on the left side of an assignment statement. Run i Errors that occur during the execution of a program are known as run time errors. Logical error: D It is a type of runtime error that may simply produce the wrong output or may cause a program to crash while running. D> Itis an error in a program's source code that results in incorrect or unexpected result. > The logical error might only be noticed during runtime, because it is often hidden in the source code and are typically harder to find and debug. a = 100 while a < 10: az=aei print (a) In the above example, the while loop will not execute even a single time, because the initial value of ‘a’ is 100. Page23 of 23,

You might also like