Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Unlock the World of Python, Study notes of Computer Applications

Elevate your Python programming with our meticulously crafted study notes designed to accelerate your learning journey! Whether you're a beginner or an experienced coder, our Python notes provide a valuable resource to enhance your skills and understanding of this versatile language. Level up Your Python Journey Today! Dive into Practice-Driven Learning - Order Now!

Typology: Study notes

2022/2023

Available from 01/21/2024

muzen
muzen 🇮🇳

1 document

1 / 110

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
6
Python Programming
Unit I
Introduction : Fundamental ideas of Computer Science - Strings, Assignment, and Comments
- Numeric Data types and Character sets Expressions Loops and Selection Statements:
Definite iteration: the for Loop - selection: if and if-else statements - Conditional iteration:
the while Loop
Unit II
Strings and Text Files: Accessing Characters and substrings in strings - Data encryption-
Strings and Number systems- String methods Text - Lists and Dictionaries: Lists
Dictionaries Design with Functions: A Quick review - Problem Solving with top-Down
Design - Design with recursive Functions - Managing a Program‘s namespace - Higher-Order
Functions
Unit III
Design with Classes: Getting inside Objects and Classes Data-Modeling Examples Building
a New Data Structure The Two Dimensional Grid - Structuring Classes with Inheritance
and Polymorphism - GraphicalUser Interfaces. The Behavior of terminal-Based programs
and GUI-Based programs - Coding Simple GUI-Based programs - Windows and Window
Components - Command Buttons and responding to events
Unit IV
Working with Python Packages: NumPy Library-Ndarray Basic Operations Indexing,
Slicing and Iteration Array manipulation - Pandas The Series The DataFrame - The Index
Objects Data Vizualization with Matplotlib The Matplotlib Architecture pyplot The
Plotting Window Adding Elements to the Chart Line Charts Bar Charts Pie charts
Unit V
Django: Installing Django Building an Application Project Creation Designing the
Data Schema - Creating an administration site for models - Working with QuerySets and
Managers- Retrieving Objects Building List and Detail Views
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Unlock the World of Python and more Study notes Computer Applications in PDF only on Docsity!

6

Python Programming

Unit I Introduction : Fundamental ideas of Computer Science - Strings, Assignment, and Comments

  • Numeric Data types and Character sets – Expressions – Loops and Selection Statements: Definite iteration: the for Loop - selection: if and if-else statements - Conditional iteration: the while Loop Unit II Strings and Text Files: Accessing Characters and substrings in strings - Data encryption- Strings and Number systems- String methods – Text - Lists and Dictionaries: Lists – Dictionaries – Design with Functions: A Quick review - Problem Solving with top-Down Design - Design with recursive Functions - Managing a Program‘s namespace - Higher-Order Functions Unit III Design with Classes: Getting inside Objects and Classes – Data-Modeling Examples – Building a New Data Structure – The Two – Dimensional Grid - Structuring Classes with Inheritance and Polymorphism - GraphicalUserInterfaces. The Behavior of terminal-Based programs and GUI-Based programs - Coding Simple GUI-Based programs - Windows and Window Components - Command Buttons and responding to events Unit IV Working with Python Packages: NumPy Library-Ndarray – Basic Operations – Indexing, Slicing and Iteration – Array manipulation - Pandas – The Series – The DataFrame - The Index Objects – Data Vizualization with Matplotlib – The Matplotlib Architecture – pyplot – The Plotting Window – Adding Elements to the Chart – Line Charts – Bar Charts – Pie charts Unit V Django: Installing Django – Building an Application – Project Creation – Designing the DataSchema - Creating an administration site for models - Working with QuerySets and Managers- Retrieving Objects – Building List and Detail Views

Basics of Python Programming

UNIT – I

Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for:

  • web development (server-side),
  • software development,
  • mathematics,
  • System scripting. What can Python do? Python can be used on a server to create web applications.
  • Python can be used alongside software to create workflows.
  • Python can connect to database systems. It can also read and modify files.
  • Python can be used to handle big data and perform complex mathematics.
  • Python can be used for rapid prototyping, or for production-ready software development. Why Python?
  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written, This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way. Python Syntax compared to other programming languages
  • Python was designed for readability, and has some similarities to the English language with influence from mathematics.
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
  • Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.

