802 Lab6 Shoaib
802 Lab6 Shoaib
802 Lab6 Shoaib
Code:
print("1/7", str(1/7))
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
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.
# Driver Code
n1 = int(input("Enter lower range (e.g. 3):-\n"))
n2 = int(input("Enter upper range (e.g. 6):-\n"))
print()
print("-------After Using Formatters---------")
print()
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
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()
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"])
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)
Task-3
Code :
import locale
import datetime
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.