python case study and need a sample draft to help me learn.
step 1 ppython
Requirements:
PYTHON PROGRAMMING UNIT-I OVERVIEW OF PYTHON 1. Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. 2. It uses English keywords frequently whereas the other languages use punctuations. 3. It has fewer syntactical constructions than other languages. Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is like PERL and PHP. Python is Interactive: You can sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects. Python is a Beginner’s Language: Python is a great language for the beginner level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. HISTORY OF PYTHON 1. Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. 2. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, Smalltalk, and Unix shell and other scripting languages. 3. Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL). 4. Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python 2.7.11 is the latest edition of Python 2. 5. Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2. Python 3.10.2 is the latest version of Python 3. PYTHON FEATURES Python’s features include Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows a student to pick up the language quickly. Easy-to-read: Python code is more clearly defined and visible to the eyes. Easy-to-maintain: Python’s source code is fairly easy-to-maintain. A broad standard library: Python’s bulk of the library is very portable and cross platform compatible on UNIX, Windows, and Macintosh. Interactive Mode: Python has support for an interactive mode, which allows interactive testing and debugging of snippets of code. Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
PYTHON PROGRAMMING Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases: Python provides interfaces to all major commercial databases. GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable: Python provides a better structure and support for large programs than shell scripting. GETTING STARTED WITH PYTHON PROGRAMMING Guido van Rossum invented the Python programming language in the early 1990s. Python is a high-level, general-purpose programming language for solving problems on modern computer systems. The language and many supporting tools are free, and Python programs can run on any operating system. You can download Python, its documentation, and related materials from www.python.org. Running Code in the Interactive Shell Python is an interpreted language, and you can run simple Python expressions and statements in an interactive programming environment called the shell. The easiest way to open a Python shell is to launch the IDLE (Integrated Development Environment). This is an integrated program development environment that comes with the Python installation. When you do this, a window named Python Shell opens. Figure 1-6 shows a shell window on macOS. A shell window running on a Windows system, or a Linux system should look similar, if not identical, to this one. Note that the version of Python appearing in this screenshot shown in this book assumes that you will use Python 3 rather than Python 2. There are substantial differences between the two versions, and many examples used in this book will not work with Python Figure 1-1 Python shell window A shell window contains an opening message followed by the special symbol >>>, called a shell prompt. The cursor at the shell prompt waits for you to enter a Python command. When you enter an expression or statement, Python evaluates it and displays its result, if there is one, followed by a new prompt. The next few lines show the evaluation of several expressions and statements.
PYTHON PROGRAMMING >>> 3 + 4 # Simple arithmetic 7 >>> 3 # The value of 3 is 3 >>> “Python is really cool!” # Use a string for text ‘Python is really cool!’ >>> name = “Ken Lambert” # Give a variable a value >>> name # The value of name is ‘Ken Lambert’ >>> “Hi there, ” + name # Create some new text ‘Hi there, Ken Lambert’ >>> print(‘Hi there’) # Output some text Hi there >>> print(“Hi there,”, name) # Output two values Hi there, Ken Lambert Note the use of colors in the Python code. The IDLE programming environment uses color-coding to help the reader pick out different elements in the code. In this example, the items within quotation marks are in green, the names of standard functions are in purple, program comments are in red, and the responses of IDLE to user commands are in blue. The remaining code is in black. Table 1-1 lists the color-coding scheme used in all program code. Table 1-1 Color-coding of Python program elements in IDLE The Python shell is useful for experimenting with short expressions or statements to learn new features of the language, as well as for consulting
PYTHON PROGRAMMING documentation on the language. To quit the Python shell, you can either select the window’s close box or press the Control1D key combination. PROGRAM DEVELOPMENT LIFE CYCLE The Program Development Cycle (PDC) contains the following Phases 1. Problem Definition 2. Program Design 3. Coding 4. Maintenance 1.Problem Definition: Here the formal definition of the problem is stated. This stage gives thorough understanding of the problem, and all the related factors such as input, output, processing requirements, and memory requirements etc. 2.Program Design: Once the problem and its requirements have been identified, then the design of the program will be carried out with tools like algorithms and flowcharts. i. An Algorithm is a step-by-step process to be followed to solve the problem. It is formally written using the English language. ii. The flowchart is a visual representation of the steps mentioned in the algorithm. This flowchart has some set of symbols that are connected to perform the intended task. The symbols such as Square, Dimond, Lines, and Circles etc. are used. 3.Coding: Once the design is completed, the program is written using any programming language such as C, C++, Python, and Java etc. The Coding usually takes very less time, and syntax rules of the language are used to write the program. a. Debugging: At this stage the errors such as syntax errors in the programs are detected and corrected. This stage of program development is an important process. Debugging is also known as program validation.
PYTHON PROGRAMMING b. Testing: The program is tested on a number of suitable test cases. The most insignificant and the most special cases should be identified and tested. c. Documentation: Documentation is a very essential step in the program development. Documentation helps the users and the who actually maintain the software. 4.Maintenance: Even after the software is completed, it needs to be maintained and evaluated regularly. In software maintenance, the programming team fixes program errors and updates the software when new features are introduced. INPUT, PROCESSING, AND OUTPUT • Most useful programs accept inputs from some source, process these inputs, and then finally output results to some destination. • In terminal-based interactive programs, the input source is the keyboard, and the output destination is the terminal display. • The Python shell itself takes inputs as Python expressions or statements. Its processing evaluates these items. Its outputs are the results displayed in the shell. • Python provides numerous built-in functions that are readily available to us at the Python prompt. • Some of the functions like input() and print() are widely used for standard input and output operations respectively. Reading Input from the Keyboard: In python input () is used to read the input from the keyboard dynamically. By default, the value of the input function will be stored as a string. Syntax: Variable name =input(‘prompt’) Example: Name =input (“Enter Employee Name “) salary =input (“Enter salary “) company =input (“Enter Company name “) print(“\n”) print(“Printing Employee Details”) print(“Name”,”Salary”,”Company”) print(name, salary, company) Output: Enter Employee Name John Enter salary 12000 Enter Company name Google Printing Employee Details Name Salary Company Jon 12000 Google
PYTHON PROGRAMMING Accept an numeric input from User: To accept an integer value from a user in Python. We need to convert an input string value into an integer using a int() function. Example: first_number = int(input(“Enter first number “)) to convert an input string value into a float using a float() function as shown below. Example: first_number = float(input(“Enter first number “)) # program to calculate addition of two input numbers a=int(input(“Enter first number “)) b=int(input(“Enter second number “)) print(“First Number:”,a) print(“Second Number:”,b) c = a+b print(“Addition of two number is: “, c) Enter first number 20 Enter second number 40 First Number: 20 Second Number: 40 Addition of two number is: 60 Get multiple input values from a user in one line: In Python, we can accept two or three values from the user in one input() call. Example: In a single execution of the input() function, we can ask the user his/her name, age, and phone number and store it in three different variables name, age, phone =input(“Enter your name, Age, phone Percentage separated by space “).split() print(“\n”) print(“User Details: “, name, age, phone) Output: Enter your name, Age, Percentage separated by space John 26 75.50 User Details: John 26 75.50 Performing Calculations(Processing) Computers are great at math problems! How can we tell Python to solve a math problem for us? In this we use numbers in Python and the special symbols we use to tell it what kind of calculation to do. Example-1: 1. print(2+2) 2. print(“2″+”2”) Output: 4 22 Question: Why does line 2 give the wrong Answer?
PYTHON PROGRAMMING Answer: When we do math in Python, we can’t use strings. We have to use numbers. The first line uses two numbers. Both are integers (called int in Python). Calculations in Python follow the Order of Operations, which is sometimes called PEMDAS. PEMDAS: Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right). print((6 – 2) * 5) 20 print(6 – 2 * 5) -4 Subtraction: print(2 – 2) Multiplication: print(2 * 2) Division: print(2 / 2) The first statement is evaluated by Python like this: 1. (6 – 2) * 5 Parentheses first 2. 4 * 5 3. 20 The second statement is evaluated like this: 1. 6 – 2 * 5 Multiplication first 2. 6 – 10 Example-2: The modulo operator (%) finds the remainder of the first number divided by the second number. Run: print(12 % 10) 12 / 10 = 1 with a remainder of 2. Integer division (//) is like normal division, but it rounds down if there is a decimal point. Run: print(5 // 2) 5 / 2 = 2.5, which is rounded down to 2 Exponentiation (**) raises the first number to the power of the second number. Run: print(3 ** 2) This is the same as 32 Example-2: Remember, input() returns a string, and we can’t do math with strings. Fortunately, we can change strings into ints like so: two = “2” two = int(two) print(two + two) If you need to work with a decimal point, you can change it to a float instead:
PYTHON PROGRAMMING two = float(two) Example-3:one_up_level = 1 a1 = input(“How many seconds does it take you to run the 100 meter dash?”) a1 = int(a1) print(“That’s cool. I can do it in”, a1 – one_up_level, “seconds though. And I don’t even have legs, sooooo…”) a2 = input(“But what about your GPA? I’m sure that’s pretty good, eh? (Enter your GPA)”) a2 = float(a2) print(“Alright. Mine was”, a2 + one_up_level) print(“Not that it matters, lol”) Python Output Using print () function We use the print() function to output data to the standard output device (screen). We can also output data to a file print() function: The print() function prints the given object to the standard output device (screen) or to the text stream file syntax of print() is: print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) objects – object to be printed. * indicates that there may be more than one object sep – objects are separated by sep. Default value: ‘ ‘ end – end is printed at last by default it has \n file – must be an object with write(string) method. If omitted it, sys.stdout will be used which prints objects on the screen. flush – A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False Example 1: print(‘This sentence is output to the screen’) Output: This sentence is output to the screen Example 2: a = 5 print(‘The value of a is’, a) Output: The value of a is 5 Example 3: print(“Python is fun.”) a = 5 # Two objects are passed print(“a =”, a) b = a # Three objects are passed print(‘a =’, a, ‘= b’) Output: Python is fun. a= 5 a = 5 = b Case 1:print without any arguments print(‘St.Ann’s College of Engineering & Technology’)
PYTHON PROGRAMMING print () # we have not passed any argument by default it takes new line and create one line blank space print(‘Computer Science Engineering’) Output: St.Ann’s College of Engineering & Technology Computer Science Engineering Case 2:print function with string operations (with arguments) 1.print(‘helloworld’) Output: helloworld 2.print(‘hello\nworld’) Output: hello world 3.print(‘hello\tworld’) Output: hello world 4. # string concatenation both objects are string only print(‘tec’ + ‘cse’) Output: teccse print(‘tec’ , ‘cse’) Output: tec cse 5.# repeat string into number of times print(5*’cse’) Output: csecsecsecsecse print(5*’cse\n’) Output: cse cse cse cse cse print(5*’cse\t’) Output: cse cse cse cse cse Case 3:print function with any number of arguments 1. (a) print(‘values are :’,10,20,30) Output: values are : 10 20 30 (b) a,b,c=10,20,30 print(‘values are:’,a,b,c) Output: values are : 10 20 30 2. print function with “sep” attribute: This is used to separate objects By default, value of sep is empty space(sep=’ ’) >>>print(‘values are:’,10,20,30,sep=”:”) Output: values are::10:20:30 >>>print(‘values are:’,10,20,30,sep=”–“) Output: values are:–10–20—30 Case 4: print statement with end attribute • The end key of print function will set the string that needs to be appended when printing is done. • By default, the end key is set by newline character (By default, attribute end =’\n’ in print function). So after finishing printing all the variables, a newline character is appended. Hence, we get the output of each print statement in different line. But we will now overwrite the newline character by any character at the end of the print statement.
PYTHON PROGRAMMING Example-1: print(‘Tirumala’) # in this statement by default end =’\n’ so it takes new line print(‘rajani’) # in this statement by default end =’\n’ so it takes new line print(‘devansh’) # in this statement by default end =’\n’ so it takes new line Output: Tirumala rajani devansh Example-2: print (‘Tirumala’, end=’$’) print (‘rajani’ ,end=’*’) print(‘devansh’) Output: Tirumala$rajani*devansh Case 5: print function with sep and end attribute Example print(19,20,30,sep=’:’,end=’$$$’) print(40,50,sep=’:’) print(70,80,sep=’:’,end=’&&&’) print(90,100) Output: 19:20:30$$$40:50 70:80&&&90 100 OUTPUT FORMATTING There are several ways to present the output of a program, data can be printed in a human readable form, or written to a file for future use. Sometimes user often wants more control the formatting of output than simply printing space-separated values. There are several ways to format output. 1.Formatting output using String modulo operator (%): Syntax: print (‘formatted string’ %( variable list)) The % operator can also be used for string formatting. string modulo operator ( % ) is still available in Python(3.x) and user is using it widely. Example 1 # Python program showing how to use string modulo operator (%) to print program output # print integer and float value print (“CSE: % 2d, Portal: % 5.2f”%(1, 05.333)) # print integer value print (“Total students: % 3d, Boys: % 2d”%(240, 120)) # print octal value print (“% 7.3o”%(25)) # print exponential value print (“% 10.3E”%(356.08977)) Output :
PYTHON PROGRAMMING CSE: 1, Portal: 5.33 Total students: 240, Boys: 120 031 3.561E+0 Example 2 (a) a=6 print(‘a value is =%i’ %a) Output: a value is =6 (b) a=6;b=7;c=8 print(‘a value is =%i and b=%f and c=%i’ %(a,b,c)) Output: a value is =6 and b=7.000000 and c=8 2. print function with replacement operator {}or format function str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting. Example:1 Name= ‘John’ Salary=1000 print(‘hello my name is {} and my salary is {}’.format(Name,Salary)) Output: hello my name is John and my salary is 1000 Example:2 name=’John’ salary=1000 print(‘hello my name is “{}” and my salary is “{}”‘.format(name,salary)) Output: : hello my name is “John” and my salary is “1000” *********we can also use index values and print the output********* Example: 3 name=’John’ salary=1000 print(‘hello my name is “{0}” and my salary is “{1}”‘.format(name,salary)) Output: hello my name is “John” and my salary is “1000” Example: 4 print(‘hello my name is “{0}” and my salary is “{1}”‘.format(salary,name)) Output: hello my name is “1000” and my salary is “john” ***** **** we can also use variables in the reference operator********* Example: 5 print (‘hello my name is “{n}” and my salary is “{s}”‘. format (n=name, s=salary)) Output: hello my name is “john” and my salary is “1000” Example: 6 print (‘hello my name is “{n}”and my salary is { s}’.format(s=salary,n=name)) Output: hello my name is “john” and my salary is “1000” EDITING, SAVING, AND RUNNING A SCRIPT
PYTHON PROGRAMMING While it is easy to try out short Python expressions and statements interactively at a shell prompt, it is more convenient to compose, edit, and save longer, more complex programs in files. We can then run these program files or scripts either within IDLE or from the operating system’s command prompt without opening IDLE. 1. To compose and execute programs in this manner, you perform the following steps: 2. Select The option New Window from the File menu of the shell window. In the new window, enter Python expressions or statements on separate lines, in the order in which you want Python to execute them. 3. At any point, you may save the file by selecting File/Save. If you do this, you should use a . py extension. For example, your first program file might be named myprogram.py. 4. To run this file of code as a Python script, select Run Module from the Run menu or press the F5 key. The command in Step 4 reads the code from the saved file and executes it. If Python executes any print functions in the code, you will see the outputs as usual in the shell window. If the code requests any inputs, the interpreter will pause to allow you to enter them. Otherwise, program execution continues invisibly behind the scenes. When the interpreter has finished executing the last instruction, it quits and returns you to the shell prompt. Figure 1-5 shows an IDLE window containing a complete script that prompts the user for the width and height of a rectangle, computes its area, and outputs the result: Figure 1-5:Python script in an IDLE window When the script is run from the IDLE window, it produces the interaction with the user in the shell window shown in Figure 1-6.
PYTHON PROGRAMMING Figure 1-6: Interaction with a script in a shell window Behind the Scenes: How Python Works Figure 1-7:Steps in interpreting a Python program Steps in interpreting a Python program 1. The Python expression or statement, also called the source code, and verifies that it is well formed. In this step, the interpreter behaves like a strict English teacher who rejects any sentence that does not adhere to the gram- mar rules, or syntax, of beat language. As soon as the interpreter encounters such an error, it halts translation with an error message. 2. If a Python expression is well formed, the interpreter then translates it to an equivalent form in a low-level language called byte code. when D interpreter runs a script, it completely translates it to byte code.
PYTHON PROGRAMMING 3. This byte code is next sent to another software component, called the Python virtual machine (PVM), where it is executed. If another error occurs during this step execution also halts with an error message. PYTHON VARIABLES 1. Variable is not “statically typed”. We do not need to declare variables before 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. 2. The value stored in a variable can be changed during program execution. 3. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. Rules for creating variables in Python: 1. A variable name must start with a letter or the underscore character. 2. A variable name cannot start with a number. 3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). 4. Variable names are case-sensitive (name, Name and NAME are three different variables). 5. The reserved words(keywords) cannot be used naming the variable. Let’s see the simple variable creation: #!/usr / bin / python # An integer assignment age = 45 # A floating point salary = 1456.8 # A string name = “John” print(age) print(salary) print(name) Output: 45 1456.8 John Let’s see how to declare the variable and print the variable. # declaring the var Number = 100 # display print( Number) Output: 100 Re-declare the Variable: We can re-declare the python variable once we have declared the variable already.
PYTHON PROGRAMMING # declaring the var Number = 100 # display print(“Before declare: “, Number) # re-declare the var Number = 120.3 print(“After re-declare:”, Number) Output: Before declare: 100 After re-declare: 120.3 Assigning a single value to multiple variables: Also, Python allows assigning a single value to several variables simultaneously with“=”operators. For example: #!/usr / bin / python a = b = c = 10 print(a) print(b) print(c) Output: 10 10 10 Assigning different values to multiple variables: Python allows adding different values in a single line with “,” operators. #!/usr / bin / python a, b, c = 1, 20.2, “Welcome to SACET” print(a) print(b) print(c) Output: 1 20.2 Welcome to SACET Can we use the same name for different types? If we use the same name, the variable starts referring to a new value and type. #!/usr / bin / python a = 10 a = ” Welcome to SACET ” print(a) Output Welcome to SACET How does + operator work with variables? #!/usr / bin / python a = 10 b = 20
PYTHON PROGRAMMING print(a+b) a = “Welcome To” b = “SACET” print(a+b) Output 30 Welcome to SACET OPERATORS AND EXPRESSIONS An expression in Python is a block of code that produces a result or value upon evaluation. A simple example of an expression is 6 + 3. An expression can be broken down into operators and operands. Operators are symbols which help the user or command computer to perform mathematical or logical operations. In the expression 6 + 3, the ‘+’ acts as the operator. An operator requires data to operate and this data is called operand. In this example, 6 and 3 are the operands. ARITHMETIC OPERATORS There are two types of arithmetic operators in Python, viz. binary and unary unary Operators Unary arithmetic operators perform mathematical operations on one operand only. The ‘+’ and ‘-’ are two unary operators. The unary operator minus (-) produces the negation of its numeric operand. The unary operator plus (+) returns the numeric operand without change. Table 3.2 gives the details of unary operators.
PYTHON PROGRAMMING Examples of Unary Operators >>> x=-5 #Negates the value of X >>> x -5 >>> x=+6 #Returns the numeric operand, i.e. 6, without any change >>> x 6 Some More Complex Examples of Unary Operators >>> +-5 -5 In the above expression +-5, the first ‘+’ operator represents the unary plus operation and the second ‘-’ operator represents the unary minus operation. The expression +-5 is equivalent to +(-(5)), which is equal to -5. >>> 1–3 #Equivalent to 1-(-3) 4 >>> 2—3 #Equivalent to 2-(-(-3)) -1 >>> 3+–2 #Equivalent to 3+(-(-2)) 5 Binary Operators Binary operators are operators which require two operands. They are written in infix form, i.e. the operator is written in between two operands. The Addition (+) Operator The ‘+’ operator in Python can be used with binary and unary form. If the addition operator is applied in between two operands, it returns the result as the arithmetic sum of the operands. Some examples of addition operators executed in Python interactive mode are given as follows: Example >>> 4+7 #Addition 11 >>>5+5 #Addition 10
PYTHON PROGRAMMING Table :Addition operator The Subtraction (-) Operator The ‘-’ operator in Python can be used with binary and unary form. If the subtraction operator is applied in between two operands, the result is returned as the arithmetic difference of the operands. Some examples of subtraction operators executed in Python interactive mode are given as follows: Example >>> 7-4 #Subtraction 3 >>>5-2 #Subtraction 3 Table explains the syntax and semantics of the subtraction operator in Python, using its three numeric types, viz. int, float and complex. Table : Subtraction operator The Multiplication (*) Operator The ‘*’ operator in Python can be used only with binary form. If the multiplication operator is applied in between two operands, it returns the result as the arithmetic product of the operands. Some examples of multiplication operators executed in Python interactive mode are given as follows: Example >>> 7*4 #Multiplication 28 >>>5*2 #Multiplication
PYTHON PROGRAMMING 10 Table explains the syntax and semantics of the multiplication operator in Python, using its three numeric types, viz. int, float and complex. The Division (/) Operator The ‘/’ operator in Python can be used only with binary form. If the division operator is applied in between two operands, it returns the result as the arithmetic quotient of the operands. Some examples of division operators executed in Python interactive mode are given as follows: Example >>> 4/2 #Division 2.0 >>> 10/3 3.3333333333333335 #Division Table 3.6 explains the syntax and semantics of the division operator in Python, using its three numeric types, viz. int, float and complex. The Floor Division (//) Operator The ‘//’ operator in Python can be used only with binary form. If the floor division operator is applied in between two operands, it returns the result as the arithmetic quotient of the operands. Some examples of floor division operators executed in Python interactive mode are given as follows: Example >>> 4//2 # Floor Division 2
PYTHON PROGRAMMING >>> 10//3 3 #Floor Division Table 3.7 explains the syntax and semantics of the floor division operator in Python, using its numeric types, viz. int and float. The Modulo (%) Operator When the second number divides the first number, the modulo operator returns the remainder. The % modulo operator is also known as the remainder operator. If the remainder of x divided by y is zero then we can say that x is divisible by y or x is a multiple of y. In the above example, 14 % 4 returns 3 as the remainder. Thus, the left-side operand, i.e. 14 is the dividend and the right-side operand, i.e. 4 is the divisor. Some more examples of the modulo operator executed in Python interactive mode are given below. Example >>> 10 % 4 # 10 is divided by 4 returns remainder as 2 2 >>> 13%5 3 Table 3.8 explains the syntax and semantics of the modulo (%) operator in Python, using its numeric types, viz. int and float.
PYTHON PROGRAMMING The Exponent ** Operator The ‘**’ exponent operator is used to calculate the power or exponent of a number. To compute xY (X raised to Y), the expression is written as X**Y. The exponent operator is also called power operator. Example >>> 4**2 #Calculate Square of a Number 4 16 >>> 2**3 #Calculate Cube of a Number 2 8 BITWISE OPERATORS Python has six bitwise operators for bitwise manipulation. The bitwise operator permits a programmer to access and manipulate individual bits within a piece of data. Table 3.12. shows various bitwise operators supported by Python. The Bitwise and (&) Operator This operator performs AND operation on input bits of numbers. The Bitwise AND operator is represented as ‘&’. The ‘&’ operator operates on two operands bit-by-bit. Table 3.13. explains the AND operator. We can conclude from this table that the output is obtained by multiplying the input bits. Example of AND Operator >>> 1 & 3 1 # The bitwise & operator on 1 and 3 returns 1
PYTHON PROGRAMMING >>> 5 & 4 4 # The bitwise & operator on 5 and 4 returns 4 Working of the bitwise operator is given as follows: the Bitwise Or (|) Operator This operator performs bitwise OR operation on the numbers. The bitwise OR operator is represented as ‘|’. It also operates on two operands and the two operands are compared bit-by-bit. Table 3.14 explains the ‘|’ (OR) operator. Table: Bitwise OR operator We can conclude from this table that the output is obtained by adding the input bits. Examples of Bitwise ‘|’ (OR) Operator >>> 3 | 5 7 # The bitwise | operator on 3 and 5 returns 7 >>> 1 | 5 5 # The bitwise | operator on 1 and 5 returns 5
PYTHON PROGRAMMING the Bitwise xOr (^) Operator This operator performs bitwise exclusive or XOR operation on the numbers. It is represented as ‘^’. The ‘^’ operator also operates on two operands and these two operands are compared bit-by-bit. Table explains the ‘^’ (XOR) operator. We can conclude from this table that the output is logic one when one of the input bits is logic one. Examples of Bitwise XOR (^) Operator >>> 3 ^ 5 6 # The bitwise ^ operator on 3 and 5 returns 6 >>> 1 ^ 5 4 # The bitwise ^ operator on 1 and 5 returns 4 Working of the bitwise XOR (‘^’) operator is given as follows:
PYTHON PROGRAMMING the right shift (>>) Operator The right shift operator is represented as >>. It also needs two operands. It is used to shift bits to the right by n position. Working of the right shift operator (>>) is explained as follows: Example >>>4 >> 2 # The input data 4 is to be shifted by 2 bits towards the right side 1 >>>8>>2 2 Explanation the Left shift (<<) Operator The left shift operator is represented as <<. It also needs two operands. It is used to shift bits to the left by N position. The working of the left shift operator is given as follows:
PYTHON PROGRAMMING Example >>> 4 << 2 # The input data 4 is to be shifted by 2 bits towards the left side 16 >>> 8 << 2 # The input data 8 is to be shifted by 2 bits towards the left side 32 Explanation Identity operators x1 , y1 = 5 ,5 x2 , y2 = "cse",”cse” x3 , y3= [1,2,3],[1,2,3] print(id(x1)) #20935504 print(id(y1)) #20935504 print(x1 is y1) print(x1 is not y1) print(id(x2)) #21527296 print(id(y2)) #21527296 print(x2 is y2) print(x2 is not y2) print(id(x3)) #45082264 print(id(y3)) #45061624 print(x3 is y3) a=10 b=15 x=a y=b z=a print(x is y) print(x is a) print(y is b) print(x is not y) print(x is not a)
PYTHON PROGRAMMING print(x is z) Membership operators: in: "in" operator return true if a character or the entire substring is present in the specified string, otherwise false. not in: "not in" operator return true if a character or entire substring does not exist in the specified string, otherwise false. Example: str1="ramuit" str2="tirumalacse" str3="ramu" str4="tirumala" print(str3 in str1) # True print(str4 in str2) # True print(str3 in str2) # False print("ratan" in "ratanit") #true print("ratan" in "durgasoft") #False print(str3 not in str1) # False print(str4 not in str2) # False print(str3 not in str2) # True print("ratan" not in "ratanit") # false print("ratan" not in "anu") # true PYTHON COMMENTS Comments are descriptions that help programmers better understand the intent and functionality of the program. It is completely ignored by the Python interpreter. Single-Line Comments in Python: In Python, we use the hash symbol # to write a single-line comment. Example 1: Writing Single-Line Comments # printing a string print('Hello world') Output: Hello world Here, the comment is: # printing a string. This line is ignored by the Python interpreter. Everything that comes after # is ignored. So, we can also write the above program in a single line as: print('Hello world') #printing a string The output of this program will be the same as in Example 1. The interpreter ignores all the text after #. Multi-Line Comments in Python: We can use # at the beginning of each line of comment on multiple lines. Example 2: Using multiple # # it is a multiline # comment Here, each line is treated as a single comment and all of them are ignored.
PYTHON PROGRAMMING In a similar way, we can use multiline strings (triple quotes) to write multiline comments as shown below. The quotation character can either be ' or ". ''' I am a multiline comment! ''' print("Hello World") STRINGS ASSIGNMENT AND COMMENT Data types a data type consists of a set of values and a set of operations that can be performed on those values. A literal is the way a value of a data type looks to a program- the programmer can use a literal in the program to mention the data value. When the Python interpreter evaluates a literal, the value it returns is simply that literal. Table 1-2 shows example literals of several Python data types. Table 1-2 Literals for some Python data types The first two data types listed in Table 1-2, int and float, are called numeric data types, because they represent numbers. String: String is a sequence of characters. String Literals In Python, a string literal is a sequence of characters enclosed in single or double quotation marks. The following session with the Python shell shows some example strings: >>> ‘Hello there!’ ‘Hello there!’ >>> “Hello there!” ‘Hello there!’ >>> ” ”
PYTHON PROGRAMMING >>> “” ” The last two string literals (” and “”) represent the empty string. Although it contains no characters, the empty string is a string nonetheless. Note that the empty string is different from a string that contains a single blank space character, ” “. Double-quoted strings are handy for composing strings that contain single quotation marks or apostrophes. Here is a self-justifying example: >>> “I’m using a single quote in this string!” “I’m using a single quote in this string!” >>> print(“I’m using a single quote in this string!”) I’m using a single quote in this string! Note that the print function displays the nested quotation mark but not the enclosing quotation marks. A double quotation mark can also be included in a string literal if one uses the single quotation marks to enclose the literal. Escape Sequences The newline character \n is called an escape sequence. Escape sequences are the way Python expresses special characters, such as the tab, the newline, and the backspace (delete key), as literals. Table 2-3 lists some escape sequences in Python. Table 1-3 Some escape sequences in Python Because the backslash is used for escape sequences, it must be escaped to appear as a literal character in a string. Thus, print(‘\\’) would display a single \ character. String Concatenation You can join two or more strings to form a new string using the concatenation
PYTHON PROGRAMMING operator +. Here is an example: >>> “Hi ” + “there, ” + “Ken!” ‘hi there ken’ The * operator allows you to build a string by repeating another string a given number of times. The left operand is a string, and the right operand is an integer. For example, if you want the string “Python” to be preceded by 10 spaces, it would be easier to use the * operator with 10 and one space than to enter the 10 spaces by hand. The next session shows the use of the * and + operators to achieve this result: >>> ” ” * 10 +Python” ‘ Python’ PYTHON CORE DATA TYPES There are five Data Types in Python 1. numeric 2. dictionary 3. Boolean 4. set 5. sequence integer From simple Mathematics, we know that an integer is a combination of positive and negative numbers including (zero) 0. In a program, integer literals are written without commas and a leading minus sign to indicate a negative value. Following is an example of simple integer literals displayed in Python interactive mode Example >>> 10 10 >>> 1220303 1220303 >>> -87 -87
PYTHON PROGRAMMING Integer literals can be octal or hexadecimal in format. All the above examples are of decimal type integers. Decimal integers or literals are represented by a sequence of digits in which the first digit is non-zero. To represent an octal, 0o, i.e. a zero and a lower or upper case letter O followed by a sequence of digits from 0 to 7 is used. An example of octal literals is given as follows. Example >>> 0o12 10 >>> 0o100 64 Similarly, numbers can also be represented as hexadecimal (base 16) notation using 0x (zero and the letter X) followed by a sequence of digits. Simple examples of hexadecimal literals displayed in Python interactive mode are given as follows: Example >>> 0x20 32 >>> 0x33 51 The int Function The int function converts a string or a number into a whole number to integer. The int function removes everything after the decimal point. Consider the following example. Example >>> int(12.456) 12 The following example converts a string to an integer. Example >>> int(‘123’) 123 Floating point number The value of π (3.14) is an example of a real number in mathematics. It consists of a whole number, decimal point and fractional part. The length of real numbers has infinite precession, i.e. the digits in the fractional part can continue forever. Thus, Python uses floating point numbers to represent real numbers. A floating-point number can be written using a decimal notation or scientific notation. Some examples of floating-point numbers displayed in Python interactive mode are given as follows: Example >>> 3.7e1 37.0 >>> 3.7 3.7 >>> 3.7*10 37.0
PYTHON PROGRAMMING The above example shows the representation of floating-point number 37.0 in both decimal and scientific manner. Scientific notations are extremely helpful because they help programmers to represent exceptionally large numbers. Table below shows decimal notations in scientific notation format. Table: Example of floating-point numbers The float Function The float function converts a string into a floating-point number. A programmer can make use of float to convert string into float. Consider the following example. Example >>>float(‘10.23’) 10.23 complex number A complex number is a number that can be expressed in the form a+bj, where a and b are real numbers and j is an imaginary unit. Simple example of complex numbers displayed in Python interactive mode is given as follows: Example >>> 2+4j (2+4j) >>> type(2+4j)
PYTHON PROGRAMMING >>> 5 == 4 False >>> 5 == 5 True >>> 4 < 6 True >>> 6> 3 True Strings Data type : (str) • A string is a list of characters in order enclosed by single quote or double quote. • Python string is immutable modifications are not allowed once it is created. • In java String data combine with int data it will become String but not in python String index starts from 0, trying to access character out of index range will generate Index Error. • In python it is not possible to add any two different data types, possible to add only same data type data. Slice Notation
PYTHON PROGRAMMING The str function is used to convert a number into a string. The following example illustrates the same. >>> 12.5 #Floating Point Number 12.5 >>> type(12.5)
PYTHON PROGRAMMING print (data2[:]) Tuple data type : (tuple) •tuple : type • group of heterogeneous objects in sequence • this is immutable modifications are not allowed. • Declared within the parenthesis ( ) • Insertion order is preserved it means in which order we inserted the objects same order output is printed. • The tuple contains forward indexing & backward indexing. Syntactically, a tuple is a comma-separated list of values: >>> t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ Although it is not necessary, it is common to enclose tuples in parentheses to help us quickly identify tuples when we look at Python code: >>> t = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’) Example: tup1 = (‘ratan’, ‘anu’, ‘durga’) tup2 = (1, 2, 3, 4, 5 ) tup3 = “a”, “b”, “c”, “d” # valid not recommended tup4=() tup5 = (10) tup6 = (10,) tup7=(1,2,3,”ratan”,10.5) print(tup1) (‘ratan’, ‘anu’, ‘durga’) print(tup2) (1, 2, 3, 4, 5 ) print(tup3) “a”, “b”, “c”, “d” print(tup4) () print(type(tup5))
PYTHON PROGRAMMING
PYTHON PROGRAMMING phonebook[“Arun “] = 7989103355 phonebook[“gifty “] = 7989103322 print(phonebook) {‘Ram’: 9959830984, ‘Arun’: 7989103355, ‘gifty’: 7989103322} Alternatively, a dictionary can be initialized with the same values in the following notation: >>> phonebook={“Ram”:9959830984,”Arun”:7989103355,”gifty”:7989103322} >>> print(phonebook) {‘Ram’: 9959830984, ‘Arun’: 7989103355, ‘gifty’: 7989103322} Important points 1. Dictionaries can be created using pair of curly braces ( {} ). Each item in the dictionary consist of key, followed by a colon, which is followed by value. And each item is separated using commas (,) . 2. An item has a key and the corresponding value expressed as a pair, key: value. 3. in dictionary values can be of any data type and can repeat,. 4. keys must be of immutable type (string, number or tuple with immutable elements) and must be unique USING FUNCTIONS AND MODULES Calling Functions: Arguments and Return Values A function is a chunk of code that can be called by name to perform a task. Functions often require arguments, that is, specific data values, to perform their tasks. Names that refer to arguments are also known as parameters. When a function completes its task (which is usually some kind of computation), the function may send a result back to the part of the program that called that function in the first place. The process of sending a result back to another part of a program is known as returning a value. For example, the argument in the function call round(6.5) is the value 6.5, and the value returned is 7. When an argument is an expression, it is first evaluated, and then its value is passed to the function for further processing. For instance, the function call abs(4 – 5) first evaluates the expression 4 – 5 and then passes the result, –1, to abs. Finally, abs returns 1. The values returned by function calls can be used in expressions and statements. For example, the function call print(abs(4 – 5) + 3) prints the value 4. Some functions have only optional arguments, some have required arguments, and some have both required and optional arguments. For example, the round function has one required argument, the number to be
PYTHON PROGRAMMING rounded. When called with just one argument, the round function exhibits its default behavior, which is to return the nearest whole number with a fractional part of 0. However, when a second, optional argument is supplied, this argument, a number, indicates the number of places of precision to which the first argument should be rounded. For example, round(7.563, 2) returns 7.56. To learn flow to use a function’s arguments, consult the documentation on functions in the shell. For example, Python’s help function displays information about round, as follows: >>> help(round) Help on built-in function round in module builtin: round(…) round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This returns an int when called with one argument, otherwise the same type as number, ndigits may be negative. The math Module Functions and other resources are coded in components called modules. Functions like abs and round from the built-in module are always available for use, where as the programmer must explicitly import other functions from the modules where they are defined. The math module includes several functions that perform basic mathematical operations. The next code session imports the math module and lists a directory of its resources: >>> import math >>> dir(math) [‘ doc ‘, ‘ file ‘, ‘ loader ‘, ‘ name ‘, ‘ package ‘, ‘ spec ‘, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘pi’, ‘pow’,
PYTHON PROGRAMMING ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’] This list of function names includes some familiar trigonometric functions as well as Python’s most exact estimates of the constants p and e. To use a resource from a module, you write the name of a module as a qualifier, followed by a dot (.) and the name of the resource. For example, to use the value of pi from the math module, you would write the following code: math.pi. The next session uses this technique to display the value of p and the square root of 2: >>> math.pi 3.1415926535897931 >>> math.sqrt(2) 1.4142135623730951 Once again, flelp is available if needed: >>> help(math.cos) Help on built-in function cos in module math: cos(…) cos(x) Return the cosine of x (measured in radians). If you are going to use only a couple of a module’s resources frequently, you can avoid the use of the qualifier with each reference by importing the individual resources, as follows: >>> from math import pi, sqrt >>> print(pi, sqrt(2)) 3.14159265359 1.41421356237 Programmers occasionally import all of a module’s resources to use without the qualifier. For example, the statement from math import * would import all of the math module’s resources. Generally, the first technique of importing resources (that is, importing just the module’s name) is preferred. The use of a module qualifier not only reminds the reader of a function’s purpose but also helps the computer to discriminate between different functions that have the same name.
PYTHON PROGRAMMING The Main Module To differentiate this script from the other modules in a program (and there could be many), we call it the main module. Like any module, the main module can also be imported. Instead of launching the script from a terminal prompt or loading it into the shell from IDLE, you can start IDLE from the terminal prompt and import the script as a module. Let’s do that with the taxform.py script, as follows: >>> import taxform Enter the gross income: 120000 Enter the number of dependents: 2 The income tax is $20800.0 After importing a main module, you can view its documentation by running tfle help function: >>> help(taxform) DESCRIPTION Program: taxform.py Author: Ken Compute a person’s income tax. Significant constants tax rate standard deduction deduction per dependent The inputs are gross income number of dependents Computations: net income 5 gross income – the standard deduction – a deduction for each dependent income tax 5 is a fixed percentage of the net income The outputs are the income tax SELECTION: if and if-else Statements If statement if test expression: statemen(s)
PYTHON PROGRAMMING Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True. If the test expression is False, the statement(s) is not executed. In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.Python interprets non-zero values as True. None and 0 are interpreted as False. Flowchart Example1: num=20 if num>0: print(“Possitive Number”) print(“This is printed always”) output Possitive Number This is printed always Example2: num=-2 if num>0: print(“Possitive Number”) print(“This is printed always”) output This is printed always If-else statement If test expression:
PYTHON PROGRAMMING Body of if else: Body of else The if..else statement evaluates test expression and will execute the body of if only when the test condition is True. If the condition is False, the body of else is executed. Indentation is used to separate the blocks. Flowchart: Example1: # Program checks if the number is positive or negative # And displays an appropriate message num = 3 if num >= 0: print(“Positive or Zero”) else: print(“Negative number”) Output: Positive or Zero In the above example, when num is equal to 3, the test expression is true and the body of if is executed and the body of else is skipped. if…elif…else STATEMENT Syntax: if test expression: Body of if elif test expression: Body of elif
PYTHON PROGRAMMING else: Body of else The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False, it checks the condition of the next elif block and so on.If all the conditions are False, the body of else is executed. Only one block among the several if…elif…else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks. Flowchart: Example1: ”’In this program, we check if the number is positive or negative or zero and display an appropriate message”’ num = 3.4 if num > 0: print(“Positive number”) elif num == 0:
PYTHON PROGRAMMING print(“Zero”) else: print(“Negative number”) Output: Positive number Example2: ”’In this program, we input a number check if the number is positive or negative or zero and display an appropriate message This time we use nested if statement”’ num = float(input(“Enter a number: “)) if num >= 0: if num == 0: print(“Zero”) else: print(“Positive number”) else: print(“Negative number”) Output: Enter a number:5 Positive number NESTED DECISION STRUCTURES When a programmer writes one if statement inside another if statement then it is called a nested if statement. A general syntax for nested if statements is given as follows: if Boolean-expression1: if Boolean-expression2: statement1 ….. else: statement2 else: statement3 In the above syntax, if the Boolean-expression1 and Boolean-expression2 are correct then statement1 will execute. If the Boolean-expression1 is correct and Boolean-expression2 is incorrect then statement2 will execute. And if both Boolean-expression1 and Boolean-expression2 are incorrect then statement3will execute. A program to demonstrate the use of nested if statements is given as follows num1=int(input(“Enter the number:”)) num2=int(input(“Enter the number:”)) num3=int(input(“Enter the number:”)) if num1>num2: if num2>num3:
PYTHON PROGRAMMING print(num1,”is greater than “,num2,”and “,num3) else: print(num1,” is less than “,num2,”and”,num3) print(“End of Nested if”) output: Enter the number:12 Enter the number:34 Enter the number:56 12 is less than 34 and 56 End of Nested if TYPE CONVERSION Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming. There are two types of Type Conversion in Python: 1. Implicit Type Conversion 2. Explicit Type Conversion Let’s discuss them in detail. Implicit Type Conversion In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data type to another without any user involvement. Example x = 10 print(“x is of type:”,type(x)) y = 10.6 print(“y is of type:”,type(y)) x = x + y print(x) print(“x is of type:”,type(x)) As we can see the type od ‘x’ got automatically changed to the “float” type from the “integer” type. this is a simple case of Implicit type conversion in python. Explicit Type Conversion In Explicit Type Conversion in Python, the data type is manually changed by the user as per their requirement. Various form of explicit type conversion are explained below: 1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string. 2. float(): This function is used to convert any data type to a floating-point number #Python code to demonstrate Type conversion # using int(), float() # initializing string s = “10010” # printing string converting to int base 2 c = int(s,2) print (“After converting to integer base 2 : “, end=””) print (c)
PYTHON PROGRAMMING # printing string converting to float e = float(s) print (“After converting to float : “, end=””) print (e) Output: After converting to integer base 2 : 18 After converting to float : 10010.0 3. ord() : This function is used to convert a character to integer. 4. hex() : This function is to convert integer to hexadecimal string. 5. oct() : This function is to convert integer to octal string. 6. tuple() : This function is used to convert to a tuple. 7. set() : This function returns the type after converting to set. 8. list() : This function is used to convert any data type to a list type. 9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary. 10. str() : Used to convert integer into a string. 11. complex(real,imag) : : This function converts real numbers to complex(real,imag) number. After converting tuple to dictionary : {‘a’: 1, ‘f’: 2, ‘g’: 3} 12. chr(number) : : This function converts number to its corresponding ASCII character. REPETITION STRUCTURE The Structure and Behavior of a while Loop Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance. Here is its syntax: while expression: statement(s) Statements represent all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. When a while loop is executed, expr is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the expr is checked again, if it is still true then the body is executed again, and this continues until the expression becomes false. Flowchart of While Loop :
PYTHON PROGRAMMING Python program to illustrate while loop count = 0 while (count < 3): count = count + 1 print("Hello SACET") output: Hello SACET Hello SACET Hello SACET count = 0 while (count < 3): count = count + 1 print("Hello SACET",end=" ") output: Hello SACET Hello SACET Hello SACET For LOOP for loop : A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. syntax : for
PYTHON PROGRAMMING Print each fruit in a fruit list: fruits = [“apple”, “banana”, “cherry”] for x in fruits: print(x) statement(s) output: apple banana cherry The for loop does not require an indexing variable to set beforehand. Looping Through a String Example Loop through the letters in the word “banana”: for x in “banana”: print(x) output: b a n a n a
We are a professional custom writing website. If you have searched a question and bumped into our website just know you are in the right place to get help in your coursework.
Yes. We have posted over our previous orders to display our experience. Since we have done this question before, we can also do it for you. To make sure we do it perfectly, please fill our Order Form. Filling the order form correctly will assist our team in referencing, specifications and future communication.
1. Click on the “Place order tab at the top menu or “Order Now” icon at the bottom and a new page will appear with an order form to be filled.
2. Fill in your paper’s requirements in the "PAPER INFORMATION" section and click “PRICE CALCULATION” at the bottom to calculate your order price.
3. Fill in your paper’s academic level, deadline and the required number of pages from the drop-down menus.
4. Click “FINAL STEP” to enter your registration details and get an account with us for record keeping and then, click on “PROCEED TO CHECKOUT” at the bottom of the page.
5. From there, the payment sections will show, follow the guided payment process and your order will be available for our writing team to work on it.
Need this assignment or any other paper?
Click here and claim 25% off
Discount code SAVE25