0% found this document useful (0 votes)
9 views5 pages

Python Programming Basics and Examples

The document contains Python programming exercises including finding the sum and difference of two numbers, calculating the area and perimeter of a triangle, appending a name to a list, sorting a dictionary, and outlining the syntax for various Python data types. Each exercise is accompanied by example code and expected outputs. Additionally, it covers numeric, sequence, set, mapping, boolean, binary, and None types in Python.

Uploaded by

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

Python Programming Basics and Examples

The document contains Python programming exercises including finding the sum and difference of two numbers, calculating the area and perimeter of a triangle, appending a name to a list, sorting a dictionary, and outlining the syntax for various Python data types. Each exercise is accompanied by example code and expected outputs. Additionally, it covers numeric, sequence, set, mapping, boolean, binary, and None types in Python.

Uploaded by

shwetasatav22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Electronics Practical : Python Programming

Q.1. Write a python program to find Sum and difference of a=20, b=11.
a=20
b=11
sum_result=a+b
difference_result=a-b
print("Sum:",sum_result)
Output:
Sum: 31
print("Difference:",difference_result)
Output:
Difference: 9

Q.2. write a python program to find area and perimeter of a triangle.


import math
def triangle_perimeter(a,b,c):
return a+b+c
def herons_area(a,b,c):
s=(a+b+c)/2
return [Link](s*(s-a)*(s-b)*(s-c))
print("Enter the sides of the triangle:")
Output:
Enter the sides of the triangle:
a=float(input("Side 1:"))
Output:
Side 1: 3
b=float(input("Side 2:"))
Output:
Side 2: 4
c=float(input("Side 3:"))
Output:
Side 3: 6
if a+b>c and a+c>b and b+c>a:
perimeter=triangle_perimeter(a,b,c)
area = herons_area(a, b, c)
print(f"Perimeter of the triangle:{perimeter}")
Output:
Perimeter of the triangle:13.0
print(f"Area of the triangle:{area:2f}")
Output:
Area of the triangle:5.33
Q.3. Write a python program to append name in the given below list ?
Names = ["Joseph", "Peter", "Cook", "Tim"]
Names=["Joseph","Peter","Cook","Tim"]
def append_name(name):
[Link](name)
print("Updated List:",Names)
Output:
Updated List: ['Joseph', 'Peter', 'Cook', 'Tim']
new_name=input("Enter a name to append:Nooh")
Output:
Enter a name to append:Nooh

Q.4. Write a python program to sort the given dictionary.


names = {1:’Alice’, 2:’John’, 4:’Peter’, 3:’Andrew’, 6:’Ruffalo’, 5:’Chris’}
names={1:'Alice',2:'John',4:'Peter',3:'Andrew',6:'Ruffalo',5:'Chris'}
sorted_names=dict(sorted([Link]()))
print("Sorted Dictionary:",sorted_names)
Output:
Sorted Dictionary: {1: 'Alice', 2: 'John', 3: 'Andrew', 4: 'Peter', 5: 'Chris', 6: 'Ruffalo'}
Q.5. Write syntax of all data types of python language.
1. Numeric Types
a. Integer (int)
num_int = 10
b. Floating Point (float)
num_float = 10.5
c. Complex Number (complex)
num_complex = 3 + 4j
2. Sequence Types
a. String (str)
text = "Hello, Python!"
b. List (list)
my_list = [1, 2, 3, "apple", 4.5]
c. Tuple (tuple)
my_tuple = (1, 2, 3, "banana", 5.6)
d. Range (range)
my_range = range(5)
3. Set Types
a. Set (set)
my_set = {1, 2, 3, 4, 5} # Example of a set
b. Frozen Set (frozenset)
my_frozenset = frozenset([1, 2, 3, 4, 5])
4. Mapping Type
a. Dictionary (dict)
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

5. Boolean Type
a. Boolean (bool)
is_valid = True

6. Binary Types
a. Bytes (bytes)
my_bytes = b"Hello"
b. Bytearray (bytearray)
my_bytearray = bytearray(5)
c. Memoryview (memoryview)
my_memoryview = memoryview(bytes(5))

7. None Type
a. NoneType (None)
my_var = None

Common questions

Powered by AI

