Python


What is Python?
 

  • 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.


WindowsThere 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/.

LinuxPython 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.

macOSGenerally, 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.

# Script Begins
  
print("GeeksQuiz")
  
# Scripts Ends

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

  1. Emphasis on code readability, shorter codes, ease of writing
  2. Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.
  3. Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.
  4. There exists inbuilt functions for almost all of the frequently used concepts.
  5. 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 

  • No need to declare anything. An assignment statement binds a name to an object, and the object can be of any type.
  • No type casting is  required when using container objects

Statically Typed

  • All variable names (along with their types) must be explicitly declared. Attempting to assign an object of the wrong type to a variable name triggers a type exception.
  • Type casting is required when using container objects.
Concise Express much in limited wordsVerbose Contains more words
CompactLess Compact
Uses Indentation for structuring codeUses braces for structuring code

The classical Hello World program illustrating the relative verbosity of a Java Program and Python Program
Java Code

public class HelloWorld
{
   public static void main (String[] args)
   {
      System.out.println("Hello, world!");
   }
}

Python Code

print("Hello, world!")

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

2

Command Line interface

3

Softwares making use of Python

Python has been successfully embedded in a number of software products as a scripting language.

  1. GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.
  2. Python has also been used in artificial intelligence
  3. Python is often used for natural language processing tasks.

Current Applications of Python

  1. A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity
  2. Python has seen extensive use in the information security industry, including in exploit development.
  3. Raspberry Pi– single board computer uses Python as its principal user-programming language.
  4. Python is now being used Game Development areas also.

Pros:

  1. Ease of use
  2. Multi-paradigm Approach

Cons:

  1. Slow speed of execution compared to C,C++
  2. Absence from mobile computing and browsers
  3. 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 : 

  1. Presence of third-party modules 
  2. Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) 
  3. Open source and community development 
  4. Versatile, Easy to read, learn and write
  5. User-friendly data structures 
  6. High-level language 
  7. Dynamically typed language(No need to mention data type based on the value assigned, it takes data type) 
  8. Object-oriented language 
  9. Portable and Interactive
  10. Ideal for prototypes – provide more functionality with less coding
  11. 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.)
  12. (IoT)Internet of Things Opportunities
  13. Interpreted Language
  14. Portable across Operating systems 

 

Applications : 

  1. GUI based desktop applications
  2. Graphic design, image processing applications, Games, and Scientific/ computational Applications
  3. Web frameworks and applications 
  4.  Enterprise and Business applications 
  5.  Operating Systems 
  6. Education
  7. Database Access
  8. Language Development 
  9.  Prototyping 
  10. Software Development 

Organizations using Python : 

  1. Google(Components of Google spider and Search Engine) 
  2. Yahoo(Maps) 
  3. YouTube 
  4. Mozilla 
  5. Dropbox 
  6. Microsoft 
  7. Cisco 
  8. Spotify 
  9. 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).

# Python code for "Hello World"
# nothing else to type...see how simple is the syntax.
  
print("Hello World")      

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.

