0% found this document useful (0 votes)
8 views25 pages

UNIT 1 PythonNotes

This document provides an introduction to Python programming, covering its advantages, features, and fundamental concepts such as variables, data types, and control structures. It highlights Python's versatility in various applications including web development, data science, and automation, while also explaining key programming principles like object-oriented and functional programming. Additionally, the document details Python's data types, variable assignment, and the importance of comments in code for readability.

Uploaded by

rameshapositive
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 views25 pages

UNIT 1 PythonNotes

This document provides an introduction to Python programming, covering its advantages, features, and fundamental concepts such as variables, data types, and control structures. It highlights Python's versatility in various applications including web development, data science, and automation, while also explaining key programming principles like object-oriented and functional programming. Additionally, the document details Python's data types, variable assignment, and the importance of comments in code for readability.

Uploaded by

rameshapositive
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

UNIT – I FUNDAMENTALS OF PYTHON

Introduction to Python – Advantages of Python programming – Variables and Data types –


Comments – Indentation – I/O function – Operators – Selection control structures – Looping
control structures – Functions: Declaration – Types of arguments – Anonymous functions:
Lambda.

1.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 a programming language that lets you work
quickly and integrate systems more efficiently.

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

1.2 Features
Python provide lot of features for the programmers.
 Object-Oriented and Functional
Python is an object-oriented language, from the ground up. It follow object and class
concept. Its class model supportsadvanced notions such as polymorphism, operator
overloading, and multiple inheritance; Like C++, Python supports procedure-oriented
programming as well as object-oriented programming.In addition to its original procedural
(statement-based) and object-oriented (classbased)paradigms, python borrows functional
programming concepts —a set that by most measures includes generators, comprehensions,
closures,maps, decorators, anonymous function lambdas, and first-class function objects.
 Free and Open Source
Python is completely free to use and distribute. As with other open source software,such
as Tcl, Perl, Linux, and Apache, you can fetch the entire Python system’s sourcecode for free
on the Internet. There are no restrictions on copying it, embedding it inyour systems, or
shipping it with your products. This is called FLOSS(Free/Libre and Open Source Software).
 Portable
The standard implementation of Python is written in portable ANSI C, and it compilesand
runs on virtually every major platform currently in use. For example, Python programsrun
today on everything from PDAs to supercomputers. Python can run equally on different
platforms such as Windows, Linux, Unix and Macintosh etc.
 Relatively Easy to Use and Learn
Compared to alternative languages, python programming is extremely simple to learn.
It offers an easy to understand syntax, simple setup, and has many practical applications in
web development. To run a Python program, you simply type it and
run it. There are no intermediate compile and link steps, like there are for languagessuch as C
or C++. Python executes programs immediately, which makes for an interactive
programming experience and rapid turnaround after program changes
 Interpreted
Python is an interpreted language i.e. interpreter executes the code line by line at a time.
When you use an interpreted language like Python, there is no separate compilation and
execution steps. You just run the program from the source code. This makesdebugging easy
and thus suitable for beginners. Internally, Python converts the source code into an
intermediate form called bytecodes and then translates this into the native language of your
specific computer and then runs it. You just run your programs and you never have to worry
about linking and loading with libraries, etc.
 Extensible
If needed, Python code can be written in other languages like C++. This makes Python an
extensible language, meaning that it can be extended to other languages. Python extensions
can be written in C and C++ for the standard implementation of python in C. The Java
language implementation of python is called Jython. Finally, there is Ironpython, the C#
implementation for the .NET.
 Powerful
From a features perspective, Python is something of a hybrid. Its toolset places it between
traditional scripting languages (such as Tcl, Scheme, and Perl) and systems development
languages (such as C, C++, and Java).Python is useful for large-scale development projects.
The following features make Python language more powerful.
● Dynamic typing
● Automatic memory management
● Programming-in-the-large support
● Built-in object types
● Built-in tools
● Library utilities

1.2 Advantages of Python Programming

● It supports functional and structured programming methods as well as OOP.


● It can be used as a scripting language or can be compiled to byte-code for building
large applications.
● It provides very high-level dynamic data types and supports dynamic type checking.
● It supports automatic garbage collection.
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java

Example:
1.Hello, World! in python is the first python program which we learn when we start learning
any program. It’s a simple program that displays the message “Hello, World!” on the screen.
Here’s the “Hello World” program:
print("Hello, World!")
Output: Hello World
1.3 Variables:

