- Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
- Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
- Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
- Python supports modules and packages, which encourages program modularity and code reuse.
- The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.
Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite different.
Beginning with Python programming:
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our programs. There are certain online interpreters like https://ide.geeksforgeeks.org/ that can be used to run Python programs without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software downloaded from http://python.org/.
Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you’re running, type “python” in the terminal emulator. The interpreter should start and print the version number.
macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install Python 3 from http://python.org/.
2) Writing our first program:
Just type in the following code after you start the interpreter.
Output:
GeeksQuiz
Let’s analyze the script line by line.
Line 1: [# Script Begins] In Python, comments begin with a #. This statement is ignored by the interpreter and serves as documentation for our code.
Line 2: [print(“GeeksQuiz”)] To print something on the console, print() function is used. This function also adds a newline after our message is printed(unlike in C). Note that in Python 2, “print” is not a function but a keyword and therefore can be used without parentheses. However, in Python 3, it is a function and must be invoked with parentheses.
Line 3: [# Script Ends] This is just another comment like in Line 1.
Python designed by Guido van Rossum at CWI has become a widely used general-purpose, high-level programming language.
Prerequisites:
Knowledge of any programming language can be a plus.
Reason for increasing popularity
- Emphasis on code readability, shorter codes, ease of writing
- Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.
- Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.
- There exists inbuilt functions for almost all of the frequently used concepts.
- Philosophy is “Simplicity is the best”.
LANGUAGE FEATURES
- Interpreted
- There are no separate compilation and execution steps like C and C++.
- Directly run the program from the source code.
- Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.
- No need to worry about linking and loading with libraries, etc.
- Platform Independent
- Python programs can be developed and executed on multiple operating system platforms.
- Python can be used on Linux, Windows, Macintosh, Solaris and many more.
- Free and Open Source; Redistributable
- High-level Language
- In Python, no need to take care about low-level details such as managing the memory used by the program.
- Simple
- Closer to English language;Easy to Learn
- More emphasis on the solution to the problem rather than the syntax
- Embeddable
- Python can be used within C/C++ program to give scripting capabilities for the program’s users.
- Robust:
- Exceptional handling features
- Memory management techniques in built
- Rich Library Support
- The Python Standard Library is very vast.
- Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.
- Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.
Python vs JAVA
Python | Java |
---|---|
Dynamically Typed
| Statically Typed
|
Concise Express much in limited words | Verbose Contains more words |
Compact | Less Compact |
Uses Indentation for structuring code | Uses braces for structuring code |
The classical Hello World program illustrating the relative verbosity of a Java Program and Python Program
Java Code
Python Code
Similarity with Java
- Require some form of runtime on your system (JVM/Python runtime)
- Can probably be compiled to executables without the runtime (this is situational, none of them are designed to work this way)
LOOK and FEEL of the Python
GUI
Command Line interface
Softwares making use of Python
Python has been successfully embedded in a number of software products as a scripting language.
- GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.
- Python has also been used in artificial intelligence
- Python is often used for natural language processing tasks.
Current Applications of Python
- A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity
- Python has seen extensive use in the information security industry, including in exploit development.
- Raspberry Pi– single board computer uses Python as its principal user-programming language.
- Python is now being used Game Development areas also.
Pros:
- Ease of use
- Multi-paradigm Approach
Cons:
- Slow speed of execution compared to C,C++
- Absence from mobile computing and browsers
- For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these.
Industrial Importance
Most of the companies are now looking for candidates who know about Python Programming. Those having the knowledge of python may have more chances of impressing the interviewing panel. So I would suggest that beginners should start learning python and excel in it.
Python is a high-level, interpreted, and general-purpose dynamic programming language that focuses on code readability. It has fewer steps when compared to Java and C. It was founded in 1991 by developer Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world. Python is a powerful, flexible, and easy-to-use language. In addition, the community is very active there. It is used in many organizations as it supports multiple programming paradigms. It also performs automatic memory management.
Advantages :
- Presence of third-party modules
- Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc)
- Open source and community development
- Versatile, Easy to read, learn and write
- User-friendly data structures
- High-level language
- Dynamically typed language(No need to mention data type based on the value assigned, it takes data type)
- Object-oriented language
- Portable and Interactive
- Ideal for prototypes – provide more functionality with less coding
- Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)
- (IoT)Internet of Things Opportunities
- Interpreted Language
- Portable across Operating systems
Applications :
- GUI based desktop applications
- Graphic design, image processing applications, Games, and Scientific/ computational Applications
- Web frameworks and applications
- Enterprise and Business applications
- Operating Systems
- Education
- Database Access
- Language Development
- Prototyping
- Software Development
Organizations using Python :
- Google(Components of Google spider and Search Engine)
- Yahoo(Maps)
- YouTube
- Mozilla
- Dropbox
- Microsoft
- Cisco
- Spotify
- Quora
So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare Python’s Syntax with C, C++, Java ( I have taken these 3 because they are most famous and mostly used languages).
Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope.
Now moving on further Lets start our basics of Python . I will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily.
- If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.
It will look somehow this :
- If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.
It will look like this : - Presence of third-party modules
- Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics, etc.)
- Open source and large active community base
- Versatile, Easy to read, learn and write
- User-friendly data structures
- High-level language
- Dynamically typed language(No need to mention data type based on the value assigned, it takes data type)
- Object-Oriented and Procedural Programming language
- Portable and Interactive
- Ideal for prototypes – provide more functionality with less coding
- Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)
- Internet of Things(IoT) Opportunities
- Interpreted Language
- Portable across Operating systems
- Performance: Python is an interpreted language, which means that it can be slower than compiled languages like C or Java. This can be an issue for performance-intensive tasks.
- Global Interpreter Lock: The Global Interpreter Lock (GIL) is a mechanism in Python that prevents multiple threads from executing Python code at once. This can limit the parallelism and concurrency of some applications.
- Memory consumption: Python can consume a lot of memory, especially when working with large datasets or running complex algorithms.
- Dynamically typed: Python is a dynamically typed language, which means that the types of variables can change at runtime. This can make it more difficult to catch errors and can lead to bugs.
- Packaging and versioning: Python has a large number of packages and libraries, which can sometimes lead to versioning issues and package conflicts.
- Lack of strictness: Python’s flexibility can sometimes be a double-edged sword. While it can be great for rapid development and prototyping, it can also lead to code that is difficult to read and maintain.
- Steep learning curve: While Python is generally considered to be a relatively easy language to learn, it can still have a steep learning curve for beginners, especially if they have no prior experience with programming.
- GUI-based desktop applications
- Graphic design, image processing applications, Games, and Scientific/ computational Applications
- Web frameworks and applications
- Enterprise and Business applications
- Operating Systems
- Education
- Database Access
- Language Development
- Prototyping
- Software Development
- Data Science and Machine Learning
- Scripting
- Google(Components of Google spider and Search Engine)
- Yahoo(Maps)
- YouTube
- Mozilla
- Dropbox
- Microsoft
- Cisco
- Spotify
- Quora
The ” >>> ” represents the python shell and its ready to take python commands and code.
In other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String.
Output:
3 4.5 helloworld
See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.
List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.
append() function is used to add data to the list.
Output:
[21, 40.5, String]
Comments:
# is used for single line comment in Python """ this is a comment """ is used for multi line comments
Input and Output
In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user.
Output:
hello harssh
Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
Selection
Selection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)
Output:
Num1 is good
Functions
You can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.
Syntax:
def function-name(arguments): #function body
Output:
hello hello again hello hello again
Now as we know any program starts from a ‘main’ function…lets create a main function like in many other programming languages.
Output:
Started Enter integer: 5
As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here.
Output:
0 1 2 3 4
Python has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here
‘import’ keyword is used to import a particular module into your python code. For instance consider the following program.
Output:
85.0
Python Language advantages and applicationsPython is a high-level, interpreted, and general-purpose dynamic programming language that focuses on code readability. It generally has small programs when compared to Java and C. It was founded in 1991 by developer Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world. Python is a powerful, flexible, and easy-to-use language. In addition, the python community is very active. It is used in many organizations as it supports multiple programming paradigms. It also performs automatic memory management.Advantages:
Disadvantages:
Applications:
Organizations using Python :
Python 3 basics
Python 3 is a popular high-level programming language used for a wide variety of applications. Here are some basics of Python 3 that you should know:
- Variables: In Python 3, variables are created by assigning a value to a name. For example, x = 5 creates a variable called x and assigns the value 5 to it.
- Data types: Python 3 supports several built-in data types, including integers, floats, strings, booleans, lists, tuples, and dictionaries.
- Operators: Python 3 supports a variety of operators, including arithmetic operators (+, -, *, /), comparison operators (>, <, ==, !=), and logical operators (and, or, not).
- Control flow statements: Python 3 supports several control flow statements, including if-else statements, for loops, and while loops. These statements allow you to control the flow of execution in your code.
- Functions: In Python 3, functions are created using the def keyword. For example, def my_function(x): creates a function called my_function that takes one argument called x.
Input and output: In Python 3, you can use the input() function to get user input, and the print() function to output text to the console.
Modules: Python 3 supports modules, which are collections of functions and variables that can be imported and used in other Python code. You can import modules using the import keyword.
Advantages of Python 3:
- Python 3 has a simple syntax that is easy to learn and read, making it a good choice for beginners.
- Python 3 is a high-level language that has a large standard library and many third-party libraries available, making it a versatile language that can be used for a wide variety of applications.
- Python 3 supports multiple programming paradigms, including object-oriented, functional, and procedural programming.
- Python 3 is an interpreted language, meaning that it does not need to be compiled before running, making it easy to write and test code quickly.
- Python 3 has good support for data analysis and scientific computing, with libraries such as NumPy and Pandas.
Disadvantages of Python 3:
- Python 3 can be slower than compiled languages such as C++ or Java, which may be a concern for applications that require high performance.
- Python 3 has a global interpreter lock (GIL), which can limit its ability to take advantage of multiple CPU cores.
- Python 3 may not be the best choice for low-level systems programming, as it does not offer the same level of control over hardware as other languages.
- Python 3 is not as popular in some fields as other languages, such as R for data analysis or C++ for game development, so it may not always be the best choice for specific applications.
Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it’s not compiled and the interpreter will check the code line by line. This article can be used to learn the very basics of Python programming language. So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare Python’s Syntax with C, C++, and Java ( I have taken these 3 because they are the most famous and mostly used languages).
Python3
Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope. Let us start with our basics of Python where we will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily.
Introduction and Setup
- If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as a Python’s IDE to run the Python Scripts. It will look somehow this :
- If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go. It will look like this :
The ” >>> ” represents the python shell and its ready to take python commands and code.
Variables and Data Structures
In other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String.
Python3
3 4.5 helloworld
See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built-in Data Structures namely List, Dictionary, Tuple, and Set.
List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.
append() function is used to add data to the list.
Python3
[21, 40.5, 'String']
Python3
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Python3
('Geeks', 'For', 'Geeks')
Python3
{'Geeks', 'For'}
Comments:
# is used for single line comment in Python
""" this is a comment """ is used for multi line comments
Input and Output
In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user.
Python3
Output:
hello harssh
Python3
Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
Selection
Selection in Python is made using the two keywords ‘if’ and ‘elif’(elseif) and else
Python3
Num1 is good
You can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.
Syntax:
def function-name(arguments):
#function body
Python3
hello hello again hello hello again
Now as we know any program starts from a ‘main’ function…lets create a main function like in many other programming languages.
Python3
Iteration (Looping)
As the name suggests it calls repeating things again and again. We will use the most popular ‘for and while’ loop here.
Python3
Python3
0 1 2 3 4
Modules
Python has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here
‘import’ keyword is used to import a particular module into your python code. For instance consider the following program.
Python3
85.0
Python Keywords
Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier.
List of Keywords in Python
Keyword | Description | Keyword | Description | Keyword | Description |
---|---|---|---|---|---|
and | It is a Logical Operator | False | Represents an expression that will result in not being true. | nonlocal | It is a non-local variable |
as | It is used to create an alias name | finally | It is used with exceptions | not | It is a Logical Operator |
assert | It is used for debugging | for | It is used to create Loop | or | It is a Logical Operator |
break | Break out a Loop | from | To import specific parts of a module | pass | pass is used when the user doesn’t want any code to execute |
class | It is used to define a class | global | It is used to declare a global variable | raise | raise is used to raise exceptions or errors. |
continue | Skip the next iteration of a loop | if | To create a Conditional Statement | return | return is used to end the execution |
def | It is used to define the Function | import | It is used to import a module | True | Represents an expression that will result in true. |
del | It is used to delete an object | is | It is used to test if two variables are equal | try | Try is used to handle errors |
elif | Conditional statements, same as else-if | in | To check if a value is present in a Tuple, List, etc. | while | While Loop is used to execute a block of statements |
else | It is used in a conditional statement | lambda | Used to create an anonymous function | with | with statement is used in exception handling |
except | try-except is used to handle these errors | None | It represents a null value | yield | yield keyword is used to create a generator function |
Get the List of all Python keywords
We can also get all the keyword names using the below code.
- Python3
Output:
The list of keywords are:[‘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’] Let’s discuss each keyword in detail with the help of good examples.
- True, False, None Keyword
- True: This keyword is used to represent a boolean true. If a statement is true, “True” is printed.
- False: This keyword is used to represent a boolean false. If a statement is false, “False” is printed.
- None: This is a special constant used to denote a null value or a void. It’s important to remember, 0, any empty container(e.g. empty list) does not compute to None.
It is an object of its datatype – NoneType. It is not possible to create multiple None objects and can assign them to variables.
True, False, and None
- Python3
True True 3 1 False False
and, or, not, in, is
- and: This a logical operator in Python. “and” Return the first false value. If not found return last. The truth table for “and” is depicted below.
3 and 0 return 0
3 and 10 return 10
10 or 20 or 30 or 10 or 70 returns 10
The above statements might be a bit confusing to a programmer coming from a language like C where the logical operators always return boolean values(0 or 1). The following lines are straight from the Python docs explaining this:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that neither and nor restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not ‘foo’ produces False rather than ”.)
- or: This a logical operator in Python. “or” Return the first True value. if not found return last. The truth table for “or” is depicted below.
3 or 0 returns 3
3 or 10 returns 3
0 or 0 or 3 or 10 or 0 returns 3
- not: This logical operator inverts the truth value. The truth table for “not” is depicted below.
- in: This keyword is used to check if a container contains a value. This keyword is also used to loop through the container.
- is: This keyword is used to test object identity, i.e to check if both the objects take the same memory location or not.
Example: and, or, not, is and in keyword
- Python
Output:
True
False
False
s is part of geeksforgeeks
g e e k s f o r g e e k s
True
False
Iteration Keywords – for, while, break, continue
- for: This keyword is used to control flow and for looping.
- while: Has a similar working like “for”, used to control flow and for looping.
- break: “break” is used to control the flow of the loop. The statement is used to break out of the loop and passes the control to the statement following immediately after loop.
- continue: “continue” is also used to control the flow of code. The keyword skips the current iteration of the loop but does not end the loop.
Example: For, while, break, continue keyword
- Python3
0 1 2 3 4 5 6 0 1 2 3 4 5 7 8 9
Conditional keywords – if, else, elif
- if : It is a control statement for decision making. Truth expression forces control to go in “if” statement block.
- else : It is a control statement for decision making. False expression forces control to go in “else” statement block.
- elif : It is a control statement for decision making. It is short for “else if“
Example: if, else, and elif keyword
- Python3
i is 20
Note: For more information, refer to out Python if else Tutorial.
def
def keyword is used to declare user defined functions.
Example: def keyword
- Python3
Inside Function
Return Keywords – Return, Yield
- return : This keyword is used to return from the function.
- yield : This keyword is used like return statement but is used to return a generator.
Example: Return and Yield Keyword
- Python3
45 0 1 3 6 10 15 21 28 36 45
class
class keyword is used to declare user defined classes.
Example: Class Keyword
- Python3
mammal I'm a mammal I'm a dog
Note: For more information, refer to our Python Classes and Objects Tutorial .
With
with keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used much in day to day programming.
Example: With Keyword
- Python3
as
as keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as mymath.
Example: as Keyword
- Python3
120
pass
pass is the null statement in python. Nothing happens when this is encountered. This is used to prevent indentation errors and used as a placeholder.
Example: Pass Keyword
- Python3
Lambda
Lambda keyword is used to make inline returning functions with no statements allowed internally.
Example: Lambda Keyword
- Python3
343
Import, From
- import : This statement is used to include a particular module into current program.
- from : Generally used with import, from is used to import particular functionality from the module imported.
Example: Import, From Keyword
- Python3
3628800 3628800
Exception Handling Keywords – try, except, raise, finally, and assert
- try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in “try” block is checked, if there is any type of error, except block is executed.
- except : As explained above, this works together with “try” to catch exceptions.
- finally : No matter what is result of the “try” block, block termed “finally” is always executed.
- raise: We can raise an exception explicitly with the raise keyword
- assert: This function is used for debugging purposes. Usually used to check the correctness of code. If a statement is evaluated to be true, nothing happens, but when it is false, “AssertionError” is raised. One can also print a message with the error, separated by a comma.
Example: try, except, raise, finally, and assert Keywords
- Python3
Output
Can't divide by zero
This is always executed
The value of a / b is :
AssertionError: Divide by 0 error
- Python3
Output
TypeError: Both the strings are different.
Note: For more information refer to our tutorial Exception Handling Tutorial in Python.
del
del is used to delete a reference to an object. Any variable or list value can be deleted using del.
Example: del Keyword
- Python3
Output
20
GeeksForGeeks
NameError: name 'my_variable1' is not defined
Global, Nonlocal
- global: This keyword is used to define a variable inside the function to be of a global scope.
- non-local : This keyword works similar to the global, but rather than global, this keyword declares a variable to point to variable of outside enclosing function, in case of nested functions.
Example: Global and nonlocal keywords
- Python3
25 20
Python If Else
There comes situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code. Decision-making statements in programming languages decide the direction(Control Flow) of the flow of program execution.
Types of Control Flow in Python
In Python programming language, the type of control flow statements is as follows:
Python if statement
The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not.
Syntax:
if condition: # Statements to execute if # condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not.
As we know, python uses indentation to identify a block. So the block under an if statement will be identified as shown in the below example:
if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block.
Flowchart of Python if statement
![Flowchart of Python if statement](https://media.geeksforgeeks.org/wp-content/uploads/if-statement.jpg)
Flowchart of Python if statement
Example of Python if Statement
As the condition present in the if statement is false. So, the block below the if statement is executed.
- Python3
Output:
I am Not in if
Python If-Else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But if we want to do something else if the condition is false, we can use the else statement with if statement to execute a block of code when the if condition is false.
Syntax:
if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false
Flowchart of Python if-else statement
![Flowchart of Python is-else statement](https://media.geeksforgeeks.org/wp-content/uploads/if-else.jpg)
Flowchart of Python is-else statement
Example of Python if-else statement
The block of code following the else statement is executed as the condition present in the if statement is false after calling the statement which is not in the block(without spaces).
- Python3
Output:
i is greater than 15 i'm in else Block i'm not in if and not in else Block
Example of Python if else statement in a list comprehension
In this example, we are using an if statement in a list comprehension with the condition that if the element of the list is odd then its digit sum will be stored else not.
- Python3
Output :
[16, 3, 18, 18]
Nested-If Statement in Python
A nested if is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e., we can place an if statement inside another if statement.
Syntax:
if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here
Flowchart of Python Nested if Statement
![Flowchart of Python Nested if statement](https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200710163548/Nested_if.jpg)
Flowchart of Python Nested if statement
Example of Python Nested if statement
In this example, we are showing nested if conditions in the code, All the If conditions will be executed one by one.
- Python3
Output:
i is smaller than 15 i is smaller than 12 too
Python if-elif-else Ladder
Here, a user can decide among multiple options. 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 be executed.
Syntax:
if (condition): statement elif (condition): statement . . else: statement
Flowchart of Python if-elif-else ladder
![](https://media.geeksforgeeks.org/wp-content/uploads/if-elseif-ladder.jpg)
Flowchart of if-elif-else ladder
Example of Python if-elif-else ladder
In the example, we are showing single if condition and multiple elif conditions, and single else condition.
- Python3
Output:
i is 20
Short Hand if statement
Whenever there is only a single statement to be executed inside the if block then shorthand if can be used. The statement can be put on the same line as the if statement.
Syntax:
if condition: statement
Example of Python if shorthand
In the given example, we have a condition that if the number is less than 15, then further code will be executed.
- Python3
Output:
i is less than 15
Short Hand if-else statement
This can be used to write the if-else statements in a single line where only one statement is needed in both the if and else blocks.
Syntax:
statement_when_True if condition else statement_when_False
Example of Python if else shorthand
In the given example, we are printing True if the number is 15 else it will print False.
- Python3
Output:
True
Python For LoopsIn Python, there is no C style for loop, i.e., for (i=0; I <n; i++). There is a “for” loop which is similar to each loop in other languages. Let us learn how to use a loop for sequential traversals.
For Loops in Python
Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like String, Tuple, List, Set, or Dictionary.
Note: In Python, for loops only implement the collection-based iteration.
For Loops Syntax
for var in iterable: # statementsFlowchart of for loop
For Loop flowchart
Here the iterable is a collection of objects like lists, and tuples. The indented statements inside the for loops are executed once for each item in an iterable. The variable var takes the value of the next item of the iterable each time through the loop.
Examples of Python For Loop
Python For Loop with List
This code uses a for loop to iterate over a list of strings, printing each item in the list on a new line. The loop assigns each item to the variable I and continues until all items in the list have been processed.
- Python3
Output :
geeks for geeksPython For Loop in Python Dictionary
This code uses a for loop to iterate over a dictionary and print each key-value pair on a new line. The loop assigns each key to the variable i and uses string formatting to print the key and its corresponding value.
- Python3
Output:
Dictionary Iteration xyz 123 abc 345
Python For Loop in Python String
This code uses a for loop to iterate over a string and print each character on a new line. The loop assigns each character to the variable i and continues until all characters in the string have been processed.
- Python3
Output:
String Iteration G e e k sPython For Loop with a step size
This code uses a for loop in conjunction with the range() function to generate a sequence of numbers starting from 0, up to (but not including) 10, and with a step size of 2. For each number in the sequence, the loop prints its value using the print() function. The output will show the numbers 0, 2, 4, 6, and 8.
- Python3
Output :
0 2 4 6 8Python For Loop inside a For Loop
This code uses nested for loops to iterate over two ranges of numbers (1 to 3 inclusive) and prints the value of i and j for each combination of the two loops. The inner loop is executed for each value of i in the outer loop. The output of this code will print the numbers from 1 to 3 three times, as each value of i is combined with each value of j.
- Python3
Output :
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3Python For Loop with Zip()
This code uses the zip() function to iterate over two lists (fruits and colors) in parallel. The for loop assigns the corresponding elements of both lists to the variables fruit and color in each iteration. Inside the loop, the print() function is used to display the message “is” between the fruit and color values. The output will display each fruit from the list of fruits along with its corresponding color from the colours list.
- Python3
Output :
apple is red banana is yellow cherry is greenPython For Loop with Tuple
This code iterates over a tuple of tuples using a for loop with tuple unpacking. In each iteration, the values from the inner tuple are assigned to variables a and b, respectively, and then printed to the console using the print() function. The output will show each pair of values from the inner tuples.
- Python3
Output :
1 2 3 4 5 6Loop Control Statements
Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
Python for Loop with Continue Statement
Python continue Statement returns the control to the beginning of the loop.
- Python3
Output:
Current Letter : g Current Letter : k Current Letter : f Current Letter : o Current Letter : r Current Letter : g Current Letter : kPython For Loop with Break Statement
Python break statement brings control out of the loop.
- Python3
Output:
Current Letter : ePython For Loop with Pass Statement
The pass statement to write empty loops. Pass is also used for empty control statements, functions, and classes.
- Python3
Output:
Last Letter : sPython for loop with range function
The Python range() function is used to generate a sequence of numbers. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes mainly three arguments.
- start: integer starting from which the sequence of integers is to be returned
- stop: integer before which the sequence of integers is to be returned.
The range of integers ends at a stop – 1.- step: integer value which determines the increment between each integer in the sequence.
- Python3
Output:
0 1 2 3 4 5 6 7 8 9 Sum of first 10 numbers : 45
Else With For loop in Python
Python also allows us to use the else condition for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
- Python3
Output:
1 2 3 No Break
Python While Loop
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.
Syntax:
while expression: statement(s)
Flowchart of While Loop :
![Python While Loop](https://media.geeksforgeeks.org/wp-content/uploads/20191101170515/while-loop.jpg)
While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance.
Statements represent all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. When a while loop is executed, expr is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the expr is checked again, if it is still true then the body is executed again and this continues until the expression becomes false.
Example 1: Python While Loop
Python3
Hello Geek Hello Geek Hello Geek
In the above example, the condition for while will be True as long as the counter variable (count) is less than 3.
Example 2: Python while loop with list
Python3
4 3 2 1
In the above example, we have run a while loop over a list that will run until there is an element present in the list.
Example 3: Single statement while block
Just like the if block, if the while block consists of a single statement we can declare the entire loop in a single line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;).
Python3
Hello Geek Hello Geek Hello Geek Hello Geek Hello Geek
Example 4: Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
Continue Statement
Python Continue Statement returns the control to the beginning of the loop.
Example: Python while loop with continue statement
Python3
Current Letter : g Current Letter : k Current Letter : f Current Letter : o Current Letter : r Current Letter : g Current Letter : k
Break Statement
Python Break Statement brings control out of the loop.
Example: Python while loop with a break statement
Python3
Current Letter : g
Pass Statement
The Python pass statement to write empty loops. Pass is also used for empty control statements, functions, and classes.
Example: Python while loop with a pass statement
Python3
Value of i : 13
While loop with else
As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
Note: The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
Python3
1 2 3 4 No Break 1
Sentinel Controlled Statement
In this, we don’t use any counter variable because we don’t know how many times the loop will execute. Here user decides that how many times he wants to execute the loop. For this, we use a sentinel value. A sentinel value is a value that is used to terminate a loop whenever a user enters it, generally, the sentinel value is -1.
Example: Python while loop with user input
Python3
Output:
Explanation:
- First, it asks the user to input a number. if the user enters -1 then the loop will not execute
- User enter 6 and the body of the loop executes and again ask for input
- Here user can input many times until he enters -1 to stop the loop
- User can decide how many times he wants to enter input
Example: While loop on Boolean values:
One common use of boolean values in while loops is to create an infinite loop that can only be exited based on some condition within the loop. For example:
Python3
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5 Count is 6 Count is 7 Count is 8 Count is 9 Count is 10 The loop has ended.
In this example, we initialize a counter and then use an infinite while loop (True is always true) to increment the counter and print its value. We check if the counter has reached a certain value and if so, we exit the loop using the break statement.
Here's a brief introduction to some essential aspects of Python:
- Installation: Before you start coding in Python, you need to install it on your computer. You can download the latest version from the official Python website (https://www.python.org/downloads/). Python is available for various operating systems, including Windows, macOS, and Linux.
- How to install python
- Running Python: Once Python is installed, you can open the Python interpreter, also known as the REPL (Read-Eval-Print Loop), where you can type Python code and see the results immediately. Alternatively, you can write your code in a text editor and save it with the
.py
extension. Then, you can run the script using the Python interpreter. - Hello, World!: The traditional starting point in programming is writing a simple "Hello, World!" program. In Python, it looks like this:
- Easy-to-Read Syntax: Python uses indentation and whitespace to structure code, which enhances readability. This design philosophy, often referred to as the "Pythonic" way, encourages developers to write clean and concise code.
- Interpreted Language: Python is an interpreted language, meaning that code is executed line-by-line by an interpreter at runtime. This approach allows for faster development and easier debugging.
- Object-Oriented: Python supports object-oriented programming (OOP), allowing developers to create and work with classes and objects, promoting code organization and reusability.
- Large Standard Library: Python comes with a comprehensive standard library that provides a wide range of modules and packages, enabling developers to perform various tasks without having to write additional code from scratch.
- Cross-Platform: Python is a cross-platform language, meaning it can run on different operating systems such as Windows, macOS, and various Linux distributions, with minimal modifications.
- Extensible and Embeddable: Python can be extended with C/C++ libraries, and it can be embedded in other applications to provide scripting capabilities.
- Community and Ecosystem: Python has a vibrant and supportive community, which has contributed to the development of a vast ecosystem of third-party libraries and frameworks for various purposes, including web development, data analysis, machine learning, and more.
- Variables and Data Types: In Python, you don't need to declare the data type of a variable explicitly. Python uses dynamic typing, which means the data type is inferred automatically. Some common data types in Python include integers, floats, strings, lists, tuples, dictionaries, and booleans.
- Control Flow: Python supports typical control flow structures, such as if-else statements and loops (for and while loops), which allow you to make decisions and repeat actions based on certain conditions.
- Functions: Functions are blocks of reusable code that perform specific tasks. In Python, you can define functions using the def keyword and call them later in your code.
- File Handling: Python makes it easy to read from and write to files on your computer, which is crucial for working with data and managing information.
- Lists and Dictionaries: Lists are ordered collections of items, while dictionaries are unordered collections of key-value pairs. Both are essential data structures in Python that allow you to store and manipulate data efficiently.
- Modules and Packages: Python's standard library provides a rich set of modules and packages for various tasks. You can also install third-party libraries using package managers like pip, which greatly extends Python's capabilities.
- Object-Oriented Programming (OOP): Python supports object-oriented programming, enabling you to create classes and objects for more organized and reusable code.
0 Comments