Introduction and Setup

  1. 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 :

  2. 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 :
  3. 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.

    # Python program to declare variables
    myNumber = 3
    print(myNumber)
      
    myNumber2 = 4.5
    print(myNumber2)
      
    myNumber ="helloworld"
    print(myNumber)

    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 ListDictionaryTuple 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.

    # Python program to illustrate a list 
      
    # creates a empty list
    nums = [] 
      
    # appending data in list
    nums.append(21)
    nums.append(40.5)
    nums.append("String")
      
    print(nums)

    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.

    # Python program to illustrate
    # getting input from user
    name = input("Enter your name: "
      
    # user entered the name 'harssh'
    print("hello", name)

    Output:

    hello harssh   

    # Python3 program to get input from user
      
    # accepting integer from the user
    # the return type of input() function is string ,
    # so we need to convert the input to integer
    num1 = int(input("Enter num1: "))
    num2 = int(input("Enter num2: "))
      
    num3 = num1 * num2
    print("Product is: ", num3)

    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)

    # Python program to illustrate
    # selection statement
      
    num1 = 34
    if(num1>12):
        print("Num1 is good")
    elif(num1>35):
        print("Num2 is not gooooo....")
    else:
        print("Num2 is great")

    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

    # Python program to illustrate
    # functions
    def hello():
        print("hello")
        print("hello again")
    hello()
      
    # calling function
    hello()               

    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.

    # Python program to illustrate 
    # function with main
    def getInteger():
        result = int(input("Enter integer: "))
        return result
      
    def Main():
        print("Started")
      
        # calling the getInteger function and 
        # storing its returned value in the output variable
        output = getInteger()     
        print(output)
      
    # now we are required to tell Python 
    # for 'Main' function existence
    if __name__=="__main__":
        Main()

    Output:

    Started
    Enter integer: 5
    

    Iteration (Looping)

    As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here.

    # Python program to illustrate
    # a simple for loop
      
    for step in range(5):    
        print(step)

    Output:

    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.

    # Python program to illustrate
    # math module
    import math
      
    def Main():
        num = -85
      
        # fabs is used to get the absolute 
        # value of a decimal
        num = math.fabs(num) 
        print(num)
          
          
    if __name__=="__main__":
        Main()

    Output:

    85.0
    Python Language advantages and applications
    Python 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: 

    1. Presence of third-party modules 
    2. Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics, etc.) 
    3. Open source and large active community base 
    4. Versatile, Easy to read, learn and write
    5. User-friendly data structures 
    6. High-level language 
    7. Dynamically typed language(No need to mention data type based on the value assigned, it takes data type) 
    8. Object-Oriented and Procedural  Programming language
    9. Portable and Interactive
    10. Ideal for prototypes – provide more functionality with less coding
    11. 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.)
    12. Internet of Things(IoT) Opportunities
    13. Interpreted Language
    14. Portable across Operating systems 

    Disadvantages:

    1. 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.
    2. 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.
    3. Memory consumption: Python can consume a lot of memory, especially when working with large datasets or running complex algorithms.
    4. 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.
    5. Packaging and versioning: Python has a large number of packages and libraries, which can sometimes lead to versioning issues and package conflicts.
    6. 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.
    7. 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.

    Applications: 

    1. GUI-based desktop applications
    2. Graphic design, image processing applications, Games, and Scientific/ computational Applications
    3. Web frameworks and applications 
    4. Enterprise and Business applications 
    5. Operating Systems 
    6. Education
    7. Database Access
    8. Language Development 
    9. Prototyping 
    10. Software Development
    11.  Data Science and Machine Learning
    12. Scripting

    Organizations using Python : 

    1. Google(Components of Google spider and Search Engine) 
    2. Yahoo(Maps) 
    3. YouTube 
    4. Mozilla 
    5. Dropbox 
    6. Microsoft 
    7. Cisco 
    8. Spotify 
    9. Quora 
  4. Facebook

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:

  1. 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.
  2. Data types: Python 3 supports several built-in data types, including integers, floats, strings, booleans, lists, tuples, and dictionaries.
  3. Operators: Python 3 supports a variety of operators, including arithmetic operators (+, -, *, /), comparison operators (>, <, ==, !=), and logical operators (and, or, not).
  4. 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.
  5. 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:

  1. Python 3 has a simple syntax that is easy to learn and read, making it a good choice for beginners.
  2. 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.
  3. Python 3 supports multiple programming paradigms, including object-oriented, functional, and procedural programming.
  4. 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.
  5. Python 3 has good support for data analysis and scientific computing, with libraries such as NumPy and Pandas.

Disadvantages of Python 3:

  1. Python 3 can be slower than compiled languages such as C++ or Java, which may be a concern for applications that require high performance.
  2. Python 3 has a global interpreter lock (GIL), which can limit its ability to take advantage of multiple CPU cores.
  3. 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.
  4. 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

# Python code for "Hello World"
# nothing else to type...see how simple is the syntax.
  
print("Hello World")      

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 

  1. 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 : 

 

  1. 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

# Python program to declare variables
myNumber = 3
print(myNumber)
   
myNumber2 = 4.5
print(myNumber2)
   
myNumber ="helloworld"
print(myNumber)
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 ListDictionaryTuple, 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

# Python program to illustrate a list 
   
# creates a empty list
nums = [] 
   
# appending data in list
nums.append(21)
nums.append(40.5)
nums.append("String")
   
print(nums)
Output
[21, 40.5, 'String']

Python3

# Python program to illustrate a Dictionary
  
# creates a empty list
Dict = []
  
# putting integer values
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
  
print(Dict)
  
#Code submitted by Susobhan AKhuli
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Python3

