0% found this document useful (0 votes)
8 views

unit 1

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, known for its readability and versatility across various applications such as web development, data science, and machine learning. Key features include dynamic typing, extensive libraries, and cross-platform compatibility, making it a popular choice for beginners and professionals alike. The document also covers Python syntax, data types, and expressions, providing examples of how to use them effectively.

Uploaded by

dummy10802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

unit 1

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, known for its readability and versatility across various applications such as web development, data science, and machine learning. Key features include dynamic typing, extensive libraries, and cross-platform compatibility, making it a popular choice for beginners and professionals alike. The document also covers Python syntax, data types, and expressions, providing examples of how to use them effectively.

Uploaded by

dummy10802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Introduction to Python

Python is a widely used high-level, interpreted 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 used for:

 Web Development: Frameworks like Django, Flask.


 Data Science and Analysis: Libraries like Pandas, NumPy, Matplotlib.
 Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.
 Automation and Scripting: Automate repetitive tasks.
 Game Development: Libraries like Pygame.
 Web Scraping: Tools like BeautifulSoup, Scrapy.
 Desktop Applications: GUI frameworks like Tkinter, PyQt.
 Scientific Computing: SciPy, SymPy.
 Internet of Things (IoT): MicroPython, Raspberry Pi.
 DevOps and Cloud: Automation scripts and APIs.
 Cybersecurity: Penetration testing and ethical hacking tools.

Key Features of Python


Python is Easy to Learn and Use: There is no prerequisite to start Python, since it is Ideal
programming language for beginners.

High Level Language: Python don’t let you worry about low-level details, like memory
management, hardware-level operations etc.

Python is Interpreted: Code is executed line-by-line directly by interpreter, and no need for
separate compilation. Which means –
 You can run the same code across different platforms.
 You can make the changes in code without restarting the program.

Dynamic Typed: Python is a dynamic language, meaning there are no need to explicitly
declare the data type of a variable. Type is checked during runtime, not at compile time.
Object Oriented: Python supports object-oriented concepts like classes, inheritance, and
polymorphism etc. OOPs empowers Python with modularity, reusability and easy to maintain
code.
Extensive Library are Available: Python has huge set of library and modules, which can
make development lot easier and faster.
Open-Source with Huge community Support: Along with opensource, Python is blessed
with very large community contributing to its further development.
Cross Platform: Same Python code can run on Windows, macOS and Linux, without any
modification in code.
Good Career Opportunities: Python is in high demand across industries like Software
development, AI, finance, and cloud computing etc.

Applications of Python in Modern Technology

Python has a wide range of applications, including:

 Full-Stack Web Development: Building complete web applications and RESTful


APIs.
 Artificial Intelligence and Machine Learning: Creating AI models and ML
applications.
 Finance and Trading: Developing financial models and implementing algorithmic
trading.
 Chatbots and Voice Assistants: Building intelligent applications using Natural
Language Processing (NLP).
 Blockchain and Cryptocurrency: Developing blockchain systems and
cryptocurrency platforms.

Python Interpreter
Python is an interpreted language because it executes line-by-line instructions. There are
actually two way to execute python code one is in Interactive mode and another thing is
having Python prompts which is also called script mode. Python does not convert high level
code into low level code as many other programming languages do rather it will scan the
entire code into something called bytecode. every time when Python developer runs the code
and start to execute the compilation part execute first and then it generate an byte code which
get converted by PVM Python Virtual machine that understand the analogy and give the
desired output.

Interpreters

Interpreters are the computer program that will convert the source code or an high level
language into intermediate code (machine level language). It is also called translator in
programming terminology. Interpreters executes each line of statements slowly. This process
is called Interpretation. For example Python is an interpreted language, PHP, Ruby, and
JavaScript.

Working of Interpreter
Example: Here is the simple Python program that takes two inputs as a and b and prints the
sum in the third variable which is c. It follows sequential as well as functional execution of
programs