In Python, variables are used to store data that can be referenced and manipulated
during program execution. A variable is essentially a name that is assigned to a value. Unlike
many other programming languages, Python variables do not require explicit declaration of
type. The type of the variable is inferred based on the value assigned. Variables act as
placeholders for data. They allow us to store and reuse values in our program.

Example:
# Variable 'x' stores the integer value 5
x=5

# Variable 'name' stores the string "keerthi"


name = "keerthi"

print(x)
print(name)

Output:
5
Keerthi

1.3.1 Rules for Naming Variables


To use variables effectively, we must follow Python’s naming rules:
 Variable names can only contain letters, digits and underscores (_).
 A variable name cannot start with a digit.
 Variable names are case-sensitive (myVar and myvar are different).
 Avoid using Python keywords (e.g., if, else, for) as variable names.

Valid Example:

 age = 21
 _colour = "lilac"
 total_score = 90
Invalid Example:

1name = "Error" # Starts with a digit


class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen

1.3.2 Assigning Values to Variables


 Basic Assignment
Variables in Python are assigned values using the =operator.
Example:
x=5
y = 3.14
z = "Hi"
 Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold different
types of values during execution.
Example:
x = 10
x = "Now a string"

1.3.3 Multiple Assignments


Python allows multiple variables to be assigned values in a single line.
Assigning the Same Value
Python allows assigning the same value to multiple variables in a single line, which can be
useful for initializing variables with the same value.
Example:
a = b = c = 100
print(a, b, c)
Output: 100 100 100

1.3.4 Assigning Different Values


We can assign different values to multiple variables simultaneously, making the code concise
and easier to read.
Example:
x, y, z = 1, 2.5, "Python"
print(x, y, z)

Output: 1 2.5 python

1.3.5 Type Casting a Variable


Type casting refers to the process of converting the value of one data type into another.
Python provides several built-in functions to facilitate casting, including int(), float() and str()
among others.
Basic Casting Functions
 int() – Converts compatible values to an integer.
 float() – Transforms values into floating-point numbers.
 str() – Converts any data type into a string.

Example:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string

# Display results
print(n)
print(f)
print(s2)
Output:
10
5.0
25

1.4 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 are the standard or built-in data types
in Python:
 Numeric – int, float, complex
 Sequence Type – string, list, tuple
 Mapping Type – dict
 Boolean – bool
 Set Type – set, frozenset
 Binary Types – bytes, bytearray, memoryview

This code assigns variable ‘x’ different values of few Python data types – int, float, list, set
and string. Each assignment replaces the previous value, making ‘x’ take on the data type
and value of the most recent assignment.

# int, float, string, list and set


x = 50
x = 60.5
x = "Hello World"
x = ["logic", "for", "logic"]
x = ("logic", "for", "logic")

1.4.1. Numeric Data Types in Python


The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number. These values are
defined as Python int , Python float , and Python complex classes in Python .
 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an
integer value can be.
 Float – This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific notation.
 Complex Numbers – A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . For example – 2+3j
Example:
a=5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>
1.4.2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python
data types. Sequences allow storing of multiple values in an organized and efficient fashion.
There are several sequence data types of Python:
 Python String
 Python List
 Python Tuple
 String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python, there is
no character data type Python, a character is a string of length one. It is represented by str
class.
Strings in Python can be created using single quotes, double quotes, or even triple quotes. We
can access individual characters of a String using index.
Example:
s = 'Welcome to the CSE World'
print(s)

# check data type


print(type(s))

# access string with index


print(s[1])
print(s[2])
print(s[-1])
Output

Welcome to the CSE World


<class 'str'>
e
l
d
 List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It
is very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[].
Example:
# Empty list
a = []

# list with int values


a = [1, 2, 3]
print(a)

# list with mixed int and string


b = ["logic", "For", "logic", 4, 5]
print(b)

Output

[1, 2, 3]

['logic', 'For', 'logic', 4, 5]

 Tuple Data Type


Just like a list, a tuple is also an ordered collection of Python objects. The only difference
between a tuple and a list is that tuples are immutable. Tuples cannot be modified after it is
created.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values separated by a
‘comma’ with or without the use of parentheses for grouping the data sequence. Tuples can
contain any number of elements and of any datatype (like strings, integers, lists, etc.).

Example:

# initiate empty tuple


t1 = ()

t2 = ('tech', 'For')
print("\nTuple with the use of String: ", t2)
Output
Tuple with the use of String: ('tech', 'For')

