Documente Academic
Documente Profesional
Documente Cultură
Manipulation
Implement a program that takes a filename as an input from a user and print
the extension of that filename.
>>> Solution
As an example:
>>> Solution
import datetime
my_year = int(input("Enter a year yyyy: "))
my_month = int(input("Enter a month mm: "))
my_day = int(input("Enter a day dd: "))
my_date = datetime.date(my_year, my_month, my_day)
print(my_date)
two_days = datetime.timedelta(days=2)
print(my_date + two_days)
Note that you do not need to memorise the specifiers code to format a string
or a date, refer to the specifiers code table.
>>> Solution
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print ('{0:%d-%m-%Y %X}'.format(now))
As an example, this is what your program should display after the user
entered a sequence of integers as follows:
>>> Solution
values = input("Enter a sequence of integers separated by commas(no whitespace characters): ")
my_list = values.split(",")
my_tuple = tuple(my_list)
my_set = set(my_list)
print(my_list)
print(my_tuple)
print(my_set)
>>> Solution
import math
Example of output:
31 is between 30 and 59
Note that you do not need to memorise the specifiers code to format a string
or a date, refer to the specifiers code table.
>>> Solution
import random
for i in range(5):
my_num = random.random()*100
print("{0:<10.2f}".format(my_num), end = " ")
print("\n")
my_int = random.randint(0, 100)
if my_int >= 60:
print("{} is greater than or equal to 60".format(my_int))
elif my_int >= 30:
print("{} is between 30 and 59".format(my_int))
else:
print("{} is strictly less than 30".format(my_int))
Save your module into your python_scripts directory (in Documents). Run it to
check if no error is raised.
Import your module, radius, in test_radius.py and call the functions from radius
to print the perimeter, the area of a circle and the volume of a sphere
(floating point numbers with 2 decimals), for a radius of 2cm.
Reminder
Reminder When importing a module, you have to remove the file extension
.py.
>>> Solution
#!/usr/bin/env python
import math
pi = math.pi
def circle_perimeter(r):
"""Returns the perimeter of a circle given its radius """
return 2 * pi * r
def circle_area(r):
"""Returns the perimeter of a circle given its radius """
return pi * r**2
def sphere_volume(r):
"""Returns the perimeter of a circle given its radius """
return 4/3 * pi * r**3
#!/usr/bin/env python
import radius
Note that to delete a directory using os.rmdir(), it has to be empty. Note that
once a directory created, trying to create it again raises an error. (Comment
the line to debug in the editor)
>>> Solution
import os
# The path to your document depends on your Operating System and its version
os.chdir('/home/delseny/Documents')
os.mkdir('dir_test')
os.mkdir('dir_test2')
os.chdir('dir_test')
print(os.getcwd())
with open('test.txt', 'w') as f:
f.write('Hello')
os.chdir('../dir_test2')
with open('../dir_test/test.txt', 'r') as f:
print(f.read())
os.chdir('..')
os.remove('dir_test/test.txt')
os.rmdir('dir_test')
os.rmdir('dir_test2')
/home/delseny/Documents/dir_test
Hello
MatPlotLib
Implement a program to plot a pie chart with commas-separated numbers
entered by a user from the input (no space allowed):
As an example, this is what should be displayed once the user have entered
the values:
Assume we are creating groups of person, each entered value represents the
number of persons in a group.
There are as many groups as input values. To get the number of groups:
Hint Use the string split() method to create a list (using the comma as a
separator) from the entered values. Return the lenght of the list using the
len() function to get the number of groups.
Hint 'group1' is the result of 'group' + str(1): Use a for loop to iterate over a
range() object from 1 up to the length of the list (included) to concatenate
'group' with 1, 2, 3, etc. to provide labels names. You may use a list
comprehension syntax.
Add the corresponding percentage for each group passing the keyword
argument autopct='%.2f%%' to plt.pie()
Note that you do not need to memorise the syntax of pyplot functions to
create plots, refer to your course, to MatPlotLib galleries, and adapt your
code accordingly.
>>> Solution
import matplotlib.pyplot as plt
values = input("Enter commas-separated values for plotting the pie chart: ")
num_list = values.split(",")
nb_groups = len(num_list)
my_labels = ["group"+str(i) for i in range(1, nb_groups + 1)]
x_values = list(map(float, x_strings))
plt.pie(x_values, labels = my_labels, autopct='%.2f%%')
plt.title("Number of persons per group")
plt.show()