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

Python Lab 2

The document provides an overview of Python comments, functions, and control flow statements, including if-else structures. It explains built-in functions like abs(), all(), and bin(), along with defining and calling user-defined functions. Additionally, it covers the syntax and usage of conditional statements and nested if statements in Python.

Uploaded by

namrach62
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
3 views25 pages

Python Lab 2

The document provides an overview of Python comments, functions, and control flow statements, including if-else structures. It explains built-in functions like abs(), all(), and bin(), along with defining and calling user-defined functions. Additionally, it covers the syntax and usage of conditional statements and nested if statements in Python.

Uploaded by

namrach62
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 25

PYTHON LAB 2

Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing
code.
Example
#This is a comment
print("Hello, World!")
Multiline Comments
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python
C++

Comment begins with // #

Statement ends with ; No semi-colon needed

Conditional statement if-else if- else if – elif – else:

Not required but loop condition fol-


Parentheses for loop
Required lowed by a colon : while a < n:
execution condition
print(a)
Python - Functions
Python includes many built-in functions. These functions perform a
predefined task and can be called upon in any program, as per
requirement. However, if you don't find a suitable built-in function to
serve your purpose, you can define one.
Python Built-in Functions:
The Python interpreter has a number of functions that are always
available for use. These functions are called built-in functions. For
example, print() function prints the given object to the standard output
device (screen) or to the text stream file.
Python abs() Function:
Definition
The abs() method returns the absolute value of the given
number. If the number is a complex number, abs() returns its
magnitude.
Syntax
The syntax of abs() method is:
abs(num)
Parameters
The abs() method takes a single argument:
num – A number whose absolute value is to be returned. The
number can be:
• integer
• floating number
Example
# random integer
integer = -20
print('Absolute value of -20 is:', abs(integer))

#random floating number


floating = -30.33
print('Absolute value of -30.33 is:', abs(floating))

Output

Absolute value of -20 is: 20 Absolute value of -


30.33 is: 30.33
Python all() Function:
Definition

The all() method returns True when all elements in the given
iterable are true. If not, it returns False.

Syntax

The syntax of all() method is:

all(iterable)
Parameters

The all() method takes a single parameter:

iterable – Any iterable (list, tuple, dictionary, etc.) which


contains the elements
Example:
# all values true
l = [1, 3, 4, 5]
print(all(l)) Output

# all values false True


l = [0, False] False
print(all(l)) False
False
# one false value True
l = [1, 3, 4, 0]
print(all(l))

# one true value


l = [0, False, 5]
print(all(l))

# empty iterable
l = []
print(all(l))
Python bin() Function:
Definition
The bin() method converts and returns the binary equivalent string of a given
integer.
Syntax
The syntax of bin() method is:
bin(num)
Parameters
he bin() method takes a single parameter:
num – an integer number whose binary equivalent is to be calculated.
Example:
number = 5
print('The binary equivalent of 5 is:', bin(number))
Output
The binary equivalent of 5 is: 0b101
We will now see how to define and use a function in a Python program.
Defining a Function
A function is a reusable block of programming statements
designed to perform a certain task. To define a function, Python
provides the def keyword. The following is the syntax of defining
a function.
Syntax:
def function_name(parameters):
"""docstring"""
statement1
statement2
...
...
return [expr]

User-defined Function
def greet():
print("sadaf")
Calling User-defined Function
greet()
Output

Hello World!
By default, all the functions return None if the return statement does not exist.

Example: Calling User-defined Function


def greet():
val = greet()
print(val)
Example: Parameterized Function

def greet(name):
print ('Hello ', name)

greet('Steve') # calling function with argument


greet(123)
Output
Hello Steve
Hello 123
Multiple Parameters

def greet(name1, name2, name3):


print ('Hello ', name1, ' , ', name2 , ', and ',
name3)

greet('Steve', 'Bill', 'Yash') # calling function with


string argument

Output
Hello Steve, Bill, and Yash
The following function works with any number of arguments.
def greet(*names):
i=0
print('Hello ', end='')
while len(names) > i:
print(names[i], end=', ')
i+=1

greet('Steve', 'Bill', 'Yash')


greet('Steve', 'Bill', 'Yash', 'Kapil', 'John', 'Amir')

Output:
Hello Steve, Bill, Yash, Hello Steve, Bill, Yash, Kapil,
John, Amir,
Function with Keyword Arguments
def greet(firstname, lastname):
print ('Hello', firstname, lastname)

greet(lastname='Jobs', firstname='Steve') # passing


parameters in any order using keyword argument

Output:
Hello Steve Jobs
Function with Return Value
def sum(a, b):
return a + b
total=sum(10, 20)
print(total)
total=sum(5, sum(10, 20))
print(total)

Output
30
35
Operator Description
() Parentheses
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo, and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise ‘AND’
Bitwise exclusive ‘OR’ and regular ‘OR’
^|

<= < > >= Comparison Operators


== != Equality Operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Python if...else Statement
In Python, there are three forms of the if...else
statement.

• if statement
• if...else statement
• if...elif...else statement
1. Python if statement
The syntax of if statement in Python is:

if condition:
# body of if statement
The if statement evaluates condition.

• If condition is evaluated to True, the code inside


the body of if is executed.
• If condition is evaluated to False, the code inside
the body of if is skipped.
Example 1: Python if Statement
number = 10

# check if number is greater than 0


if number > 0:
print('Number is positive.')
2. Python if...else Statement
An if statement can have an optional else clause.
The syntax of if...else statement is:
if condition:
# block of code if condition is True
else:
# block of code if condition is False
The if...else statement evaluates the given condition:
If the condition evaluates to True,
the code inside if is executed
the code inside else is skipped
If the condition evaluates to False,
the code inside else is executed
the code inside if is skipped
Example 2. Python if...else Statement
number = 10

if number > 0:
print('Positive number')

else:
print('Negative number')

Output
Positive number
3. Python if...elif...else Statement
The if...else statement is used to execute a block of code among two
alternatives.

However, if we need to make a choice between more than two


alternatives, then we use the if...elif...else statement.

The syntax of the if...elif...else statement is:

if condition1:
# code block 1

elif condition2:
# code block 2

else:
# code block 3
Here,
If condition1 evaluates to true, code block 1 is executed.
If condition1 evaluates to false, then condition2 is evaluated.
If condition2 is true, code block 2 is executed.
If condition2 is false, code block 3 is executed.
Example 3: Python if...elif...else Statement
number = 0

if number > 0:
print("Positive number")

elif number == 0:
print('Zero')
else:
print('Negative number')

Output:
Zero
Python Nested if statements
We can also use an if statement inside of an if statement.
This is known as a nested if statement.

The syntax of nested if statement is:

# outer if statement
if condition1:
# statement(s)

# inner if statement
if condition2:
# statement(s)
Notes:

We can add else and elif statements to the inner if statement


as required.
We can also insert inner if statement inside the outer else or
elif statements(if they exist)
We can nest multiple layers of if statements.
Example:
number = 5

# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')

# inner else statement


else:
print('Number is positive')

# outer else statement


else:
print('Number is negative')

# Output: Number is positive

You might also like