a=3
b=7
c=a+b
print(c) # output 10

Output
10

Functioning of Interpreters in Python

Python interpreter is written in C programming. Python interpreter called "CPython". Initially


in source code analysis, Python get source and check for some Indentation rule and check for
errors. if there are any errors Python stops its execution and make to modify to prevent errors.
This process is called Lexical analysis in python which states that dividing the source code
into list of individual tokens.In Byte code generation, once the python interpreter receives the
tokens, it generates AST (Abstract Structure tree) which coverts to byte code and then byte
code can be saved in (.py) extension. At last, by using Python Virtual Machine, interpreter
loads the machine language and PVM converts in into 0s and 1 s which prints the results.

Python Syntax

Python syntax is like grammar for this programming language. Syntax refers to the set of
rules that defines how to write and organize code so that the Python interpreter can
understand and run it correctly. These rules ensure that your code is structured, formatted,
and error-free.

Indentation in Python
Python Indentation refers to the use of whitespace (spaces or tabs) at the beginning of code
line. It is used to define the code blocks. Indentation is crucial in Python because, unlike
many other programming languages that use braces "{}" to define blocks, Python uses
indentation. It improves the readability of Python code, but on other hand it became difficult
to rectify indentation errors. Even one extra or less space can leads to indentation error.

if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")
Python Data Types

Python Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since everything is
an object in Python programming, Python data types are classes and variables are instances
(objects) of these classes. The following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

Numbers

Numeric values are stored in numbers. The whole number, float, and complex qualities have
a place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.

When a number is assigned to a variable, Python generates Number objects. For instance,

a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three kinds of numerical data.

 Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. Its worth has a place with int.
 Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
 Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like
2.14j, 2.0 + 2.3j, etc.

Sequence Type

 A sequence is an ordered collection of items, indexed by positive


integers.
 It is a combination of mutable (value can be changed) and
immutable (values cannot be changed) data types.

String