Note – The creation of a Python tuple without the use of parentheses is known as Tuple
Packing.

1.4.3. Boolean Data Type in Python


Python Data type with one of the two built-in values, True or False. Boolean objects
that are equal to True are truthy (true), and those equal to False are falsy (false). However
non-Boolean objects can be evaluated in a Boolean context as well and determined to be true
or false. It is denoted by the class bool.
Example: The first two lines will print the type of the boolean values True and False, which
is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in
Python. Python is case-sensitive, which means it distinguishes between uppercase and
lowercase letters.
Example:
print(type(True))

print(type(False))

print(type(true))

Output:
<class 'bool'>
<class 'bool'>

Traceback (most recent call last):


File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined

1.4.4. Set Data Type in Python


In Python Data Types, Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements. The order of elements in a set is undefined though it
may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in
a set need not be the same, various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values

# initializing empty set


s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])


print("Set with the use of List: ", s2)

Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}
1.4.5. Dictionary Data Type

A dictionary in Python is a collection of data values, used to store data values like a
map, unlike other Python Data Types that hold only a single value as an element, a
Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it more
optimized. Each key-value pair in a Dictionary is separated by a colon : , whereas each key is
separated by a ‘comma’.
Create a Dictionary in Python
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable. The dictionary can also be created by the built-in
function dict().
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
# initialize empty dictionary
d = {}

d = {1: 'tech', 2: 'For', 3: 'Geeks'}


print(d)

# creating dictionary using dict() constructor


d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

1.5 Comments in Python


Comments are lines that exist in computer programs that are ignored by compilers and
interpreters. Including comments in programs makes code more readable for humans as it
provides some information or explanation about what each part of a program is doing.
In Python, there are two ways to ways to include comments.The first is to include comments
that detail or indicate what a section of code – or snippet – does.The second makes use of
multi-line comments or paragraphs that serve as documentation for others reading your code.
Single-line comments
Single-line comments are created simply by beginning a line with the hash (#) character, and
they are automatically terminated by the end of line.
For example:

#Thisis the comment in Python


Comments that span multiple lines are used to explain things in more detail are created by
adding a delimiter (“””) on each end of the comment.

“”” This would be a multiline commentin Python that includes several lines and
describesthecode,or anything you want it to…
“””

1.6 Indentation
In Python, indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All statements with the
same level of indentation are considered part of the same block. Indentation is achieved using
whitespace (spaces or tabs) at the beginning of each line.
For Example:

if 10 > 5:
print("This is true!")
print("I am tab indentation")

print("I have no indentation")

Output
This is true!
I am tab indentation
I have no indentation

If we Skip Indentation, Python will throw error.

if 10>5:
print("GeeksforGeeks")
1.7 Python Input and Output Functions

1. Input Function (input())

 Used to take user input from the console.


 Returns data as a string.
 Syntax:

user_input = input("Enter something: ")


2. Output Function (print())

 Used to display output on the console.


 Supports multiple arguments and formatting.
 Syntax:

print("Hello, World!")
3. Formatting Output (f-strings, format())

 Using f-strings:

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

 Using .format():

print("My name is {} and I am {} years old.".format(name, age))


4. Output with File Handling (file parameter)

 Printing output to a file:

with open("output.txt", "w") as f:


print("This is written to a file.", file=f)

1.8 Operators
Operators are special symbols which can manipulate the value of operands. Operators
can manipulate individual items and returns a result.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Python language supports the following types of operators.
● Arithmetic Operators
● Relational Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
● Identity Operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication and division etc. Assume variable a holds 10 and variable b holds 20, then

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder

** Exponent Performs exponential (power) calculation on operators a**b =10 to the


power 20

// Floor Division The division of operands where the result is the 9//2 = 4 and
quotient in which the digits after the decimal point are 9.0//2.0 = 4.0, -
removed. But if one of the operands is negative, the 11//3 = -4,
result is floored, i.e., rounded away from zero
(towards negative infinity) − -11.0//3 = -4.0

Relational Operators
Relational operators compare the values of two operands. It either returns True or False
according to the condition. Assume variable a holds 10 and variable b holds 20, then

Operator Description Example

== If the values of two operands are equal, then the condition (a == b) = False
becomes true.

!= If values of two operands are not equal, then condition becomes (a != b) = True.
true.

<> If values of two operands are not equal, then condition becomes (a <> b) = True.
true. This is similar to !
= operator.

> If the value of left operand is greater than the value of right (a > b) = False.
operand, then condition becomes true.

< If the value of left operand is less than the value of right operand, (a < b) = Ttrue.
then condition becomes true.

>= If the value of left operand is greater than or equal to the value of (a >= b)=False.
right operand, then condition becomes true.

<= If the value of left operand is less than or equal to the value of (a <= b) = True.
right operand, then condition becomes true.

Assignment Operators

Python assignment operators are used for assigning the value of the right operand to the left
operand. Various assignment operators used in Python are (+=, - = , *=, /= , etc.)

Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical
operators in Python are AND, OR and NOT. For logical operators following condition are
applied.

● For AND operator – It returns TRUE if both the operands (right side and left side)
are true
● For OR operator- It returns TRUE if either of the operand (right side or left side) is
true
● For NOT operator- returns TRUE if operand is false

Example

a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))

Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation.

Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operato
Meaning Example
r

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)