# Python program to illustrate a tuple
    
# creates a tuple which is immutable
tup = ('Geeks', 'For', 'Geeks')
  
print(tup)
  
#Code submitted by Susobhan AKhuli
Output
('Geeks', 'For', 'Geeks')

Python3

# Python program to illustrate a set
  
# define a set and its elements
myset = set(["Geeks", "For", "Geeks"])
  
#as set doesn't have duplicate elements so, 1 geeks will not be printed
print(myset)
  
#Code submitted by Susobhan Akhuli
Output
{'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

# Python program to illustrate
# getting input from user
name = input("Enter your name: "
   
# user entered the name 'harssh'
print("hello", name)

Output:

hello harssh

Python3

# Python3 program to get input from user
   
# accepting integer from the user
# the return type of input() function is string ,
# so we need to convert the input to integer
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
   
num3 = num1 * num2
print("Product is: ", num3)

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

# Python program to illustrate
# selection statement
   
num1 = 34
if(num1>12):
   print("Num1 is good")
elif(num1>35):
   print("Num2 is not gooooo....")
else:
   print("Num2 is great")
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

Python3

# Python program to illustrate
# functions
def hello():
   print("hello")
   print("hello again")
hello()
   
# calling function
hello()
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.

Python3

# Python program to illustrate 
# function with main
def getInteger():
   result = int(input("Enter integer: "))
   return result
   
def Main():
   print("Started")
   
   # calling the getInteger function and 
   # storing its returned value in the output variable
   output = getInteger()     
   print(output)
   
# now we are required to tell Python 
# for 'Main' function existence
if __name__=="__main__":
   Main()

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

# Python program to illustrate
# a simple for loop
   
for step in range(5):    
   print(step)

Python3

# Python program to illustrate
# a simple while loop
step = 0
while(step < 5):
    print(step)
    step = step+1
Output
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

# Python program to illustrate
# math module
import math
   
def Main():
   num = -85
   
   # fabs is used to get the absolute 
   # value of a decimal
   num = math.fabs(num)
   print(num)
       
       
if __name__=="__main__":
   Main()
Output
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.

# Python code to demonstrate working of iskeyword()
 
# importing "keyword" for keyword operations
import keyword
 
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)

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 

print(False == 0)
print(True == 1)
 
print(True + True + True)
print(True + False + False)
 
print(None == 0)
print(None == [])
Output
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. 

and keyword python

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. 
     

or

3 or 0 returns 3 

3 or 10 returns 3 

0 or 0 or 3 or 10 or 0 returns 

  • 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

# showing logical operation
# or (returns True)
print(True or False)
 
# showing logical operation
# and (returns False)
print(False and True)
 
# showing logical operation
# not (returns False)
print(not True)
 
# using "in" to check
if 's' in 'geeksforgeeks':
    print("s is part of geeksforgeeks")
else:
    print("s is not part of geeksforgeeks")
 
# using "in" to loop through
for i in 'geeksforgeeks':
    print(i, end=" ")
 
print("\r")
 
# using is to check object identity
# string is immutable( cannot be changed once allocated)
# hence occupy same memory location
print(' ' is ' ')
 
# using is to check object identity
# dictionary is mutable( can be changed once allocated)
# hence occupy different memory location
print({} is {})

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

# Using for loop
for i in range(10):
 
    print(i, end=" ")
 
    # break the loop as soon it sees 6
    if i == 6:
        break
 
print()
 
# loop from 1 to 10
i = 0
while i < 10:
 
    # If i is equals to 6,
    # continue to next iteration
    # without printing
    if i == 6:
        i += 1
        continue
    else:
        # otherwise print the value
        # of i
        print(i, end=" ")
 
    i += 1
Output
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

# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
 
i = 20
if (i == 10):
    print("i is 10")
elif (i == 20):
    print("i is 20")
else:
    print("i is not present")
Output
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

# def keyword
def fun():
    print("Inside Function")
 
 
fun()
Output
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

# Return keyword
def fun():
    S = 0
 
    for i in range(10):
        S += i
    return S
 
 
print(fun())
 
# Yield Keyword
 
 
def fun():
    S = 0
 
    for i in range(10):
        S += i
        yield S
 
 
for i in fun():
    print(i)
Output
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 program to
# demonstrate instantiating
# a class
 
 
class Dog:
 
    # A simple class
    # attribute
    attr1 = "mammal"
    attr2 = "dog"
 
    # A sample method
    def fun(self):
        print("I'm a", self.attr1)
        print("I'm a", self.attr2)
 
 
# Driver code
# Object instantiation
Rodger = Dog()
 
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
Output
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

# using with statement
with open('file_path', 'w') as file:
    file.write('hello world !')

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

import math as gfg
 
print(gfg.factorial(5))
Output
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

n = 10
for i in range(n):
 
    # pass can be used as placeholder
    # when code is to added later
    pass
Output
 

Lambda

Lambda keyword is used to make inline returning functions with no statements allowed internally. 

Example: Lambda Keyword

# Lambda keyword
g = lambda x: x*x*x
 
print(g(7))
Output
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

# import keyword
from math import factorial
import math
print(math.factorial(10))
 
# from keyword
print(factorial(10))
Output
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

# initializing number
a = 4
b = 0
 
# No exception Exception raised in try block
try:
    k = a//# raises divide by zero exception.
    print(k)
 
# handles zerodivision exception
except ZeroDivisionError:
    print("Can't divide by zero")
 
finally:
    # this block is always executed
    # regardless of exception generation.
    print('This is always executed')
 
# assert Keyword
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Divide by 0 error"
print(a / b)
 
# raise keyword
# Raises an user defined exception
# if strings are not equal
temp = "geeks for geeks"
if temp != "geeks":
    raise TypeError("Both the strings are different.")

Output

Can't divide by zero
This is always executed
The value of a / b is :
AssertionError: Divide by 0 error

# raise keyword
# Raises an user defined exception
# if strings are not equal
temp = "geeks for geeks"
if temp != "geeks":
    raise TypeError("Both the strings are different.")

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

my_variable1 = 20
my_variable2 = "GeeksForGeeks"
 
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
 
# delete both the variables
del my_variable1
del my_variable2
 
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)

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