The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using.

 single quotes (' ') Eg, 'This a string in single quotes'


 double quotes (" ") Eg, "'This a string in double quotes'"
 triple quotes(""" """) Eg, This is a paragraph.
 It is made up of multiple lines and sentences."""
 Individual character in a string is accessed using a subscript (index).

When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.

Because the operation "Python" *2 returns "Python," the operator * is referred to as a


repetition operator.

Example - 1

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)

Output:

string using double quotes


A multiline
string

List

Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections [].

1. list1 = [1, "hi", "Python", 2]


2. #Checking type of given list
3. print(type(list1))
4. #Printing the list1
5. print (list1)

Output:

[1, 'hi', 'Python', 2]


Tuple

In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.

Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)

Output:

<class 'tuple'>
('hi', 'Python', 2)

Dictionary

A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.

Example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2. # Printing dictionary
3. print (d)
4. # Accesing value using keys
5. print("1st name is "+d[1])
6. print("2nd name is "+ d[4])
7. print (d.keys())
8. print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. True and False can be represented by 0 or any
value that is not zero.

Example.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set

The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the
curly braces and separated by a comma to create the set or the built-in function set() is used to
create the set. It can contain different kinds of values.

Look at the following example.

1. # Creating Empty set


2. set1 = set()
3. set2 = {'James', 2, 3,'Python'}
4. #Printing Set value
5. print(set2)
6. # Adding element to the set
7. set2.add(10)
8. print(set2)
9. #Removing element from the set
10. set2.remove(2)
11. print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other
value.

1. Constant Expressions: These are the expressions that have constant values only.

Example:

# Constant Expressions
x = 15 + 1.3

print(x)

Output
16.3

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric


values, operators, and sometimes parenthesis. The result of this type of expression is
also a numeric value. The operators used in these expressions are arithmetic operators
like addition, subtraction, etc. Here are some arithmetic operators in Python:

Operators Syntax Functioning


+ x + y Addition
– x – y Subtraction
* x * y Multiplication
/ x / y Division
// x // y Quotient
% x % y Remainder
** x ** y Exponentiation

Example:

# Arithmetic Expressions
x = 40
y = 12

add = x + y
sub = x - y
pro = x * y
div = x / y

print(add)
print(sub)
print(pro)
print(div)

Output
52
28
480
3.3333333333333335

3. Integral Expressions: These are the kind of expressions that produce only integer
results after all computations and type conversions.

Example:

# Integral Expressions
a = 13
b = 12.0

c = a + int(b)
print(c)

Output
25

4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.

Example:

# Floating Expressions
a = 13
b =5

c =a /b
print(c)
Output
2.6

5. Relational Expressions: In these types of expressions, arithmetic expressions are written


on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are
evaluated first, and then compared as per relational operator and produce a boolean output in
the end. These expressions are also called Boolean expressions.

Example:

# Relational Expressions
a = 21
b = 13
c = 40
d = 37

p = (a + b) >= (c - d)
print(p)
Output
True

6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is
equal to 9. As we know it is not correct, so it will return False. Studying logical expressions,
we also come across some logical operators which can be seen in logical expressions most
often. Here are some logical operators in Python:

Operator Syntax Functioning


And P and Q It returns true if both P and Q are true otherwise returns false
Or P or Q It returns true if at least one of P and Q is true
Not not P It returns true if condition P is false

Example:

Let’s have a look at an exemplar code :

P = (10 == 9)
Q = (7 > 5)

# Logical Expressions
R = P and Q
S = P or Q
T = not P

print(R)
print(S)
print(T)

Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.

Example:

# Bitwise Expressions
a = 12

x = a >> 2
y = a << 1

print(x, y)
Output
3 24

8. Combinational Expressions: We can also use different types of expressions in a single


expression, and that will be termed as combinational expressions.

Example:

# Combinational Expressions
a = 16
b = 12

c = a + (b >> 1)
print(c)
Output
22

But when we combine different types of expressions or use multiple operators in a single
expression, operator precedence comes into play.

Multiple operators in expression (Operator Precedence)

It’s a quite simple process to get the result of an expression if there is only one operator in an
expression. But if there is more than one operator in an expression, it may give different
results on basis of the order of operators executed. To sort out these confusions, the operator
precedence is defined. Operator Precedence simply defines the priority of operators that
which operator is to be executed first. Here we see the operator precedence in Python, where
the operator higher in the list has more precedence or priority:

Precedence Name Operator


1 Parenthesis ()[]{}
2 Exponentiation **
3 Unary plus or minus, complement -a , +a , ~a
4 Multiply, Divide, Modulo / * // %
5 Addition & Subtraction + –
6 Shift Operators >> <<
7 Bitwise AND &
8 Bitwise XOR ^
9 Bitwise OR |
Precedence Name Operator
10 Comparison Operators >= <= > <
11 Equality Operators == !=
12 Assignment Operators = += -= /= *=
13 Identity and membership operators is, is not, in, not in
14 Logical Operators and, or, not

Example python program:

# Multi-operator expression

a = 10 + 3 * 4
print(a)

b = (10 + 3) * 4
print(b)

c = 10 + (3 * 4)
print(c)
Output
22
52
22

Control Flow Statements

Control flow refers to the order in which statements within a program execute. While programs
typically follow a sequential flow from top to bottom, there are scenarios where we need more
flexibility.

Control flow statements are fundamental components of programming languages that allow
developers to control the order in which instructions are executed in a program. They enable
execution of a block of code multiple times, execute a block of code based on conditions,
terminate or skip the execution of certain lines of code, etc.

The flow control statements are divided into three categories

1. Conditional statements
2. Iterative statements.
3. Transfer statements
Conditional statements

In Python, condition statements act depending on whether a given condition is true or false.
Different blocks of codes can be executed depending on the outcome of a condition.
Condition statements always evaluate to either True or False.

There are three types of conditional statements.

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

Iterative statements

In Python, iterative statements allow us to execute a block of code repeatedly as long as


the condition is True. We also call it a loop statements. Iterative statements

In Python, iterative statements allow us to execute a block of code repeatedly as long as the
condition is True. It can all as loop statements.

Python provides us the following two loop statement to perform some actions repeatedly

1. for loop
2. while loop

Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain
manner. For this purpose, we use three types of transfer statements.

1. break statement
2. continue statement
3. pass statements

If statement in Python
In control statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False.

If the condition is True, then the True block of code will be executed, and if the condition is
False, then the block of code is skipped, and The controller moves to the next line

Syntax of the if statement

if condition:
statement 1
statement 2
statement n

Python if statements

Let’s see the example of the if statement. In this example, we will calculate the square of a
number if it greater than 5

Example

number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output

36
Next lines of code

If – else statement

The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.

Syntax of the if-else statement

if condition:
statement 1
else:
statement 2

If the condition is True, then statement 1 will be executed If the condition is False, statement
2 will be executed. See the following flowchart for more detail.

Python if-else statements

Example

password = input('Enter password ')

if password == "PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")

Output 1:

Enter password PYnative@#29


Correct password
Output 2:

Enter password PYnative


Incorrect Password

Chain multiple if statement in Python

In Python, the if-elif-else condition statement has an elif blocks to chain multiple
conditions one after another. This is useful when you need to check multiple conditions.

With the help of if-elif-else we can make a tricky decision. The elif statement checks
multiple conditions one by one and if the condition fulfills, then executes that code.

Syntax of the if-elif-else statement:

if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement

Example

def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")

user_check(1)
user_check(2)
user_check(3)
user_check(4)

Output:

Admin
Editor
Guest
Wrong entry

Nested if-else statement

In Python, the nested if-else statement is an if statement inside another if-else statement.
It is allowed in Python to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The nested if-else is useful
when we want to make a series of decisions.

Syntax of the nested-if-else:

if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block

Example: Find a greater number between two numbers

num1 = int(input('Enter first number '))


num2 = int(input('Enter second number '))

if num1 >= num2:


if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)

Output 1:

Enter first number 56


Enter second number 15
56 is greater than 15

Output 2:

Enter first number 29


Enter second number 78
29 is smaller than 78

Single statement suites

Whenever we write a block of code with multiple if statements, indentation plays an


important role. But sometimes, there is a situation where the block contains only a single line
statement.

Instead of writing a block after the colon, we can write a statement immediately after the
colon.

Example

number = 56
if number > 0: print("positive")
else: print("negative")
Similar to the if statement, while loop also consists of a single statement, we can place that
statement on the same line.

Example

x = 1
while x <= 5: print(x,end=" "); x = x+1

Output

1 2 3 4 5

for loop in Python


Using for loop, we can iterate any sequence or iterable variable. The sequence can be string,
list, dictionary, set, or tuple.

Python for loop

Syntax of for loop:

for element in sequence:


body of for loop

Example to display first ten numbers using for loop

for i in range(1, 11):


print(i)

Output

1
2
3
4
5
6
7
8
9
10

While loop in Python


In Python, The while loop statement repeatedly executes a code block while a particular
condition is true.

In a while-loop, every time the condition is checked at the beginning of the loop, and if it is
true, then the loop’s body gets executed. When the condition became False, the controller
comes out of the block.

Python while loop

Syntax of while-loop

while condition :
body of while loop

Example to calculate the sum of first ten numbers

num = 10
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i + 1
print("Sum of first 10 number is:", sum)

Output
Sum of first 10 number is: 55

Break Statement in Python


The break statement is used inside the loop to exit out of the loop. It is useful when we want
to terminate the loop as soon as the condition is fulfilled instead of doing the remaining
iterations. It reduces execution time. Whenever the controller encountered a break statement,
it comes out of that loop immediately

Example of using a break statement

for num in range(10):


if num > 5:
print("stop processing.")
break
print(num)

Output

0
1
2
3
4
5
stop processing.

Continue statement in python


The continue statement is used to skip the current iteration and continue with the next
iteration.

Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the body
of the loop for other numbers.

Example of a continue statement

for num in range(3, 8):


if num == 5:
continue
else:
print(num)

Output

3
4
6
7

Pass statement in Python


The pass is the keyword In Python, which won’t do anything. Sometimes there is a situation
in programming where we need to define a syntactically empty block. We can define that
block with the pass keyword.

A pass statement is a Python null statement. When the interpreter finds a pass statement in
the program, it returns no operation. Nothing happens when the pass statement is executed.

It is useful in a situation where we are implementing new methods or also in exception


handling. It plays a role like a placeholder.

Example

months = ['January', 'June', 'March', 'April']


for mon in months:
pass
print(months)

Output

['January', 'June', 'March', 'April']

Unit II

List Comprehensions
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of list comprehension:

Syntax: output_list = [output_exp for var in input_list if (var satisfies this condition)]

Generating Even list using List comprehensions

It creates a new list named list_using_comp by iterating through each element var in the
input_list. Elements are included in the new list only if they satisfy the condition, which
checks if the element is even. As a result, the output list will contain all even numbers.

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

list_using_comp = [var for var in input_list if var % 2 == 0]

print("Output List using list comprehensions:",


list_using_comp)

Output:

Output List using list comprehensions: [2, 4, 4, 6]

Dictionary Comprehensions
Extending the idea of list comprehensions, we can also create a dictionary using dictionary
comprehensions. The basic structure of a dictionary comprehension looks like below.

output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

Example 1: Generating odd number with their cube values without using dictionary
comprehension

input_list = [1, 2, 3, 4, 5, 6, 7]

output_dict = {}

for var in input_list:


if var % 2 != 0:
output_dict[var] = var**3

print("Output Dictionary using for loop:",output_dict )

Output:

Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}

Example 2: Generating odd number with their cube values with using dictionary
comprehension

We are using dictionary comprehension in Python. It initializes an list containing numbers


from 1 to 7. It then constructs a new dictionary using dictionary comprehension. For each odd
number var in the list, it calculates the cube of the number and assigns the result as the
value to the key var in the dictionary.

input_list = [1,2,3,4,5,6,7]

dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}

print("Output Dictionary using dictionary comprehensions:",dict_using_comp)

Output:

Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7:


343}

Set Comprehensions
Set comprehensions are pretty similar to list comprehensions. The only difference between
them is that set comprehensions use curly brackets { }

Example 1 : Checking Even number Without using set comprehension

Suppose we want to create an output set which contains only the even numbers that are
present in the input list. Note that set will discard all the duplicate values.

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()

for var in input_list:


if var % 2 == 0:
output_set.add(var)

print("Output Set using for loop:", output_set)

Output:

Output Set using for loop: {2, 4, 6}

Example 2: Checking Even number using set comprehension

We will use set comprehension to initializes a list with integer values. The code then creates a
new set using set comprehension. It iterates through the elements of the input_list, and for
each element, it checks whether it’s even. If the condition is met, the element is added to the
set. The printed output which will contain unique even numbers from the list.

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

set_using_comp = {var for var in input_list if var % 2 == 0}

print("Output Set using set comprehensions:",

set_using_comp)

Output:

Output Set using set comprehensions: {2, 4, 6}

Generator Comprehensions
Generator Comprehensions are very similar to list comprehensions. One difference between
them is that generator comprehensions use circular brackets whereas list comprehensions use
square brackets. The major difference between them is that generators don’t allocate memory
for the whole list. Instead, they generate each value one by one which is why they are
memory efficient.

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

output_gen = (var for var in input_list if var % 2 == 0)

print("Output values using generator comprehensions:", end = ' ')


for var in output_gen:

print(var, end = ' ')

Output:

Output values using generator comprehensions: 2 4 4 6

You might also like