Membership operators

in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence.

In a dictionary we can only test for presence of key, not the value.

Operato
Meaning Example
r

in True if value/variable is found in the sequence 5 in x


True if value/variable is not found in the
not in 5 not in x
sequence

Identity operators

is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.

Identity operators in Python

Operator Meaning Example

is True if the operands are identical (refer to the same object) x is True

is not True if the operands are not identical (do not refer to the same object) x is not True

1.9 Control Statements


Control Statement in Python performs different computations or actions depending
on whether a specific Boolean constraint evaluates to true or false. These statements allow
the computer to select or repeat an action. Control statement selects one option among all
options and repeats specified section of the program.

Selection control Structures


Decision making statements in programming languages decides the direction of flow of
program execution. Decision making statements available in python are:
● if statement
● if..else statements
● nested if statements
● if-elif ladder
if statement
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 i.e if a certain condition is
true then a block of statement is executed otherwise not.
Syntax:
ifcondition:
# Statements to execute if
# condition is true
Python uses indentation to identify a block.
# Python program to illustrate If statement

i = 20
if (i> 10):
print ("10 is less than 20")
print ("I am Not in if")

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 what if we want to do something else if
the condition is false.
Here comes the else statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

# python program to illustrate If else statement


a =20
b = 30
if(a<b):
print("a is smaller than b")
else:
print("a is greater than b")

nested-if Statement
A nested if is an if statement that is the target of another if statement. Nested if
statements means 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
# 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")

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
Python program to illustrate if-elif-else ladder

a,b,c=10,20,30
if (a >= b) and (a >= b):
largest = a

elif (b >= c):


largest = b
else:
largest = c
print("Largest among three numbers",largest)

1.10 Loops in python

Python programming language provides following types of loops to handle looping


requirements. Python provides three ways for executing the loops. While all the ways provide
similar basic functionality, they differ in their syntax and condition checking time.
1. While Loop:
In python, while loop is used to execute a block of statements repeatedly until a given a
condition is satisfied. And when the condition becomes false, the line immediately after
the loopin program is executed.
Syntax :
while expression:
statement(s)
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.
Example:
# Python program to illustratewhile loop
count =0
while(count < 3):
count =count +1
print("Welcome")
2.Using else statement with while loops:
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.

Syntax
whilecondition:
# execute these statements
else:
# execute these statements

#Python program to illustratecombining else with while


count =0
while(count < 3):
count =count +1
print("Welcome")
else:
print("In Else Block")

3.for Loop Statements


It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.

Example
for letter in 'Python': # First Example
print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit
4.Using else statement with for loops:
If the else statement is used with a for loop, the else statement is executed when the loop has
exhausted iterating the list.The following example illustrates the combination of an else
statement with a for statement that searches for prime numbers from 10 through 20.
Example
for num in range(10,20):
fori in range(2,num):
ifnum%i == 0:
j=num/i
print( '%d equals %d * %d' % (num,i,j))
break
else:
print num, 'is a prime number'

Loop Control Statements


Loop control statements change execution from its normal sequence.
1.break statement
It terminates the current loop and resumes execution at the next statement. The most common
use for break is when some external condition is triggered requiring a hasty exit from a loop.
The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost loop
and start executing the next line of code after the block.
Syntax
The syntax for a break statement in Python is as follows
break
Example
var = 10
whilevar> 0:
print 'Current variable value :', var
var = var -1
ifvar == 5:
break
Output
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6

