802 Lab6 Shoaib

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

1.

Code:
print("1/7", str(1/7))

# Print without a space


print('Hello', end='')
print('World', end='')
print("")
Output:
1/7 0.14285714285714285
HelloWorld

Explanation:
The Python code above will show you two different ways to employ the `print()` function.
Further down, it computes the quotient of 1 divided by 7 and prints this value together
with "1/7", to yield the following output: ` 0.14285714285714285`. Subsequently, it
outputs "Hello" and "World" on the same line using `end=''`. Lastly, it adds a new line
after "HelloWorld".

2. Code

print("This site is {0:f}% securely {1}!!".


format(100, "encrypted"))

# To limit the precision


print("My average of this {0} was {1:.2f}%"
.format("semester", 83.12312))

# For no decimal places


print("My average of this {0} was {1:.0f}%"
.format("semester", 83.12312))

# Convert an integer to its binary or


# with other different converted bases.
print("The {0} of 100 is {1:b}"
.format("binary", 100))

print("The {0} of 100 is {1:o}"


.format("octal", 100))
Output
This site is 100.000000% securely encrypted!!
My average of this semester was 83.12%
My average of this semester was 83%
The binary of 100 is 1100100
The octal of 100 is 144
Explanation:
Above code is some example code for how the `format()` method of Python is used to
format strings: It starts with a message that includes a floating point number formatted
to six decimal places and a string attached. Next, it formats the average score into two
decimal places and rounds this to zero decimal places. Finally, it converts the integer
100 into both its binary and octal forms, showing how handy it might be to use with
integers specifically.

3. Code
#A demo of str.format with positional arguments

emp_name = "Sarah"
emp_sal = 5000
print("Employee Name is {0}, Salary is {1}.".format("Mike", 4500))
print("Employee Name is {1}, Salary is {0}.".format(emp_sal, emp_name))

bugs = 'cochroaches'
count = 9
area = 'bedroom'
print(f'Debugging {bugs=} {count=} {area=}') #f-string format.

introduction = 'My name is {first_name} {middle_name} {last_name} AKA


the {aka}.'
full_name = {
'first_name': 'Tony',
'middle_name': 'Howard',
'last_name': 'Stark',
'aka': 'Iron Man',
}

# Notice the use of "**" operator to unpack the values.


print(introduction.format(**full_name))

# which prints out i, i ^ 2, i ^ 3,


# i ^ 4 in the given range

# Function prints out values


# in an unorganized manner
def unorganized(a, b):
for i in range(a, b):
print(i, i**2, i**3, i**4)

# Function prints the organized set of values


def organized(a, b):
for i in range(a, b):

# Using formatters to give 6


# spaces to each set of values
print("{:6d} {:6d} {:6d} {:6d}"
.format(i, i ** 2, i ** 3, i ** 4))

# Driver Code
n1 = int(input("Enter lower range (e.g. 3):-\n"))
n2 = int(input("Enter upper range (e.g. 6):-\n"))

print("------Before Using Formatters-------")

# Calling function without formatters


unorganized(n1, n2)

print()
print("-------After Using Formatters---------")
print()

# Calling function that contains


# formatters to organize the data
organized(n1, n2)

Output:
Employee Name is Mike, Salary is 4500.
Employee Name is Sarah, Salary is 5000.
Debugging bugs='cochroaches' count=9 area='bedroom'
My name is Tony Howard Stark AKA the Iron Man.
Enter lower range (e.g. 3):-
4
Enter upper range (e.g. 6):-
8
------Before Using Formatters-------
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401

-------After Using Formatters---------

4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401

Explanation:
The Python code presents an illustration of diversity in how string formatting is
executed: from positional arguments to f-strings, and dictionary unpacking. The use of
`str.format()` is first illustrated when displaying names and salaries. Then follows the
use of f-strings to embed variables in a direct, readable way. Printing integer powers is
next, comparing an unformatted with a formatted version. Finally, collecting user input
illustrates how formatting can make output clearer.

4. Code
import locale
locale.setlocale(locale.LC_ALL, 'en_GB')
print(locale.currency(12345.67, grouping=True))
print(locale.currency(12345.67))
locale.setlocale(locale.LC_ALL, 'en_US')
print(locale.currency(12345.67, grouping=True))
print(locale.currency(12345.67))
locale.setlocale(locale.LC_ALL, 'en_JP')
print(locale.currency(12345.67, symbol=True, grouping=True,
international=True))
print(locale.currency(12345.67, grouping=True))
print(locale.currency(12345.67))
Output:
£12,345.67
£12345.67
$12,345.67
$12345.67
JPY12,345.67
¥12,345.67
¥12345.67

Explanation:
This excerpt demonstrates currency formatting in Python via the use of the `locale`
module with different regional settings. It first starts by formatting amounts in British
English, displaying both grouped as well as ungrouped outputs. The locale is then
changed to American English for USD formatting, demonstrating the effect of grouping.
Lastly, it assumes the Japanese formatting, rounding the currency to Yen.

5. Code
import datetime

current_date = datetime.datetime.today()

dt_fmt1 = '{:%a, %b %d %Y}'.format(current_date)


