0% found this document useful (0 votes)
12 views6 pages

Python Programming Practical Guide

Practical

Uploaded by

Garv Saini
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)
12 views6 pages

Python Programming Practical Guide

Practical

Uploaded by

Garv Saini
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

SVKM’s NMIMS University

Mukesh Patel School of Technology Management & Engineering


Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
PRACTICAL 1
Part A (To be referred by students)

Data Types, Input / Output Statements, Operators (Arithmetic, Relational, Logical,


Bitwise) and Expressions

Problem Statements:
1. Write a program to enter a number and print its square, cube and square root.
2. WAP to calculate the average of 3 numbers.
3. Write a program to calculate the area of a right-angle triangle.
4. WAP to calculate simple interest.
5. WAP to convert temperature in Celsius into Fahrenheit.
6. WAP to find Euclidean distance between two points on a plane.
7. Write a Python program to swap two variables.
1. Using temp variable
2. Using the comma operator
3. Using bitwise XOR operator

8. WAP to find roots of a quadratic equation ax2+bx+c=0

Learning Objective: The Learner will be able to


1. Analyze the scenario to write a script declaring variables, printing output and using
expressions.
2. Infer the features of various operators for different operations as per variable data
type.
3. Evaluate the working of the algorithm using variables, printing and inputting user
values and expressions.

Theory:
 Data types:
Number: int, float, complex
String
a = 11.80
x = 100
y = “Hello”
z = 3+5.j

print(a)
print(x)
print(y)
print(z)
Output:
11.8
100
Hello
(3+5j)

1|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

 Accepting Input from the Console:

# if input() used it accepts input as string


num=input(‘Enter a number: ‘)
print(num)

# to accept numbers
num=int(input(‘Enter a number: ‘))
print(num)

num=float(input(‘Enter a number: ‘))


print(num)

Output:
Enter a number: 10
‘10’
Enter a number: 45
45
Enter a number: 78
78.0

 Output using print() with formatting:

x=6
y=89
print('The value of x is {1} and y is {0}'.format(x,y))
x = 12.3456789
print('The value of x is %3.2f' %x)

print('The value of x is %3.4f' %x)

print ('The %.2f and %.1f ' %(x, y))

Output:
The value of x is 89 and y is 6
The value of x is 12.35
The value of x is 12.3457
The 12.35 and 456.8

 Operators:
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Relational/Comparison operators

2|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

 Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Example

+ x+y

- x-y

* x*y

/ x/y

% x%y

** x ** y

// x // y

 Python Assignment Operators


Assignment operators are used to assign values to variables:
Operator Example

= x=5

+= x += 3

-= x -= 3

*= x *= 3

/= x /= 3

%= x %= 3

//= x //= 3

**= x **= 3

&= x &= 3

|= x |= 3

3|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
^= x ^= 3

>>= x >>= 3

<<= x <<= 3

 Python Relational/Comparison Operators


Comparison operators are used to compare two values:
Operator Example

== x == y

!= x != y

> x>y

< x<y

>= x >= y

<= x <= y

 Python Logical Operators


Logical operators are used to combine conditional statements:
Operato Description Example
r

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true

 Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:
Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

4|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II
<< Zero fill left Shift left by pushing zeros in from the right and
shift let the leftmost bits fall off

>> Signed right Shift right by pushing copies of the leftmost bit
shift in from the left, and let the rightmost bits fall
off

PRACTICAL 1
Part B (to be completed by students)

5|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

Data Types, Input / Output Statements, Operators (Arithmetic, Relational, Logical,


Bitwise) and Expressions

1. All the students are required to perform the given tasks in Jupyter Notebook
2. Create a new notebook for each experiment. The filename should be
RollNo_Name_Exp1)
3. In the first cell, the student must write his/her Name, roll no and class in the form of
comments
4. Every program should be written in separate cells and in the given sequence
5. After completing the experiment, download the notebook in pdf format. The filename
should be RollNo_Name_Exp1.pdf).
6. Upload the pdf on the web portal

6|Page

Common questions

Powered by AI

Logical operators in Python, such as 'and', 'or', and 'not', are used to form compound conditional statements by combining multiple boolean expressions. The 'and' operator returns True if both operands are true, 'or' returns True if at least one operand is true, and 'not' inverts the boolean value of the operand. For example, a compound statement using these operators could be: (x < 10 and y > 5) or (not z). This expression evaluates to True if x is less than 10 and y is greater than 5, or if z is false (inverted by the not operator). These operators allow the creation of complex logical sequences necessary for decision-making processes in programs.

Assignment operators in Python simplify the process of updating variables by combining a binary operation with an assignment. For instance, operators like +=, -=, *=, and /= allow programmers to update a variable's value elegantly by performing the operation on the variable itself, rather than separately. For example, x += 3 is equivalent to x = x + 3, thus making the code more concise and readable. This approach reduces redundancy and the chance of errors when repeatedly updating the value of a variable. Each assignment operator applies a specific arithmetic or bitwise operation to the variable, simplifying the coding process while maintaining clarity .