2.Continue statement
It returns the control to the beginning of the while loop.. The continue statement rejects all
the remaining statements in the current iteration of the loop and moves the control back to the
top of the loop.
The continue statement can be used in both while and for loops.

Syntax
continue
Example

var = 10
whilevar> 0:
var = var -1
ifvar == 5:
continue
print(“'Current variable value :”, var)

Output
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0

3.pass Statement
It is used when a statement is required syntactically but you do not want any command or
code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also
useful in places where your code will eventually go, but has not been written yet (e.g., in
stubs for example
Syntax
pass

Example
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
1.11 Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.Python provides many built-in functions like print(), etc. but the user can also create
their own functions. These functions are called user-defined functions.
Defining a Function
Functions can be defined to provide the required functionality. Here are simple rules to
define a function in Python.
● Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
● Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
● The code block within every function starts with a colon (:) and is indented.
● The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax of Function
deffunction_name(parameters):

"""docstring"""

statement(s)

Example of a function
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

1.11.1 Types of arguments


In Python, user-defined functions can take four different types of arguments. The argument
types and their meanings, however, are pre-defined and can’t be changed. But a developer
can, instead, follow these pre-defined rules to make their own custom functions. The
following are the four types of arguments

● Default arguments
● Required arguments
● Keyword arguments
● Variable-length arguments

 Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed.

Below is a typical syntax for default argument. In function call2 the default value of age is
35.

defemp( name, age = 35 ):


print("Name: ", name)
print( "Age: ", age)

emp( age=50, name="arun" ) #Function call11


emp( name="Anand" ) #Function call2

Output
Name: arun
Age 50
Name: Anand
Age 35

 Required arguments

Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.

defemp( name, age ):


print("Name: ", name)
print( "Age: ", age)
emp( age=50, name="arun" ) #Function call11
emp( name="Anand" ) #Function call2

To call the function emp(), you definitely need to pass two arguments, otherwise it gives a
syntax error as follows
Name: arun

Age 50

Traceback (most recent call last):

File "main.py", line 7, in <module>

emp( name="Anand" )

TypeError: emp() missing 1 required positional argument: 'age'

 Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.This
allows you to skip arguments or place them out of order because the Python interpreter is able
to use the keywords provided to match the values with parameters.
defemp( name, age = 35 ):
print("Name: ", name)
print( "Age: ", age)

emp( age=50, name="arun" ) #Function call11


emp( name="Anand" ,35) #Function call2

Output
emp( name="Anand" ,35) #Function call2
^
SyntaxError: non-keyword arg after keyword arg

In the function call2 the second argument age can not be identified with its name.

 Variable number of arguments

This is very useful when we do not know the exact number of arguments that will be passed
to a function.You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default arguments. n asterisk (*) is
placed before the variable name that holds the values of all nonkeyword variable arguments.
# Function definition
def print_info(arg1, *vartuple):
"""This prints a variable passed as arguments"""
print("Output: ")
print(arg1)
for var in vartuple:
print(var)

# Now you can call print_info function


print_info(5)
print_info(12, 50, 20)

Output
Output:
10
Output:
70
60
50
1.12 Python Anonymous/Lambda Function
In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions
are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.

Syntax of Lambda Function in python


lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever function
objects are required.
Here is an example of lambda function that doubles the input value.
Eg1:
# Program to show the use of lambda functions
double = lambda x: x * 2

print(double(5))

# Output: 10

Eg2:

# Program to show the use of lambda functions

sum = lambda x,y,z: x+y+z

print(sum(5,10,15))

# Output: 30
 Filter Function
In Python, we generally use it as an argument to a higher-order function (a function that takes
in other functions as arguments). Lambda functions are used along with built-in functions
like filter(), map() etc.

# Define a list
list1 = [1, 5, 4, 6, 8, 11, 3, 12]

# Use filter with lambda to extract even numbers


list2 = list(filter(lambda x: x % 2 == 0, list1))

# Print the output


print(list2)

output:
[4, 6, 8, 12]

 Map Function
The map() function in Python takes in a function and a list.
The function is called with all the items in the list and a new list is returned which contains
items returned by that function for each item.
Here is an example use of map() function to double all the items in a list.

# Define a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]

# Use map with lambda to multiply each element by 2


new_list = list(map(lambda x: x * 2, my_list))

# Print the output


print(new_list)

output:
[2, 10, 8, 12, 16, 22, 6, 24]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy