🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

unit 1_Python basics, control structures and other features.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

History of Python Subtitle Development and Release: ▪ Guido van Rossum, a Dutch programmer, started working on Python in the late 1980s at the National Research Institute for Mathematics and Computer Science in the Netherlands (CWI). ▪ Guido aimed to create a successor to the ABC programming l...

History of Python Subtitle Development and Release: ▪ Guido van Rossum, a Dutch programmer, started working on Python in the late 1980s at the National Research Institute for Mathematics and Computer Science in the Netherlands (CWI). ▪ Guido aimed to create a successor to the ABC programming language while incorporating certain desirable features such as an easy-to-understand syntax and automatic memory management. ▪ The first version of Python, Python 0.9.0, was released in February 1991. Definition ▪ Python is an interpreted general purpose high level programming language with easy syntax & dynamic semantics. High Level Programming Interpreted -> uses interpreter Language -> Human for its translation. General Purpose-> can use in understandable code is known Takes our code and converts it to multiple domain as high level programming machine code. language. Python C Programming programming dynamic semantics -> Int x; X=10 Variables are dynamic objects Int y; Y=5 Printf (“%d”, x+y); Print(x+y) Compiler Translator Interpreter Is a software who Computer programs are Translates source code converts source code to written in high level to machine code line by machine language, hence we line at run time understandable code. need translator to convert binary Ex- Java Ex:- C language. Can run directly if Exe file can be used to interpreter is available. share with others it can be compiled / run in any machine Python is both compiler and interpreted language [Hybrid Language] Features of Python Easy-to-Read and Expressive Syntax ▪ Python has a clean and straightforward syntax that emphasizes readability. ▪ It uses indentation (whitespace) to delimit blocks of code, promoting code clarity and reducing the need for excessive punctuation. Dynamically Typed: ▪ Python is a dynamically typed language, meaning you don't need to declare variable types explicitly. ▪ Variables can hold values of any type, and their types can be changed during runtime, offering flexibility and ease of use. Interpreted and Interactive: ▪ Python is an interpreted language, allowing for quick development cycles. ▪ It has an interactive mode that enables writing and executing code on-the-fly, making it useful for testing, experimenting, and debugging. Extensive Standard Library: ▪ Python comes with a comprehensive standard library that provides a wide range of modules and functions for various tasks, such as file handling, networking, database access, GUI development, and more. ▪ The standard library eliminates the need for external dependencies in many cases. Cross-Platform Compatibility: ▪ Python runs on different operating systems, including Windows, macOS, Linux, and more. ▪ This cross-platform compatibility allows developers to write code once and run it on multiple platforms without significant modifications. Strong Community and Ecosystem: ▪ Python has a large and active community of developers who contribute to its growth. ▪ The Python Package Index (PyPI) hosts thousands of third-party libraries and frameworks that extend Python's capabilities in areas like web development, data analysis, scientific computing, machine learning, and more. Object-Oriented Programming (OOP) Support: ▪ Python supports object-oriented programming paradigms, allowing for the creation of classes, objects, and inheritance. ▪ It promotes code organization, modularity, and code reuse. Easy Integration with Other Languages: ▪ Python provides seamless integration with other programming languages like C, C++, and Java. ▪ This feature enables developers to use existing libraries, leverage high- performance code, and extend Python's capabilities. Large and Active Community: ▪ Python has a vibrant and supportive community that actively contributes to its development and offers resources, tutorials, and forums for assistance. ▪ This community-driven approach fosters collaboration, knowledge sharing, and continuous improvement of the language. Scalability and Flexibility: ▪ Python can be used for small scripts, as well as large-scale projects. ▪ It offers features like module packaging, unit testing, and profiling, which help in building robust and scalable applications. Anaconda and jupyter ▪ Anaconda is a popular distribution of Python and R programming languages used for scientific computing, data science, machine learning, and related domains. It includes a collection of open-source packages and tools that simplify the process of setting up and managing the development and execution environments for data analysis and machine learning projects. ▪ Jupyter Notebook: This is a web-based interactive computing environment that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. It supports various programming languages, not just the three in its name. Basic Data Type - int ▪ Integer data type Eg:- -1,2,0, 150023 ▪ No limit on the size ▪ No long type integer since there is no limit for the size Basic Data Type - int ▪ To represent non decimal integer eg:- binary, octal and hexa add prefix to represent Ob or OB Binary Oo or OO Octal Ox or OX hexa Floating point data type ▪ Represents real numbers in python ex :- 1.73 1.73e5 1.73e-2 Boolean data type ▪ Represents two values TRUE/FALSE Checking condition name == ‘bsc’ If name ==‘bsc’ print(‘this is bsc’) else: print(‘hello’) String Data type ▪ Sequence of characters ▪ Represented by using ‘ ‘ or “ “. Input and Output Statements ▪ input and output statements are used to interact with the user and display information. ▪ Print Statement: Used to display information to the console. python Copy code print("Hello, World!") Input and Output Statements ▪ Formatted Output: Using the format() method or f-strings for formatted output. name = "John" age = 25 print("My name is {} and I am {} years old.".format(name, age)) ▪ Input Statements: ▪ Input Function: Used to take user input. The input() function returns a string. name = input("Enter your name: ") print("Hello, {}!".format(name)) ▪ Note: If you want to take numerical input and use it as a number, you need to convert it using int() or float(). age = int(input("Enter your age: ")) Variable ▪ A variable in Python is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. ▪ x = 10 ▪ name = "Alice" ▪ is_active = True Constants ▪ Constants are variables whose values should not change throughout the execution of a program. Python does not have built-in support for constants. ▪ PI = 3.14159 Identifiers ▪ Identifiers are the names assigned to memory locations like variables, functions, classes, modules or objects. Starts with a letter (A-Z) OR (a-z) or _ Underscore Rules Cannot begin with a digit Keywords can not be used as identifier names No punctuation within identifiers Case sensitive programming language. keywords ▪ Keywords are reserved words and cannot be used as constants, variables or other identifier names. ▪ Keywords are always mentioned in lower case only expect True, False and None. ▪ Import keyword ▪ print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] Lines and Indentation ▪ No braces to indicate blocks of code for class and function definitions or flow control ▪ Blocks of code are denoted by line indentation. ▪ All statements within the same block must be indented with the same number of spaces. All the continuous lines indented with same number of spaces will be considered as same block. ▪ Spaces should be consistent through out the block. Statements ▪ Instructions that a python interpreter can execute are called statements. ▪ Statements in python end with a new line. ▪ Incase of line continuation character (\) to denote that the line should continue. ▪ Brackets can be used instead of ( \ ) Multiple statement on a single line ▪ ; (semicolon ) can be used to use multiple statements on a single line. Python Expression ▪ Group of operators and operands make an expression. expression is a statement containing operands and operators. ▪ Every expression consists of a least one operand and one or many operator ex:- z = x+5 z,x,5 are operands ▪ =, + are operators DATA TYPE CONVERSION ▪ TYPE CONVERSION FUNCTIONS TO DIRECTLY CONVERT ONE DATA TYPE ▪ Implicit Type Conversion Interpreter automatically converts one data type to another without any user involvement. ▪ Explicit Type Conversion The data type is manually changed by user as per their requirement. Datatypes 1. Number 2. String 3. List 4. Tuple 5. Dictionary 6. Set Number Number data types store numeric values. Number objects are created when a value gets assigned to them. Example: x = 10 y = 22 Using the del statement, one can delete the reference to a number object. Syntax: del var1, var2; Python supports three different types of numeric data types. i. int (signed integers) : Int or integer is a whole number, positive or negative, without decimals, of unlimited length. Example: 10, 182, -232, 012, 0x232 Number ▪ float (floating point real values): Float is a positive or negative number containing one or more decimals. Float can also be scientific numbers with an “e” to indicate the power of 10. Example: 0.12, -34.343, 232e+21, 342.2E-12 ▪ Complex (complex numbers): Complex numbers are written with a real and “j” as the imaginary part Example: 122.3 + 12j , 23.32 – 34.3j Random Numbers Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to generate random numbers. Import the random module, and display a random number between the specified series. Example: >>> import random >>> print(random.randrange(1,1000)) 800 Strings ▪ A string is a collection of characters in single, double, or triple quotes. ▪ A string is a contiguous set of characters in quotation marks. ▪ Strings in Python are surrounded by either single quotation marks, double quotation marks or triple quotes ex:- ‘BSC’ and “BSC” ▪ Subsets of strings can be taken using the slice operator ([ ] and [:] ), with indexes starting at 0 at the beginning of the string and from -1 at the end. Lists ▪ A list is an ordered collection of similar or different types of items separated by commas and enclosed within brackets [ ]. The values stored in a 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. Lists ▪ Ordered ▪ Changeable ▪ Allow Duplicates ▪ Can have different data type Tuples ▪ A tuple is an ordered sequence of items same as a list. ▪ Ordered ▪ When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. ▪ Unchangeable ▪ Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. ▪ Allow Duplicates ▪ Since tuples are indexed, they can have items with the same value ▪ Can have different type Tuples ▪ we use the parentheses() to store items of a tuple. Dictionary ▪ Dictionary items are ordered, changeable, and does not allow duplicates. ▪ Dictionary items are presented in key:value pairs, and can be referred to by using the key name. sets ▪ A set is a collection which is unordered, unchangeable*, and unindexed. Variables ▪ Variable is a name which is used to refer to memory location. ▪ A Variable is also known as an identifier used to hold value. ▪ In Python, we do not need to specify the variable type because Python is a type infer language and smart enough to get variable type Comments Multiple assignment ▪ Python allows you to assign single value to several variables. Import statements Operators ▪ Operators are used to perform specific operations on operands example:- a = b+c a,b,c are called operands = , + are called operators Python contains the following set of operators 1. Arithmetic operators 2. Comparison operators 3. Logical operators 4. Bitwise operators 5. Assignment operators 6. Identity operators 7. Membership operators Arithmetic operators Comparison Operators Logical Operators Bitwise Operator Assignment Operators Identity Operators ▪ Identity operators compare the memory locations of two objects. Identity operators are used to compare the objects whether it is equal or not. Membership Operators ▪ Membership operators test the membership of a value in a sequence, such as strings, lists, or tuples. ▪ If the value is present in the sequence, the resulting value is true; otherwise, it returns false. ▪ Membership operators check the membership of value inside a data structure. If the value is present in the data structure, the resulting value is true; otherwise, it returns false. Arrays ▪ Used to store multiple values in one single variable ▪ An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. ▪ Array Representation – index starts with 0 can access elements easily using index value length of the array Arrays ▪ An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Arrays ▪ In python array ca be created using an array module. array(datatype, valuelist) How do we import -> import array as arr Instead of using array in the entire program we use arr Arrays Adding elements to a array Elements can be added to array by using two built in functions 1. insert() 2. append() CONTROL FLOW Divided into 2 types decision making statements - evaluate the condition and execute the associated block of statements for a single time looping statements - Looping statements evaluate the condition and execute the associated block of statements repeatedly until the condition has failed Decision Making ▪ There are various types of decision making statements. ▪ They are: ▪ i. if statement ▪ ii. if…else statement ▪ iii. if...elif...else statement ▪ iv. Nested if statement Decision Making ▪ if statement The condition will be evaluated and the result can be either TRUE or FALSE Syntax: if (expression) # set of statements to be executed when the condition is TRUE Decision Making If else statement Syntax: if (condition): # TRUE block statements else: # FALSE block statements Decision Making if…elif…else statement Decision Making Nested if statement: Looping ▪ A loop statement allows us to execute a statement or group of statements multiple times. ▪ for loop: The for loop is used to repeat the execution of a block of code for a fixed number of times. for iterator_var in sequence: statements(s) While Loop ▪ The while loop checks the condition initially and repeats the execution of the block of the statements until the evaluated condition becomes FALSE. ▪ We use a while loop when we do not know the number of times to iterate in advance. The syntax for the while loop is: while (condition): #block of statements Control Statements ▪ Python supports the following three control statements. (i) break (ii) continue (iii) pass ▪ Break -> During the execution of the loop, if an emergency exit from the loop is required, then break statement is used. loop (condition): #block of statements Break else: #block of statements Continue ▪ The continue statement is used to skip the current iteration of the loop. If the condition of the loop is evaluated as TRUE, then the body of the loop is executed. During the execution, the continue statement stops the current execution of the body and continues the next iteration. ▪ The syntax is: loop (condition): #block of statements continue pass ▪ The pass statement can be called as a do-nothing statement. ▪ It does not perform any action. This statement is mainly used to keep the CPU busy for some time. The ‘pass’ keyword is used for specifying the pass statement. Else suite in loop Using else in while loop Using else in for loop Nested For & while loop

Use Quizgecko on...
Browser
Browser