What is Programming? Programming is writing a sequence or steps of instructions in order to execute a task. For example, imagine you are playing with your pet and you ask it to fetch the ball you just threw. You may instruct your pet to: Run towards the ball Fetch the ball Bring the ball back This is an example programming for your pet! - Since computers aren’t ‘bright’, we humans have to instruct them to perform the tasks we want. - Like the program for the pet, we write programs so that computers can understand it and can execute the task. This is Programming!.
What is Programming Language? - Humans need a way to communicate with Computers. - The language that helps us to communicate with computers (i.e. allows us to write programs) is called a programming language. What is Python Programming Language? Python is a high-level programming computer language that provides instructions to teach the computer how to perform a task. High-level languages use command words and Syntax which reflects everyday language, which makes them easier to learn and use. High-level languages also offer the programmer development tools such as libraries and built-in functions. It offers efficient high-level data structures and an object-oriented programming style that is simple yet effective. Python is a computer programming language designed to represent the needs of a problem and mimics natural language or mathematical notation..
What is Programming Language? It is a free and open-source language. This means you can read, modify, and distribute the source code of Python scripts for free. It was developed by Guido van Rossum. Python is a language that works as an interpreter. when you run a Python program, an interpreter will read it line by line, as opposed to compiled languages like C or C++, where the compiler first compiles the program before running it..
Benefits of Using Python Programming Easy to Read, Learn and Write. Its syntax is similar to English and therefore enhances the code's readability and understanding. Compared to other languages, such as C/C++ and Java, you need lesser lines of code to execute the same task. Improved Productivity Python's simplicity helps developers to focus on the task at hand. They do not need to spend a significant amount of time learning the syntax or behavior of the programming language. Python developer write less code and produce more. Dynamically Typed Until a code is run, Python would not know what sort of variable you’re dealing with. However, during execution, it allocates the data type to the variables automatically. The developer is not required to declare variables or their data types. Free and Open-Source - Has popular libraries such as: SciPy: SciPy is used for scientific and technical computing. Keras: It is used for Artificial Neural Networks. Pandas: Panda is used for the manipulation and analysis of data. TensorFlow: It is used for Machine Learning tasks. NumPy: It is used for complex mathematical functions and computation. Scikit: It is used for working with various Machine Learning Models..
Applications of Python Programming Language 1. Web Development 2. Data Analysis and Visualization 3. Machine Learning and Artificial Intelligence (AI) 4. Game Development 5. Software Development 6. Web Scraping Applications 7. Embedded Applications 8. CAD Applications 9. Audio and Video Applications 10. Text Processing Improved Productivity Python's simplicity helps developers to focus on the task at hand. They do not need to spend a significant amount of time learning the syntax or behavior of the programming language. Python developer write less code and produce more. Dynamically Typed Until a code is run, Python would not know what sort of variable you’re dealing with. However, during execution, it allocates the data type to the variables automatically. The developer is not required to declare variables or their data types. Free and Open-Source.
Applications of Python Programming Language 1. Web Development. 2. Data Analysis and Visualization 3. Machine Learning and Artificial Intelligence (AI) 4. Game Development 5. Software Development 6. Web Scraping Applications 7. Embedded Applications 8. CAD Applications 9. Audio and Video Applications Improved Productivity Python's simplicity helps developers to focus on the task at hand. They do not need to spend a significant amount of time learning the syntax or behavior of the programming language. Python developer write less code and produce more. Dynamically Typed Until a code is run, Python would not know what sort of variable you’re dealing with. However, during execution, it allocates the data type to the variables automatically. The developer is not required to declare variables or their data types. Free and Open-Source.
Python Installation Many PCs and Macs will have python already installed. To check if you have python installed on a Windows PC, either: - Search in the start bar for Python Or in the search bar, type cmd and click on “Command Prompt” Next, type: “Python” to see the version you are running. If you find that you do not have Python installed on your computer, then you can download it for free from the following website: https://www.python.org/.
Python Installation The setup process and installation of Python can be done in a number of methods: Downloading official Python distributions from Python.org, Installing through a package manager (Anaconda), Installing specialized versions for numerical computation, IoT, and embedded systems. If you find that you do not have Python installed on your computer, then you can download it for free from the following website: https://www.python.org/.
Python Installation Step 1: Select Version of Python to download the Full Installer and proceed to installation. Download either 32-bit (labeled x86) and 64-bit (labeled x86–64) version for your PC. The Latest Python 3 Release is Python 3.10.11 Installing specialized versions for numerical computation, IoT, and embedded systems. Step 2: Download Python Executable Installer and install it Step 3: Wait for it to complete the installation process. Step 4: Verification of installation of Python in Windows To see if Python has been installed successfully on our machine, Open Cmd prompt in your system Run “ Python -V”.
Python Installation Step 5: Run Python. Congratulations! Python has been installed in your system. Now go to Windows Search. Type IDLE. Open it. Run your First Python code. Step 6: Verify whether PIP was installed. PIP is a robust software package management system for Python. PIP is useful, especially when working in virtual environments. The PIP doesn't come pre-installed with Python's older versions..
Python Installation To verify if PIP is installed: Write this command in CMD and hit Enter: pip --version If it is installed, the output will show the version number of the PIP. In case it is not installed, the output will be: 'pip' is not a valid internal or external command, programme, or batch file. Install pip for Python 3: Type the following to install pip sudo apt install python3-pip Then verify if it is installed correctly: pip3 --version.
Installing Python Using Anaconda Navigator Anaconda Navigator is the Anaconda Individual Edition's desktop GUI interface. It simplifies the process of launching programs and managing packages and environments without the need for command-line tools (CLI). Step 1: Go to the official Anaconda website..
Installing Python Using Anaconda Navigator Step 3: Click on the Download button on the page..
Installing Python Using Anaconda Navigator Step 5: Open it after downloading the installer..
Installing Python Using Anaconda Navigator Step 7: Congratulations! Anaconda has been successfully installed on your system..
Python Keywords Each programming language has a few reserved words, known as keywords, that have particular meanings and purposes to be used. Python keywords are reserved words that convey special meanings and purposes to the interpreter and can’t be used for anything else. These reserved keywords in Python are different from built-in functions and data types in Python. Python Keywords List The latest version of Python comprises 35 keywords. Here is the complete list of Python keywords for your reference. Assert; With; else; import; pass; None; break; except; in; raise; True; class; finally; is; return; and; False; del ; elif; try; as; def; from; nonlocal; while; lambda; await; global; not; for; async; continue; If; or; yield.
Python Keywords Each programming language has a few reserved words, known as keywords, that have particular meanings and purposes to be used. Python keywords are reserved words that convey special meanings and purposes to the interpreter and can’t be used for anything else. These reserved keywords in Python are different from built-in functions and data types in Python. Python Keywords List The latest version of Python comprises 35 keywords. Here is the complete list of Python keywords for your reference. Assert; With; else; import; pass; None; break; except; in; raise; True; class; finally; is; return; and; False; del ; elif; try; as; def; from; nonlocal; while; lambda; await; global; not; for; async; continue; If; or; yield.
Example Step 1: Open a notepad and type the following python code: print("Hello, World!") Step 2: Save the file as helloworld.py Step 3: To run the python code, open python from command prompt, type “cd” then “file path”, example “Desktop”. Step 4: After command prompt, you may get “C:\Users\User>”, Add the line “cd Desktop” to get “C:\Users\User>cd Desktop”. Note that “cd” means “change directory”. Hit enter to get “C:\Users\User\Desktop>” Step 5: Add “Python helloworld.py” to get “C:\Users\User\Desktop>Python helloworld.py” Step 6: Hit Enter to get “Hello, World!” Alternative Approach (Very Simple) Step 1: Open a notepad and type the following python code: print("Hello, World!") Step 2: Save the file as helloworld.py Step 3: Double click to open. You should get “Hello, World!”. Note: If there is a quick flash, it does not mean the code didn’t run. It just means it did so really quick. To see, add the following to your code in the notepad: “input('Press ENTER to exit’)” and return to step 3..
Alternative 2: The Python Command Line To test a short amount of code in python sometimes it is quickest and easiest not to write the code in a file. This is made possible because Python can be run as a command line itself. Step 1: Type the following on the Windows, Mac or Linux command line: “C:\Users\Your Name>python” or “C:\Users\Your Name>py” for some versions. Where “Your Name” indicate the name you gave to your PC. Step 2: Type the line “print("Hello, World!")” Step 3: Hit Enter to see "Hello, World!" in the command line. Exiting or quitting Python When done using the python command line, one can simply type the following to quit the python command line interface: “exit()” Note: To get the directory of a path, say the “Desktop”, do this: While holding Shift, perform a Right click on the Desktop folder, then choose Copy as path from the context menu..
What is a Statement in Python? In Python, a statement is a code that the interpreter runs or the instructions that the interpreter follows. A statement like y = 10 sends the value 10 to the variable y. In Python, statements come in a variety of forms, including while, if, and so on. Multi-line Statement The continuation character / in Python is used to prolong a statement across multiple lines. As a result, the statement is now a multi-line statement. Parentheses (), braces {}, or square brackets [ ] can also be used to define a multi-line statement. A semicolon ; can also be used to specify numerous statements on a single line..
Multi-line Statement Example using Continuation Character (\) for summing many numbers.
Indentation in Python Programming Indentation is an important and fundamental aspect of Python programming. Indentation in other languages, such as C, C++, Java, etc., is for the sake of readability.. Indentation in code is for readability only in other programming languages such as C, C++, Java, etc. -Indentation refers to the spaces at the beginning of a code line. - In Python, indentation is used to indicate a block of code, and thus very important. - Thus, indentation must be used carefully in python, especially at where it is placed. - In other words, Python indentation is mandatory and an essential practice that must be followed while writing code..
Indentation in Python Programming Indentation is an important and fundamental aspect of Python programming. Indentation in other languages, such as C, C++, Java, etc., is for the sake of readability.. Indentation in code is for readability only in other programming languages such as C, C++, Java, etc. -Indentation refers to the spaces at the beginning of a code line. - In Python, indentation is used to indicate a block of code, and thus very important. - Indentation in Python enable statements to be in the same indentation level, i.e., statements with an equal number of whitespaces before them, as a single piece of block. Indentation serves as a means of signaling to the Python interpreter that a group of statements belong to a particular block of code - Thus, indentation must be used carefully in python, especially at where it is placed. - In other words, Python indentation is mandatory and an essential practice that must be followed while writing code..
Python Indentation Examples 1. Statement: Code block 1 statement begins 2. if condition: Code block 1 condition continues 3. if condition: Code block 2 statement begins 4. Statement —> Code block 3 stmt begins 5. else: Code block 2 statement cont. 6. Statement: Code block 3 continues 7. Statement: Code block 1 continues -Statements in line number 1, 2, and 7 belong to code block 1 - zero level indentation -Statements 3 and 5 are indented one step ahead and form another block - first level indentation - Statements 4 and 6 form a code block number 3 - second level indentation..
Python Indentation Examples 1. Statement: Code block 1 statement begins 2. if condition: Code block 1 condition continues 3. if condition: Code block 2 statement begins 4. Statement —> Code block 3 stmt begins 5. else: Code block 2 statement cont. 6. Statement: Code block 3 continues 7. Statement: Code block 1 continues Interpretating the execution of the order of the above statements: Code execution begins at line 1 followed by checking the if condition at line 2; If the evaluation of the condition returns true, then control goes inside of the if block. If line 3 returns true, the flow enters into executing the statement in line 4. If the evaluation of line 3 returns false, then the control goes into the execution of statement 6. If the second line itself returns false, then statement 7 would have been executed. This is how we indent the python code for successful execution..
Python Indentation Examples Example 1: Let’s see if a number is odd or even and if it’s zero return zero. Program:.
Python Indentation Examples Example 2: While condition Program:.
Python Indentation Examples Example 3:. Let’s examine what happens if we do not pay attention to indentation: Program: if 5 > 2: print("Five is greater than two!") Output: SyntaxError: expected an indented block after 'if' statement on line 1 The correct way of writing the program is shown below: Correct program: if 5 > 2: print("Five is greater than two!") Correct Output: Five is greater than two!.
Rules of Indentation in Python. Indentation cannot be used on the very first line of the Python code. The standard indentation level in Python is four spaces. This indicates that each level of indentation should be of four spaces. Do not mix tabs and spaces when indenting code in Python. It is recommended to use only spaces as this ensures consistency across different text editors and IDEs. To avoid confusion, always use spaces on all the platforms. Consistency is important while indenting code in Python. All the lines that come under a code block should be indented at the same level. Indentation is an important part of the Python programming language, however, it should be used in moderation and not be overused. Always avoid extra indentation, as it will make the code harder to read and understand. Indentation is not optional. It is mandatory in Python, not adhering to it can cause errors..
Disadvantages of Python Indentation. 1. Inconsistency can lead to errors If different parts of the code block are indented differently, it can lead to confusion and errors. This will cause a huge problem, especially when working on a large project with a complex code base. 2. Requires Strict adherence Developers cannot move forward if they don’t follow indentation religiously. It is a strict requirement of the Python programming language. 3. Extra effort Developers might take indentation as an extra effort in order to maintain consistency throughout the project. 4. Does not improve performance You might believe that since we have discussed the importance of indentation, it could also have an impact on performance. However, an indentation in Python has no role to play when it comes to the performance of the code..
Comments in Python. A comment is added to a Python code using the # symbol. Its role is to provide further information. Comments aid in the user's comprehension of the code. Comments can also be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Any programming language's comments are ignored and are not compiled or understood. Assumptions are added via comments. They explain how the application works for the user. This saves the user time..
Comments in Python. Consider the following examples, in which each line of code has a remark to describe how the program works:.
Multi-Line comments. The hash character (#) at the beginning of each line can be used to add multi-line comments to several lines. Try the following: Example #This program calculates #sum of two integers #and displays the result Example #This is a comment #written in #more than just one line print("Hello, World!").
Multi-Line comments. You can also use the triple quotes ” ” ” is another technique to create a multi-line comment. These triple quotes are commonly used to denote multi-line strings, but they can also be used to denote multi-line comments. Try the following:.
Python Variables. Variables are containers for storing data values. No need to define variables or their types before utilizing them. A variable is said to be created when it is assigned a value. Python has no command for declaring a variable..
Casting. If you want to specify the data type of a variable, this can be done with casting. Example x = str(3) y = int(3) z = float(3) print(x) print(y) print(z) Output 3 3 3.0.
Case-Sensitive. Variable names are case-sensitive. Example a = 4 A = "Sally" print(a) print(A) Output 4 Sally.
Variable Names. A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for defining Python variables: A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive (name, Name, and NAME are three different variables) A variable name cannot be any of the Python keywords..
Legal variable names:. Example myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" print(myvar) print(my_var) print(_my_var) print(myVar) print(MYVAR) print(myvar2) Output john john John John John john.
Many values to multiple variables. Python allows you to assign values to multiple variables in one line:.
Unpack a Collection. If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking..
Output Variables. The Python print() function is often used to output variables..
Output Variables. For numbers, the + character works as a mathematical operator. Example x = 5 y = 10 print(x + y) Output 15.
Output Variables. For numbers, the + character works as a mathematical operator. Example x = 5 y = 10 print(x + y) Output 15.
Output Variables. The print() function will give an error if you combine a string and a number with the + operator. Example x = 5 y = "John" print(x + y) Output TypeError: unsupported operand type(s) for +: 'int' and 'str‘ One can output multiple variables in the print() function by separating the variables with commas. This works even for variables of different data types: Example x = 5 y = "John" print(x, y) Output 5 John.
Global Variables Variables created outside of a function (as in all of the examples so far) are known as global variables. Global variables can be used by everyone, both inside of functions and outside. The Global Keyword When you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword. Example def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x).
Python Data Types Data comes in different forms. Numbers (integers, decimals), Text, etc. Data types are the classification/categorization of data components. Knowing the data type of a data or collection of data helps in knowing which operations may be performed on the data. Built-in Data Types Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview None Type: NoneType.
Getting the Data Type You can get the data type of any object by using the type() function. Example Print the data type of the variable x: x = 5 print(type(x)) Output <class 'int'> Setting the Data Type In Python, the data type is set when you assign a value to a variable. Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex.
Setting the Data Type Example Data Type x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range x = dict x = set x = frozenset() frozenset x = True bool x = b"Hello" bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview x = None NoneType.
Setting the Specific Data Type If you want to specify the data type, you can use the following constructor functions. Example Data Type x = str("Hello World") str x = int(20) int x = float(20.5) float x = complex(1j) complex x = list(("apple", "banana", "cherry")) list x = tuple(("apple", "banana", "cherry")) tuple x = range(6) range x = dict(name="John", age=36) dict x = set(("apple", "banana", "cherry")) set x = frozenset(("apple", "banana", "cherry")) frozenset x = bool(5) bool x = bytes(5) bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview.