Partial preview of the text
Download Introduction to python and more Study notes Computer Science in PDF only on Docsity!
yer t INTRODUCTION History. Features of Python, Data types, Variables, Expressions, neo ents, Operators, Looping, Control Statements sonctior Practice Programs 4. Develop 2 python marks aeoopted from the user and compute the overall pass percentage for their placements. 2, Write a class Money with attributes Rupees and Paise. Overload operators +=, -=, and program to find the best of two test average marks out of three test's a i ou yy, >= so that they may be used on two objects. Also write functions so that a desired amount of money | can be either added or subtracted from Money. orig (Late 1980s): Guido van Rossum started working on Python in December 1989 at the Centrum Wiskunde & rriatica (CW) in the Netherlands, : 2 Syhon 6.9.0 (February 1991) s first official Python re Sree haadhag, furictol version 0.9.0, was released. It included features like and modules, 1.6 (lannuary 1994) é ant milestone, featuring a module system and support for functional 4 © phen 20 (october 2000) Jjuce) ist Coriprehenstons, garbage collection, and Unicode support, among offe: esedieatite foe +4 December 2008) é vi (please that aimed lo clean up the language, removing redient es d packward-incompatible change _ deearcdinngy te ( \ Trothice cyl Aenea Python 3 ‘ ( ~ JI DF DBD GO DBD Db Oe Om OS" Se CH Ore u 6. Python Software Foundation (2001): The Python Software Foundation (PSF) was estab! hed as a non-profit organization to promote, protect, and advance Python. 7. Python 2 Sunset (January 41, 2020) Python 2 officially reached its end of li for ongoing support and updates. fe, with developers encouraged to migrate to Python 3 8. Python 3.x (Ongoing): Python 3 continues to receive updates and improve! transitioned to Python 3, and new projects are encourage! ments. The community has largely d to use this version. plicity, readability, and versatility. Throughout its history, Python has gained popularity for its eadability have contributed to Its community-driven development and strong emphasis on code r its widespread adoption in various fields, including web development, data science, artificial intelligence, and more. Features of python: Python is a versatile programming language known for its simplicity and readability. Some key features of Python include: 1. Readability: Python emphasizes clean and readable code, making it easier to write and maintain. 2. Simpl The language's syntax is simple and easy to learn, which accelerates development. 3. Versatility: Python supports both procedural and object-oriented programming paradigms, making it for various applications. versat 4. Interpreted Language: Python is an interpreted language, allowing for quick development and testing. 5. Dynamic Typing: Python uses dynamic typing, enal y in variable assignment. g fle 6. Large Standard Library Python includes a comprehensive standard library with modules for various tasks, reducing the need for external libra 7. Community Support | 5. Boolean Type: ‘001 (boolean) 6. None Type: ~Kione (represents the absence of a value or a null value) ndation for creating and manipulating data in Python. These data types provide a versatile fou Variables in hon: In Python, variables are used to store and manage data. Here are key points about variables in Python: 4. Variable Assignment: variables are created by assigning a value to a name using the *=" operator. x=5 2. Dynamic Typing: u don't need to explicitly declare a variable's type. Python is dynamically typed, meaning yo The interpreter infers the type based on the assigned value. name = "John" age = 25 3. Variable Naming Rules: @ names can include letters, numbers, and underscores but should start with a letter or an underscore. Python is case-sensitive, So ‘name’ and ‘Name’ would be different variables. 4. Reassignment: You can reassign a variable to a new value. 10 “hello” x x uot 5. Multiple Assignments: Python allows multiple assignments in a single line ab,c=1,2,3 &. Variable Types: Variables can hold different types of data, such as integers, floats, strings, lists, etc. count = 10 price = 5.99 message = “Hello, Python!" Constants: While Python doesn't have constants in the traditional sense, it's a convention to use uppercase names for variables that should not be changed. PI = 3.14159 8. Deleting Variables: You can delete a variable using the ‘del’ statement. Understanding and using variables effectively is fundamental to writing Python code. They provide a way to store and manipulate.data, making your programs more flexible and dynamic. Expressions in python: © Python, expressions are combinations of values, variables, and operators that are evaluated Oduce 3 result. Here are some examples of Python expressions: or ter than= 10>5 ZPRRARA DRA AA AHRANNAN AO COCOA OL OCHA a 92% 9 Create anonymous functions using the ‘lambda’ keyword. add = lambda x, y: x+y g, allowing you to perform Expressions are a fundamental part of Python programmin and expressive manner. calculations, make decisions, and manipulate data in a concis' Conditional Statements in python: Conditional statements in Python allow you to control the flow of your program based on certain conditions. The main conditional statements are: 1. if Statement: Executes a block of code if a specified condition is ‘True’. x=10 x>5: print("x is greater than 5") 2. if-else Statement: - Executes one block of code if the condition is ‘True’ and another block if it's “False”. x=3 if x % printx i x is even") else: print("x is odd") 3. if-elif-else Statement: ows you to check multiple conditions in sequence. core = 7§ score >= 90: print("A") if score >= 80: print("B") score >= 70: Cc") 4. Nested if Statements: You can have if statements inside other if statements. x=10 if x > 0: if x % 2 ==0: print("Positive and even") else: | print("Positive and odd") | else: print("Non-positive") 5. Ternary Operator: A concise way to express a conditional statement. result = "Even" if x % 2 == 0 else "Odd" Python supports a variety of operators that allow you to perform operations on variables and values. Here are some of the key types of operators in Python: 4. Arithmetic Operators: “+° (addition) *~ (subtraction) * (multiplication) f (division) %, (modulo - remainder of division) *** (exponentiation) “Hf (floor division - result is rounded down to the nearest whole number) 2. Comparison (Relational) Operators: ==" (equal to) '=' (not equal to) < (less than) >” (greater than) “<= (less than or equal to) >=" (greater than or equal to) a sequence (such as a t, tuple, or string) or other iterable objects Used for iterating over | for item in iterable: # code to execute for each item Example: fruits = ["apple", “banana”, “orange"] for fruit in fruits: print(fruit) 2. While Loop: peats a block of code as long as a specified con ition is ‘True’. Repeats a block of code as long as a specified condition STS while condition: # code to execute while the con ion is True Example: count = 0 while count < 5: print(count) | count += 1 3. Nested Loops: You can use loops inside other loops (nested loops) to create more complex iterations. for iin range(3): for j in range(2): print(i, j) 4. Loop Control Statements: break’: Exits the loop prematurely. continue : Skips the rest of the code insi i newne ide the loop for the current iteration and moves to the Example for iin range(5) re ee ee ee mm oy « G G «| ‘1 Often used with for loops ta generate a sequence of numbers. ra — for i in range(5): _ print(i) \ cal 6. Enumerate Function: Used to iterate over both the values and their indices. 5 8 aes Qe fruits = ["apple", "banana", orange") for index, fruit in enumerate(fruits): print(index, fruit) > . 27917114 c ents in python: c ol statements are used to control the flow of a program. The main control e 7 © c if the condition is True 2A AP @ if the condition is True te if the condition is False # code to execute if the condi 4. Exception Handling: try-except Statement: try: # code that may raise an exception except ExceptionType as e: # code to handle the exception finally Statement: try: # code that may raise an exception except ExceptionType as e: # code to handle the exception finally: # code to execute regardless of whether an exception was raised or not These control statements provide the necessary tools to make decisions, iterate over data, and handle exceptions, contributing to the flexibility and functionality of Python programs. Exercise programs: 4.simple Python program that takes three test marks for two students, calculates their average, finds the best average, and computes the overall pass percentage for placements: def calculate_average(marks): return sum(marks) / len(marks) def main() # Input for student 1 print(’Enter the marks for Student 1:") student1_test1 = float(input("Test 1: ")) student1_test2 = float(input("Test 2: ")) student!_lest3 = float(input("Test 3: ")) # Input for student 2 prnt(“\nEnter the marks for Student 2:") student2_test1 = float(input("Test 1: ")) student2_test2 = float(input("Test 2: ")y eoeecce € « 5 4 \ . a a a ee ee | PARPHRAAMAANSD 944 9% 99,e977°989 } 4 ‘oh a a + BUA, A JS student2_test3 = float(input("Test 3: ")) # Calculate averages student1_average = calculate_average([student1_test1, student1_test2, student1_test3)) student2_average = calculate_average([student2_test1, student2_test2, student2_test3}) # Find the best average best_average = max(student1_average, student2_average) print("\nResults:") print(f'Student 1 Average: {student1_average:.2f}" print(f'Student 2 Average: {student2_average:.2f}" print(f'\nThe best average is: {best_average:.2f}") # Overall pass percentage calculation pass_percentage = (student1_average + student2_average) / 2 print(f'\nOverall Pass Percentage: {pass_percentage:.2f}%") if name__ =="__mai main() This program prompts the user to enter test marks for two students, calculates the average marks for each student, finds the best average, and computes the overall pass percentage based on the average marks of both students. 2.Below is an example of a Money class in Python that includes attributes for Rupees and Paise, overloads the +=, -=, and >= operators, and provides a display method: class Money: def it__(self, rupees=0, paise=0): self.rupees = rupees self paise = paise def display(self) print(f'{self rupees} Rupees and {self paise} Paise") (self, other) tance(olher, Money) = self rup ef rupees * 100 + other paise se. 100)