# global variable
a = 15
b = 10
 
# function to perform addition
def add():
    c = a + b
    print(c)
 
# calling a function
add()
 
# nonlocal keyword
def fun():
    var1 = 10
 
    def gun():
        # tell python explicitly that it
        # has to access var1 initialized
        # in fun on line 2
        # using the keyword nonlocal
        nonlocal var1
         
        var1 = var1 + 10
        print(var1)
 
    gun()
fun()
Output
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:

  1. The if statement
  2. The if-else statement
  3. The nested-if statement
  4. The if-elif-else ladder

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

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.

# python program to illustrate If statement
 
i = 10
 
if (i > 15):
    print("10 is less than 15")
print("I am Not in if")

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

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).

# python program to illustrate If else statement
#!/usr/bin/python
 
i = 20
if (i < 15):
    print("i is smaller than 15")
    print("i'm in if Block")
else:
    print("i is greater than 15")
    print("i'm in else Block")
print("i'm not in if and not in else Block")

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.

# Explicit function
def digitSum(n):
    dsum = 0
    for ele in str(n):
        dsum += int(ele)
    return dsum
 
 
# Initializing list
List = [367, 111, 562, 945, 6726, 873]
 
# Using the function on odd elements of the list
newList = [digitSum(i) for i in List if i & 1]
 
# Displaying new list
print(newList)

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

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.

# python program to illustrate nested If statement
 
i = 10
if (i == 10):
   
    #  First if statement
    if (i < 15):
        print("i is smaller than 15")
         
    # Nested - if statement
    # Will only be executed if statement above
    # it is true
    if (i < 12):
        print("i is smaller than 12 too")
    else:
        print("i is greater than 15")

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

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.

# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
 
i = 20
if (i == 10):
    print("i is 10")
elif (i == 15):
    print("i is 15")
elif (i == 20):
    print("i is 20")
else:
    print("i is not present")

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.

# Python program to illustrate short hand if
i = 10
if i < 15: print("i is less than 15")

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.

# Python program to illustrate short hand if-else
i = 10
print(True) if i < 15 else print(False)

Output: 

True
Python For Loops

In 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 StringTupleListSet, or Dictionary

Note: In Python, for loops only implement the collection-based iteration.

For Loops Syntax

for var in iterable:
    # statements

Flowchart of for loop

For Loop Flowchart

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.

# Python program to illustrate
# Iterating over a list
l = ["geeks", "for", "geeks"]
 
for i in l:
    print(i)