dt_fmt2 = '{:%A, %B %d %Y}'.format(current_date)
dt_fmt3 = '{:%m/%d/%Y}'.format(current_date)
dt_fmt4 = '{:%d-%m-%Y}'.format(current_date)
dt_fmt5 = '{:%m/%d/%y %H:%M %S}'.format(current_date)
dt_fmt6 = '{:%m/%d/%y %I:%M %S %p}'.format(current_date)

print(dt_fmt1)
print(dt_fmt2)
print(dt_fmt3)
print(dt_fmt4)
print(dt_fmt5)
print(dt_fmt6)

Output:
Fri, Nov 15 2024
Friday, November 15 2024
11/15/2024
15-11-2024
11/15/24 03:27 16
11/15/24 03:27 16 AM

Explanation:
This code utilizes the datetime module to print out the date and time with different
representations. Importing the datetime module, it gets the current date and time by
`datetime.datetime.today()` and stores it in the variable `current_date`. Then, several
formatting techniques are carried out to display dates, displaying both full and
abbreviated weekday and month names. The script makes use of 12-hour and 24-hour
time presentations. Finally, the date strings are printed out with formatting to show the
flexibility offered by Python in terms of date formatting.

6. Code
phonebook = {
"Arjun": 7387,
"Jack": 3719,
"Pooja": 7052,
}

print(phonebook["Jack"])

table = {'Singh': 4127, 'John': 4098, 'Harry': 7678}


for name, phone in table.items():
print(f'{name:10} and their phone is {phone:10d}')

Output:
3719
Singh and their phone is 4127
John and their phone is 4098
Harry and their phone is 7678

Explanation:
The following Python code demonstrates how dictionaries might be used to create and
retrieve entries in a phonebook. A dictionary named `phonebook` is created and then
retrieved and printed for the "Jack." phone number. Another dictionary, `table`, is also
defined, and its items are iterated overprinting each name as well as the phone number
in a formatted fashion. It illustrates how dictionaries may be useful in streamlining
the organization of data.
7. Code
def addNumbers(*args):
sum = 0
for num in args:
sum += num
return sum

result = addNumbers()
print('Sum is', result)

result = addNumbers(5, 6, 7, 8)
print('Sum is', result)
result = addNumbers(5, 6, 7, 8, 9, 1, 2, 3, 4, 5)
print('Sum is', result)
Output:
Sum is 0
Sum is 26
Sum is 50

Explanation:
This code demonstrates the function `addNumbers`, which accepts any variable number
of input arguments via the `*args` syntax, returning their sum. First, it initializes a zeroed
`sum` that would iterate over all the arguments and add them up. Then, the function is
called three times. The first time, it does not accept any arguments and returns 0. The
second time, with four values, the sum of which is 26. Then follows ten numbers with a
total of 56. Lastly, all results are printed out.

8. Task-1
Code :
import math

def find_area(radius):
area = math.pi * pow(radius, 2) # Using the `pow` function instead of `**`
print(f"Area of circle: {area:.2f}")

find_area(9)
Output:
Area of circle: 254.47
Explanation:
This function calculates the area of a circle with a specified radius and then prints the
calculated area rounded to two decimal places. A brief print statement contains an
example of the output, with a radius of 9.

Task-2
Code:
import math
def area_for_multiple_radii(*radii):
areas = [(radius, round(math.pi * radius ** 2, 2)) for radius in radii]
for radius, area in areas:
print("Area for radius", radius, "is", area)

area_for_multiple_radii(7, 9.1, 4.2)


Output:
Area for radius 7 is 153.94
Area for radius 9.1 is 260.16
Area for radius 4.2 is 55.42
Explanation:
It computes area for a list of radii and prints each area rounded to two decimal places.
It's obvious and explicit about what is returned: namely the radius. The example
demonstrates how to invoke the function with a few different radii.

Task-3
Code :
import locale
import datetime

# Set locale to Japanese and get currency in Yen


locale.setlocale(locale.LC_ALL, 'ja_JP.UTF-8')
yen = locale.currency(450, grouping=True)

# Set locale to US English and get currency in USD


locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
usd = locale.currency(100, grouping=True)

# Get current date and time


current_time = datetime.datetime.now()
print("Current Date and Time:", current_time)
print("In Japanese Yen:", yen)
print("In US Dollars:", usd)

Output:
Current Date and Time: 2024-11-15 03:37:31.108773
In Japanese Yen: ¥450
In US Dollars: $100.00
Explanation:
As such, it should now print a full current date and time as well as clearly labeled
currency amounts for both Yen and Dollars. Used locale and datetime to show time and
currency.

Task-4
Reflection:
Variadic functions are elegant solutions for one of the problems in the need for a
function accepting a variable number of arguments. Such is useful when we cannot
predict how many inputs the user or the system will provide. But, of course, formatted
output brings yet another group of risks if one does not use them carefully. The chances
of runtime errors or crashes are high in case of inconsistent numbers of arguments
passed and the format string. For example, if formatted output is expecting an integer,
while a string gets passed to it, it will behave erratically. Without proper validation of its
input, variadic functions become susceptible to such conditions. So, proper validation of
the data passed into a function with regards to the expected format of the function is
required and must not be ignored. In addition, proper error handling may prevent
problems like this from becoming system crashes. Validity and data type checking of the
input at regular intervals by the program means that the error chances are reduced
considerably, thus making the program execute more smoothly.

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