my_set = {1, 2, 3} Algorithms Algorithms are step-by-step processes used to solve problems. They can involve searching, sorting, and more complex operations. def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return - 1 Recursion Recursion is a technique where a function calls itself to solve a smaller instance of a problem. def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) Object-Oriented Programming (OOP) OOP is a programming paradigm that uses objects to structure code. Classes define objects with attributes (variables) and methods (functions). class Circle: def init (self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2 File Handling Reading from and writing to files. with open("myfile.txt", "r") as f: content = f.read() with open("output.txt", "w") as f: f.write("Hello, world!")

Python String

A string is a data structure in Python that represents a sequence of characters. It is an immutable data type, meaning that once you have created a string, you cannot change it. Strings are used widely in many different applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text. Creating a String in Python Strings in Python can be created using single quotes or double quotes or even triple quotes. Example

Python Program for

Creating a String

with single Quotes Output

String1 = 'Welcome to the AVSCAS' String with the use of Single Quotes: print("String with the use of Single Quotes: ") Welcome to the AVSCAS print(String1) String with the use of Double Quotes:

Creating a String I'm ashwin

with double Quotes

String1 = "I'm ashwin" Creating a multiline String: print("\nString with the use of Double Quotes: ") ''WELCOME TO MCA''' print(String1)

Creating String with triple

Quotes allows multiple lines

String1 = ''WELCOME TO MCA''' print("\nCreating a multiline String: ") print(String1) Accessing characters in Python String

print(String1)

Printing 3rd to 12th character

print("\nSlicing characters from 3-12: ") print(String1[3:12]) Deleting/Updating from a String In Python, the Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Although deletion of the entire String is possible with the use of a built-in del keyword. Example Output

Python Program to Delete

characters from a String Initial String: Chandru

String1 = "Chandu" Deleting character at 2nd Index: a print("Initial String: ") print(String1)

Deleting a character

of the String

String2 = String1[0:2] + String1[3:] print("\nDeleting character at 2nd Index: ") print(String2) Formatting of Strings Strings in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order. Example Output

Python Program for

Formatting of Strings Print String in default order: Welcome

Default order String in Positional order:

String1 = "{} {} {}".format('Welcome) „Master‟ „of‟ „Computer‟ „Application‟ print("Print String in default order: ") String in order of Keywords: print(String1) Master of Computer Applications

Positional Formatting

String1 = "{1} {0} {2}".format („Master‟ „of‟ „Computer‟ „Application‟) print("\nPrint String in Positional order: ") print(String1)

Keyword Formatting

String1 = "{l} {f} {g}".format(M='Master',C='computer',A='Applications') print("\nPrint String in order of Keywords: ") print(String1)

Assignment Statements in Python

Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. There are some important properties of assignment in Python :-

  • Assignment creates object references instead of copying the objects.
  • Python creates a variable name the first time when they are assigned a value.
  • Names must be assigned before being referenced.
  • There are some operations that perform assignments implicitly. Assignment statement forms :- Basic form: This form is the most common form. student = 'Ashwin' Output print(student) Ashwin Tuple assignment

equivalent to: (x, y) = (50, 100) Output

x, y = 50, 100 x = 50 print('x = ', x) y = 100 print('y = ', y) List assignment-> This works in the same way as the tuple assignment. [x, y] = [2, 4] Output print('x = ', x) x = 2 print('y = ', y) y = 4 Sequence assignment Recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment – any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position. a, b, c = 'AVS' Output print('a = ', a) a = A print('b = ', b) b = V print('c = ', c) C = S Extended Sequence unpacking It allows us to be more flexible in how we select portions of a sequence to assign. p, *q = 'Hello' Output print('p = ', p) p = H print('q = ', q) q = ['e', 'l', 'l', 'o'] Multiple- target assignment x = y = 50 Output print(x, y) 50 50 Augmented assignment The augmented assignment is a shorthand assignment that combines an expression and an assignment. x = 2 Output

equivalent to: x = x + 1 3

x += 1 print(x)

Example Data Types Classes Description Numeric int, float, complex holds numeric values String str holds sequence of characters Sequence list, tuple, range holds collection of items Mapping dict holds data in key-value pair form Boolean bool holds either True or False Set set, frozeenset hold collection of unique items Python String Data Type Python Strings are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from - 1 at the end. Example Output str = 'Hello World!' Hello World! print (str) H print (str[0]) llo print (str[2:5]) llo World! print (str[2:]) Hello World!Hello World! print (str * 2) Hello World!TEST print (str + "TEST") Python List Data Type Python Lists are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where as C array can store elements related to a particular data type. The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end - 1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. Example list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print (list) # Prints complete list print (list[0]) # Prints first element of the list print (list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting from 3rd element print (tinylist * 2) # Prints list two times print (list + tinylist) # Prints concatenated lists

Output ['abcd', 786, 2.23, 'john', 70.2] abcd [786, 2.23] [2.23, 'john', 70.2] [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] Python Tuple Data Type Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. Tuples can be thought of as read-only lists. Example tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print (tuple) # Prints the complete tuple print (tuple[0]) # Prints first element of the tuple print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd print (tuple[2:]) # Prints elements of the tuple starting from 3rd element print (tinytuple * 2) # Prints the contents of the tuple twice print (tuple + tinytuple) Output ('abcd', 786, 2.23, 'john', 70.2) abcd (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john') Python Boolean Data Types Python boolean type is one of built-in data types which represents one of the two values either True or False. Python bool() function allows you to evaluate the value of any expression and returns either True or False based on the expression. Example Output a = True true print(a) <class 'bool'> print(type(a)) Python Ranges Python range() is an in-built function in Python which returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number. Here is the description of the parameters used:

print("Age:", age) John 30 Input Statements

  • input ( prompt )
  • raw_input ( prompt ) input (): This function first takes the input from the user and converts it into a string. The type of the returned object always will be <class „str‟>. It does not evaluate the expression it justreturns the complete statement as String. For example, Python provides a built-in function called input which takes the input from the user. When the input function is called it stops the program and waits for the user‟s input. Example num = int(input("Enter a number: ")) print(num, " ", type(num)) floatNum = float(input("Enter a decimal number: ")) print(floatNum, " ", type(floatNum)) Output Enter a number: 30 30 <class „int‟> Enter a decimal number: 10. 10.4 <class „float‟> Expressions in Python An expression is a combination of operators and operands that is interpreted to produce some other value. In any programming language, an expression is evaluated as per the precedence of its operators. So that if there is more than one operator in an expression, their precedence decides which operation will be performed first. We have many different types of expressions in Python. Constant Expressions: These are the expressions that have constant values only. Example Output x = 15 + 1.3 16. print(x) Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in these expressions are arithmetic operators like addition, subtraction, etc. Example Output x = 40 52 y = 12 28 add = x + y 480 sub = x - y 3. pro = x * y

div = x / y print(add) print(sub) print(pro) print(div) Integral Expressions: These are the kind of expressions that produce only integer results after all computations and type conversions. Example Output a = 13 25 b = 12. c = a + int(b) print(c) as result after all computations and type conversions. Example Output a = 13 2. b = 5 c = a / b print(c) Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluatedfirst, and then compared as per relational operator and produce a boolean output in the end.These expressions are also called Boolean expressions. Example Output a = 21 True b = 13 c = 40 d = 37 p = (a + b) >= (c - d) print(p) Logical Expressions: These are kinds of expressions that result in either True or False. It basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to

  1. Know it is not correct, so it will return False. Studying logical expressions also come across some logical operators which can be seen in logical expressions most often. Example Output P = (10 == 9) False Q = (7 > 5) True R = P and Q True S = P or Q T = not P

Example Output age = “\n Please enter your age: ” Please enter your age: 17 You‟re not eligible to vote while True: Please enter your age: 18 age = input if age >= 18: break else: print (“You‟re not eligible to vote”)

Continue statement

The program encounters a continue statement in Python, it skips the execution of the current iteration when the condition is met and lets the loop continue to move to the next iteration. It is used to continue running the program even after the program encounters a break during execution. Example Output for letter in 'Flexible': Letters: F if letter == ' ': Letters: l continue Letters: e print ('Letters: ', letter) Letters: x Letters: i Letters: b Letters: l Letters: e

Pass statement

The pass statement is a null operator and is used when the programmer wants to do nothing when the condition is satisfied. This control statement in Python does not terminate or skip the execution, it simply passes to the next iteration. Example Output for letter in 'AvsCollege': Letters: A if letter == 'x': Letters: v pass Letters: s print ('Letters: ', letter) Letters: C Letters: o Letters: l Letters: l Letters: e Letters: g Letters: e

Selection Statement

In Python, the selection statements are also known as decision making statements or branching statements. The selection statements are used to select a part of the program to be executed based on a condition. Python provides the following selection statements.

  • if statement
  • if-else statement
  • if-elif statement

if statement in Python

Example Output a = 20 ; b = 20 a and b are equal if ( a == b ): If block ended print( “a and b are equal”) print(“If block ended”) In Python, use the if statement to test a condition and decide the execution of a block of statements based on that condition result. The if statement checks, the given condition then decides the execution of a block of statements. If it is True, then the block of statements is executed and if it is False, then the block of statements is ignored. The execution flow of if statement is as follows.

Example Output i = 10 i is smaller than 15 if (i == 10): i is smaller than 12 too

First if statement

if (i < 15): print("i is smaller than 15")

Nested - if statement

Will only be executed if statement above

it is true

if (i < 12): print("i is smaller than 12 too") else: print("i is greater than 15")

if-elif-else Ladder

The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will beexecuted.

Example Output print(“Select your ride:”) Select your ride: print(“1. Bike”) 1. Bike print(“2. Car”) 2. Car print(“3. SUV”) 3. SUV 3 choice = int( input() ) if( choice == 1 ): print( “You have selected Bike” ) elif( choice == 2 ): print( “You have selected Car” ) elif( choice == 3 ): print( “You have selected SUV” ) else: print(“Wrong choice!“)

Python While Loop

You have selected SUV 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.