




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
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
1 / 110
This page cannot be seen from the preview
Don't miss anything!
6
Unit I Introduction : Fundamental ideas of Computer Science - Strings, Assignment, and Comments
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:
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!")
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
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:
String1 = "I'm ashwin" Creating a multiline String: print("\nString with the use of Double Quotes: ") ''WELCOME TO MCA''' print(String1)
String1 = ''WELCOME TO MCA''' print("\nCreating a multiline String: ") print(String1) Accessing characters in Python String
print(String1)
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
String1 = "Chandu" Deleting character at 2nd Index: a print("Initial String: ") print(String1)
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
String1 = "{} {} {}".format('Welcome) „Master‟ „of‟ „Computer‟ „Application‟ print("Print String in default order: ") String in order of Keywords: print(String1) Master of Computer Applications
String1 = "{1} {0} {2}".format („Master‟ „of‟ „Computer‟ „Application‟) print("\nPrint String in Positional order: ") print(String1)
String1 = "{l} {f} {g}".format(M='Master',C='computer',A='Applications') print("\nPrint String in order of Keywords: ") print(String1)
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 :-
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
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
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
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”)
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
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
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.
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
if (i < 15): print("i is smaller than 15")
if (i < 12): print("i is smaller than 12 too") else: print("i is greater than 15")
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!“)
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.