In Python, handling input for calculating the area and perimeter of a triangle involves prompting users to enter side lengths, using `input()`. The program verifies the input to ensure the side lengths form a valid triangle, using conditional checks like `if a+b>c and a+c>b and b+c>a`. This ensures the integrity of subsequent geometric calculations, allowing programs to guard against invalid inputs that could disrupt further processing .

The Binary Types in Python include `bytes`, `bytearray`, and `memoryview`. `bytes` are immutable sequences of bytes, used for storing binary data, e.g., `my_bytes = b"Hello"`. `bytearray` is mutable and allows modification, e.g., `my_bytearray = bytearray(5)`, useful for mutable binary sequences. `memoryview` provides a way to access the internal data of an object that supports the buffer protocol, without copying, e.g., `my_memoryview = memoryview(bytes(5))`. This is helpful for efficient data handling .

The Sequence Types in Python include `str`, `list`, `tuple`, and `range`. These sequences allow for ordered collections. A `str` holds a sequence of characters, e.g., `text = "Hello, Python!"`. A `list` is mutable, allowing modifications, e.g., `my_list = [1, 2, 3, 'apple', 4.5]`. A `tuple` is immutable, like `my_tuple = (1, 2, 3, 'banana', 5.6)`. `range` represents an iterable sequence of numbers, often used in loops, e.g., `my_range = range(5)` .

To sort a dictionary by its keys in Python, you can use the `sorted()` function with the `items()` method of the dictionary, converting the result back to a dictionary with `dict()`: `sorted_names = dict(sorted(names.items()))`. The output for the given dictionary `names={1:'Alice', 2:'John', 4:'Peter', 3:'Andrew', 6:'Ruffalo', 5:'Chris'}` would be: `{1: 'Alice', 2: 'John', 3: 'Andrew', 4: 'Peter', 5: 'Chris', 6: 'Ruffalo'}` .

Heron's formula calculates the area of a triangle from its side lengths. Given sides `a`, `b`, and `c`, the semi-perimeter `s` is calculated as `(a+b+c)/2`, and the area is found using the formula: `sqrt(s*(s-a)*(s-b)*(s-c))`. This is effective for triangles where all side lengths are known, without needing height or angles. However, it can result in computational inaccuracies for very large triangles due to floating-point arithmetic limits, and it cannot be used if any side length is negative or zero .

Python handles different numeric data types including integers (`int`), floating-point numbers (`float`), and complex numbers (`complex`). Integers are for whole numbers, e.g., `num_int = 10`. Floating-point numbers support decimal values, e.g., `num_float = 10.5`. Complex numbers have a real and imaginary part, e.g., `num_complex = 3 + 4j` .

The Boolean type in Python represents one of two values: `True` or `False`. It is used extensively in conditionals and loops to control the flow of programs. For example, a simple condition might be expressed as `is_valid = True` and used in an `if` statement like `if is_valid: ...`. Common scenarios include checking conditions, managing program states, and in constructs requiring binary decision outcomes .

To calculate the area and perimeter of a triangle using Python, you can define functions for each calculation. For the perimeter, sum the lengths of all sides: `def triangle_perimeter(a, b, c): return a + b + c`. To calculate the area, use Heron's formula, which involves first computing the semi-perimeter `s = (a + b + c) / 2` and then the area `math.sqrt(s * (s - a) * (s - b) * (s - c))`. Heron's formula is the mathematical theorem used for calculating the area .

To append an element to a Python list, use the `append()` method. This method adds the new element to the end of the list. For example, given `Names = ['Joseph', 'Peter', 'Cook', 'Tim']`, calling `Names.append(name)` with `name='Nooh'` will result in `Names` being updated to `['Joseph', 'Peter', 'Cook', 'Tim', 'Nooh']` .

In Python, a `set` is mutable, allowing for modifications such as adding or removing elements, e.g., `my_set = {1, 2, 3, 4, 5}`. In contrast, a `frozenset` is immutable and thus cannot be altered after creation, e.g., `my_frozenset = frozenset([1, 2, 3, 4, 5])`. A frozenset is chosen over a set when there's a need for a hashable collection of items, such as when using keys in a dictionary or when immutability is required for consistency .

You might also like