Output :

geeks
for
geeks

Python 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.

# Iterating over dictionary
print("Dictionary Iteration")
 
d = dict()
 
d['xyz'] = 123
d['abc'] = 345
for i in d:
    print("% s % d" % (i, d[i]))

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.

# Iterating over a String
print("String Iteration")
 
s = "Geeks"
for i in s:
    print(i)

Output:

String Iteration
G
e
e
k
s

Python 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.

for i in range(0, 10, 2):
    print(i)

Output :

0
2
4
6
8

Python 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.

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

Output :

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3 

Python 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.

fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "green"]
for fruit, color in zip(fruits, colors):
    print(fruit, "is", color)

Output :

apple is red
banana is yellow
cherry is green

Python 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.

t = ((1, 2), (3, 4), (5, 6))
for a, b in t:
    print(a, b)

Output :

1 2
3 4
5 6

Loop 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.

# Prints all letters except 'e' and 's'
 
for letter in 'geeksforgeeks':
 
    if letter == 'e' or letter == 's':
        continue
    print('Current Letter :', letter)

Output: 

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Python For Loop with Break Statement

Python break statement brings control out of the loop.

for letter in 'geeksforgeeks':
 
    # break the loop as soon it sees 'e'
    # or 's'
    if letter == 'e' or letter == 's':
        break
 
print('Current Letter :', letter)

Output: 

Current Letter : e

Python For Loop with Pass Statement

The pass statement to write empty loops. Pass is also used for empty control statements, functions, and classes.

# An empty loop
for letter in 'geeksforgeeks':
    pass
print('Last Letter :', letter)

Output: 

Last Letter : s 

Python 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.

# Python Program to
# show range() basics
 
# printing a number
for i in range(10):
    print(i, end=" ")
 
# performing sum of first 10 numbers
sum = 0
for i in range(1, 10):
    sum = sum + i
print("\nSum of first 10 numbers :", sum)

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.

# Python program to demonstrate
# for-else loop
 
for i in range(1, 4):
    print(i)
else# Executed because no break in for
    print("No Break\n")

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

 

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

# Python program to illustrate
# while loop
count = 0
while (count < 3):
    count = count + 1
    print("Hello Geek")
Output
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

# checks if list still
# contains any element
a = [1, 2, 3, 4]
 
while a:
    print(a.pop())
Output
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

# Python program to illustrate
# Single statement while block
count = 0
while (count < 5): count += 1; print("Hello Geek")
Output
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

# Prints all letters except 'e' and 's'
i = 0
a = 'geeksforgeeks'
 
while i < len(a):
    if a[i] == 'e' or a[i] == 's':
        i += 1
        continue
         
    print('Current Letter :', a[i])
    i += 1
Output
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

# break the loop as soon it sees 'e'
# or 's'
i = 0
a = 'geeksforgeeks'
 
while i < len(a):
    if a[i] == 'e' or a[i] == 's':
        i += 1
        break
         
    print('Current Letter :', a[i])
    i += 1
Output
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

# An empty loop
a = 'geeksforgeeks'
i = 0
 
while i < len(a):
    i += 1
    pass
   
print('Value of i :', i)
Output
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

# Python program to demonstrate
# while-else loop
 
i = 0
while i < 4:
    i += 1
    print(i)
else# Executed because no break in for
    print("No Break\n")
 
i = 0
while i < 4:
    i += 1
    print(i)
    break
else# Not executed as there is a break
    print("No Break")
Output
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

a = int(input('Enter a number (-1 to quit): '))
 
while a != -1:
    a = int(input('Enter a number (-1 to quit): '))

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

# Initialize a counter
count = 0
 
# Loop infinitely
while True:
    # Increment the counter
    count += 1
    print(f"Count is {count}")
 
    # Check if the counter has reached a certain value
    if count == 10:
        # If so, exit the loop
        break
 
# This will be executed after the loop exits
print("The loop has ended.")
Output
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:

  1. 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.
  2. How to install python
  3. 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.
  4. Hello, World!: The traditional starting point in programming is writing a simple "Hello, World!" program. In Python, it looks like this:

Python Features:


Key features of Python include:
  • 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.
fundamental to understanding Python:
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. Object-Oriented Programming (OOP): Python supports object-oriented programming, enabling you to create classes and objects for more organized and reusable code.


Post a Comment

0 Comments