Python Programming Introduction PDF
Document Details

Uploaded by VividPeach4382
Tags
Summary
This document provides an introduction to Python programming, covering topics such as the Python language, Jupyter Notebook, data types, and programming style. It explains the advantages of Python, as well as how to use it for web applications, workflows, and big data. This is a good introductory resource for learners.
Full Transcript
PYTHON PROGRAMMING Unit -1 : Introduction to Python and Jupyter Notebook Topics : Introduction to Python Programming Language, Features of Python and its origin, Introduction to Jupyter Notebook, Basic Datatype – Integers, Boolean, Floats, Strings, type() function, typecasting, Declaring and using...
PYTHON PROGRAMMING Unit -1 : Introduction to Python and Jupyter Notebook Topics : Introduction to Python Programming Language, Features of Python and its origin, Introduction to Jupyter Notebook, Basic Datatype – Integers, Boolean, Floats, Strings, type() function, typecasting, Declaring and using variables, Comments, Reading input from users, printing output, Operator in python (Arithmetic Operators, Logical Operators, Membership Operators, Assignment Operators, Comparison Operators, Ternary Operators)Operator precedence Basic Programming Style of Python, Memory Management scheme adopted in Python. PYTHON INTRODUCTION Python is a dynamic, interpreted (bytecode-compiled) language. There are no type declarations of variables, parameters, functions, or methods in source code. This makes the code short and flexible, and you lose the compile-time type checking of the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs. 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. 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. In python, Interpreter is use to interpret and run our programs. ADVANTAGES OF PYTHON I. Extensive Libraries - Python downloads with an extensive library and contains code for various purposes like regular expressions, documentation-generation, unit-testing, web browsers, threading, databases, CGI, email, image manipulation, and more. II. Extensible - Python can be extended to other languages. You can write some of your code in languages like C++ or C. III. Simple and Easy - It is quite easy to learn, understand, and code. ADVANTAGES OF PYTHON IV. Embeddable - Complimentary to extensibility, Python is embeddable as well. You can put your Python code in your source code of a different language, like C++. V. Improved Productivity - The language’s simplicity and extensive libraries render programmers more productive than languages like Java and C++ do. You need to write less and get more things done. VI. IOT Opportunities - Since Python forms the basis of new platforms like Raspberry Pi, it finds the future bright for the Internet Of Things. ADVANTAGES OF PYTHON VII. Readable - Because it is not such a verbose language, reading Python is much like reading English. This is the reason why it is so easy to learn, understand, and code. It also does not need curly braces to define blocks, and indentation is mandatory. VIII. Object Oriented - This language supports both the procedural and object-oriented programming paradigms. While functions help us with code reusability, classes and objects let us model the real world. A class allows the encapsulation of data and functions into one. IX. Free and Open Source - Python is freely available. But not only can you download Python for free, but you can also download its source code, make changes to it, and even distribute it. It downloads with an extensive collection of libraries to help you with your tasks. ADVANTAGES OF PYTHON X. Portable - Here, you need to code only once, and you can run it anywhere. This is called Write Once Run Anywhere (WORA). However, you need to be careful enough not to include any system-dependent features. XI. Interpreted - It is an interpreted language. Since statements are executed one by one, debugging is easier than in compiled languages. USES OF PYTHON 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. Example - print(“Hello World”) Hello World INTRODUCTION TO JUPYTER The Jupyter Notebook is an open source web application that you can use to create and share documents that contain live code, equations, visualizations, and text. The next most popular distribution of Python is Anaconda. Anaconda has its own installer tool called conda that you could use for installing a third-party package. However, Anaconda comes with many scientific libraries preinstalled, including the Jupyter Notebook, so you don’t actually need to do anything other than install Anaconda INTRODUCTION TO JUPYTER INTRODUCTION TO JUPYTER A Notebook’s cell defaults to using code whenever you first create one, and that cell uses the kernel that you chose when you started your Notebook. In this case, you started yours with Python 3 as your kernel, so that means you can write Python code in your code cells. Since your initial Notebook has only one empty cell in it, the Notebook can’t really do anything. Thus, to verify that everything is working as it should, you can add some Python code to the cell and try running its contents. INTRODUCTION TO JUPYTER BASIC DATATYPES Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. Basic datatypes in python: 1. Numeric 2. Dictionary 3. Set 4. Boolean 5. Sequence Type BASIC DATATYPES INTEGER In Python, there is effectively no limit to how long an integer value can be. Of course, it is constrained by the amount of memory your system has, as are all things, but beyond that an integer can be as long as you need it to be. Example- print(4) Output: 4 print(123123123123123123123123123123 + 1) Output: 123123123123123123123123123124 FLOAT The float type in Python designates a floating-point number. float values are specified with a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation. Example - print(4.2) Output: 4.2 print(5.68 – 1.21) Output: 4.47 STRING In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class. Strings in Python can be created using single quotes or double quotes or even triple quotes. Ex – String1 = ‘Python Programming’ print(String1) Output – Python Programming TYPE FUNCTION type() function is used to determine the type of data type.Ex – a=5 print("Type of a: ", type(a)) Output - Type of a: b = 5.0 print("\nType of b: ", type(b)) Output - Type of a: c = 2 + 4j print("\nType of c: ", type(c)) Output - Type of a: BOOLEAN Python provides a Boolean datatype. Objects of Boolean type may have one of two values, True or False. Example – print(type(True) / print(type(False)) Output - TYPE CASTING Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users. In this article, we will see the various technique for typecasting. There can be two types of Type Casting in Python: 1. Implicit Type Casting 2. Explicit Type Casting IMPLICIT TYPE CASTING Python converts data type into another data type automatically. In this process, users don’t have to involve in this process. Ex - a=7 b = 3.0 c = a+b print(c) print(type(c)) Output - 10.0 EXPLICIT TYPE CASTING In this method, Python need user involvement to convert the variable data type into certain data type in order to the operation required. Mainly in type casting can be done with these data type function: int() : int() function take float or string as an argument and return int type object. float() : float() function take int or string as an argument and return float type object. str() : str() function take float or int as an argument and return string type object. TYPE CASTING INT TO FLOAT Here, we are casting integer object to float object with float() function. Ex - A=5 N = float(A) print(N) print(type(N)) Output – 5.0 TYPE CASTING FLOAT TO INT Here, we are casting float data type into integer data type with int() function. Ex - A = 3.7 N = int(A) print(N) print(type(N)) Output – 3 TYPE CASTING INT TO STRING Here, we are casting int data type into string data type with str() function. Ex - A=5 N = str(A) print(N) print(type(N)) Output – 5 TYPE CASTING STRING TO INT Here, we are casting string data type into integer data type with int() function. Ex - A = “5” N = int(A) print(N) print(type(N)) Output – 5 TYPE CASTING STRING TO FLOAT Here, we are casting string data type into float data type with float() function. Ex - A = “5.9” N = float(A) print(N) print(type(N)) Output – 5.9 ARITHMETIC OPERATOR Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example + Addition x+y - Subtraction x-y * Multiplication x*y / Division x/y % Modulus x%y ** Exponentiation x**y // Floor division x//y ASSIGNMENT OPERATOR Assignment operators are used to assign values to variables: Operator Example Same As = x=5 x=5 += x += 3 x=x+3 –= x –= 3 x=x–3 *= x *= 3 x=x*3 /= x /= 3 x=x/3 %= x %= 3 x=x%3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 ASSIGNMENT OPERATOR Operator Example Same As &= x &= 3 x=x&3 |= x |= 3 x=x|3 ^= x ^= 3 x=x^3 >>= x >>= 3 x = x >> 3 a: print("b is greater than a") IF ELSE STATEMENT An if statement is written by using the if keyword. The else keyword catches anything which isn't caught by the preceding conditions. Example: a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") IF ELIF ELSE STATEMENT The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". Example: a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") NESTED IF You can have if statements inside if statements, this is called nested if statements. Example: x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") SHORT HAND IF You can have if statements inside if statements, this is called nested if statements. Example: if a > b: print("a is greater than b") SHORT HAND IF ELSE If you have only one statement to execute, one for if, and one for else, you can put it all on the same line. This technique is known as Ternary Operators, or Conditional Expressions. Example:1 a=2 b = 330 print("A") if a > b else print("B") SHORT HAND IF ELSE Example:2 a = 330 b = 330 print("A") if a > b else print("=") if a == b else print("B") SOME EXAMPLES OF IF ELSE STATEMENT Example:1 a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") Example:2 a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") FOR LOOP Python's for loop is designed to repeatedly execute a code block while iterating through a list, tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration. Syntax: for value in sequence: { code block } FOR LOOP Example: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) Output: apple banana cherry USING ELSE STATEMENT WITH FOR LOOP As already said, a for loop executes the code block until the sequence element is reached. The statement is written right after the for loop is executed after the execution of the for loop is complete. Only if the execution is complete does the else statement comes into play. It won't be executed if we exit the loop or if an error is thrown. USING ELSE STATEMENT WITH FOR LOOP Example:1 [Without Break] for i in range(1, 4): print(i) else: # Executed because no break in for print("No Break") -Output: 1 2 3 No Break -Example:2 [With Break] for i in range(1, 4): print(i) break else: # Not executed as there is a break print("No Break") -Output: 1 WHILE LOOP While loops are used in Python to iterate until a specified condition is met. However, the statement in the program that follows the while loop is executed once the condition changes to false. Syntax: while : { code block } WHILE LOOP Example: i=1 while i < 6: print(i) i += 1 Output: 1 2 3 4 5 USING ELSE STATEMENT WITH WHILE LOOPS As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the same syntax. Example: i=1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") USING ELSE STATEMENT WITH WHILE LOOPS Output: 1 2 3 4 5 i is no longer less than 6 SINGLE STATEMENT WHILE BLOCK The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where we can write the code block in a single line. Example: counter = 0 while (counter < 3): counter+=1; print("Python Loops") Output: Python Loops Python Loops Python Loops THE RANGE() FUNCTION With the help of the range() function, we may produce a series of numbers. range(10) will produce values between 0 and 9. (10 numbers). We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step size is not specified, it defaults to 1. The range object can be characterized as being "slow“. Example: print(range(15)) Output: range(0, 15) THE RANGE() FUNCTION Example: print(list(range(15))) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] Example: print(list(range(4, 9))) Output: [4, 5, 6, 7, 8] Example: print(list(range(5, 25, 4))) Output: [5, 9, 13, 17, 21] FOR LOOP USING RANGE() FUNCTION Example: # print first 5 integers # using python range() function for i in range(5): print(i, end=" ") print() Output: 01234 CONTINUE STATEMENT It returns the control to the beginning of the loop. Syntax: while True / For x in range():... if x == 10: continue print(x) CONTINUE STATEMENT Example: # loop from 1 to 10 for i in range(1, 11): # If i is equals to 6, # continue to next iteration # without printing if i == 6: continue else: # otherwise print the value # of i print(i, end=" ") Output:1 2 3 4 5 7 8 9 10 BREAK STATEMENT It stops the execution of the loop when the break statement is reached. Syntax: Loop{ Condition: break } Example: for i in range(10): print(i) if i == 2: break Output: 0 1 2 PASS STATEMENT Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements. Example: a = 10 b = 20 if(a