Python's assignment operators modify variables by applying the specific operation implied by the operator (e.g., +=, -=). When used with different data types, these operators seamlessly convert the result to the data type that fits all involved operands. For instance, combining an int with a float using += results in a float, aligning with Python's implicit type promotion rules. However, using these operators with incompatible types like int and complex can result in errors, as complex types do not implicitly convert to simple numerical types. A potential pitfall is assuming these operations will avoid logical errors like data type overflows or precision loss automatically—careful variable tracking and typecasting becomes necessary when precision and type consistency are crucial in complex calculations .

Arithmetic operators in Python are used to perform mathematical operations such as addition, subtraction, multiplication, and division on numeric values. For example, '+' for addition (x + y), '-' for subtraction (x - y), '*' for multiplication (x * y), and '/' for division (x / y). Bitwise operators, on the other hand, operate on the binary representation of numbers. They include '&' for AND, '|' for OR, '^' for XOR, '~' for NOT, '<<' for left shift, and '>>' for right shift, manipulating individual bits of the operands. For instance, using the '&' operator on two integers results in a new integer where only the bits set in both operands are kept (x & y). These operators address different operation levels, with arithmetic dealing with whole numbers and mathematical operations, while bitwise operators manipulate binary digit positions and values.

Bitwise operators in Python are essential for low-level programming tasks, where operations need to be performed directly on the binary representations of data, such as in network programming, cryptography, and tasks involving hardware interaction. They manipulate each bit in integers, offering operations like AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). These operations are vital for tasks including setting, clearing, or flipping specific bits efficiently. For example, the XOR operator is used in algorithms such as the calculation of checksums or parity bits. Another example is using bitwise operations for fast arithmetic operations in specific embedded systems where hardware constraints demand optimized code down to the bit level . The understanding and application of these operators require a firm grasp of binary mathematics and are often crucial for performance-critical applications.

Best practices for formatting and outputting data in Python using the print function involve using formatted strings for clarity and precision. Formatted strings can be created using either the .format() method or f-strings (formatted string literals). The .format() method allows positional and keyword arguments for specific placements, such as: print('The value of x is {1} and y is {0}'.format(x, y)), while f-strings provide an even more readable way of embedding expressions: print(f'The value of x is {x} and y is {y}'). For precision control, format specifiers can be used, such as '%.2f' for two decimal points: print('The value of x is %.2f' % x). These tools help produce clean, correctly formatted outputs while avoiding hard-to-read concatenations, making data presentation in programs professional and efficient .

In Python, two variables can be swapped using a temporary variable, the comma operator, or the bitwise XOR operator. Using a temporary variable involves storing one value in a third variable temporarily, thus allowing the swap without losing any data. The comma operator is more Pythonic and concise, using tuple unpacking to accomplish the swap in a single line: a, b = b, a. This method is direct and avoids the need for an additional variable. The XOR operator method is a bitwise technique that swaps two integer variables using XOR's properties without a temporary variable: a = a ^ b; b = a ^ b; a = a ^ b. While this last approach is clever, it is less readable and used less frequently due to its complexity and potential limitations with non-integer data types .

To implement a program calculating the Euclidean distance between two points on a plane in Python, first, take the coordinates of the two points as input: (x1, y1) and (x2, y2). Then apply the Euclidean distance formula derived from the Pythagorean theorem: distance = sqrt((x2 - x1)^2 + (y2 - y1)^2). Import the math module to use the sqrt function: import math. Use the input() function to accept the x and y coordinates as float or integers. Perform the subtraction and square the differences, sum these squared differences, and then take their square root to get the distance. Finally, print the calculated distance using the print() function for output .

In Python, data types such as int, float, and complex define the kind of data stored in variables and determine the operations that can be performed on it. Integers (int) represent whole numbers without decimal points; floats are used for real numbers incorporating decimals, perfect for representing approximate values or performing division; complex numbers include a real and an imaginary part, indicated by a suffix 'j' (e.g., 3+5j). Arithmetic operators interact differently with these types: int and float operators allow addition, subtraction, multiplication, and division straightforwardly, where operations between an int and a float will yield a float. Complex numbers add an additional dimension, where arithmetic operations are performed separately on the real and imaginary parts . This precise type handling offers Python flexibility in handling large calculations and variable data formats effectively.

The use of input() in Python returns the data as a string by default, which can lead to type-related issues when numeric operations are required. Converting this input to numeric data types such as int or float is necessary for arithmetic operations. To handle numeric conversions safely, one should use try-except blocks to manage exceptions when invalid data is entered. For example, when expecting an integer, use num = int(input('Enter a number: ')) inside a try block and catch potential ValueErrors in the except block. This ensures that the program can gracefully handle incorrect inputs, prompting the user to re-enter the data or providing an error message, thus maintaining robustness and usability .

You might also like