Sunteți pe pagina 1din 9

String

Manipulation
Implement a program that takes a filename as an input from a user and print
the extension of that filename.

As an example: mydata.csv should return csv

>>> Solution

filename = input("Enter a Filename with its extension: ")


file_list = filename.split(".")
print(file_list[-1])

Enter a Filename with its extension: mydata.csv


csv

Converting Strings to Dates


Implement a program that takes three imputs: a year, a month, and a day to
display dates:

The given date


The given date + 2 days

As an example:

Enter a year yyyy: 2000


Enter a month mm: 12
Enter a day dd: 25
2000-12-25
2000-12-27

>>> 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)

Enter a year yyyy: 2000


Enter a month mm: 12
Enter a day dd: 25
2000-12-25
2000-12-27
Formatting Dates
Write a Python program to display the current date and time as
follows:

Current date and time :


23-10-2017 14:29:34

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))

Current date and time :


27-10-2017 14:27:06

String Conversion and Data structures


Implement a program which takes a sequence of comma-separated numbers
as an input from a user and generate a list, a tuple, and a set.

As an example, this is what your program should display after the user
entered a sequence of integers as follows:

Enter a sequence of integers separated by commas(no whitespace characters):


1,2,3,4,3,4

['1', '2', '3', '4', '3','4']


('1', '2', '3', '4', '3','4')
{'3', '2', '1', '4'}

Note that a set is an unordered collection without duplicate elements. The


order of elements may be different when displayed.

>>> 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)

Enter a sequence of integers separated by commas(no whitespace characters): 1,2,3,4,3,4


['1', '2', '3', '4', '3', '4']
('1', '2', '3', '4', '3', '4')
{'2', '4', '3', '1'}

the math Module


Read the radius of a circle from the input, and display the perimeter (2.π.r)
with 1 decimal as follows:

The perimeter of a circle of radius 5.0 cm is 31.4 cm

>>> Solution
import math

radius = float(input("Give a radius (cm): "))


print("The perimeter of a circle of radius {:.1f} cm is {:.1f} cm".format(radius, 2 * math.pi * radius))

Give a radius (cm): 5


The perimeter of a circle of radius 5.0 cm is 31.4 cm
Loops, if...elif...else Statements, and the
random Module
1. Using a for loop, randomly generate five floating point numbers in
the range [0.0, 100.0], including both end points.
2. Print out the numbers inline and use the format() method to get left-
aligned numbers (default alignment is right for numbers) with 2
decimals, and fix the field specifier to 10 characters.
3. Skip a line using the new line character, \n.
4. Randomly generate an integer in the range of [0, 100], including
both end points. Test if this integer is included in the range of [0, 29],
[30, 59], or [60, 100], including both end points. Display a message
accordingly:

? is greater than or equal to 60


? is between 30 and 59
? is strictly less than 30

Example of output:

33.06 0.84 16.50 39.02 35.13

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))

2.77 34.93 19.25 44.31 99.06

3 is strictly less than 30

Module and Functions


Define a module named radius.py that defines three functions:
circle_perimeter(r), circle_area(r), and sphere_volume(r)which take the radius of
a circle as an argument and respectivily return the perimeter, the area, and
the volume of the sphere.

Save your module into your python_scripts directory (in Documents). Run it to
check if no error is raised.

Create a script named test_radius.py and save it into your python_scripts


directory (in Documents), alongside your module, rayon.py.

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.

The output is expected to be:

For a radius of 2 cm:


- the perimeter is 12.57 cm
- the area is 12.57 cm
- the volume is 33.51 cm

Reminder

Perimeter of a circle = 2.π.r


Area of a circle = π.r²
Volume of a sphere = 4/3.π.r³

Reminder When importing a module, you have to remove the file extension
.py.

You module radius.py:

>>> Solution
#!/usr/bin/env python

"""This module provides functions


to calculate the perimeter or the area of a circle given
its radius and the volume of a sphere given its radius.
"""

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

Your script test_radius.py:

#!/usr/bin/env python

import radius

print("For a radius of 2 cm: ")


print("- the perimeter is {:.2f} cm".format(radius.circle_perimeter(2)))
print("- the area is {:.2f} cm".format(radius.circle_area(2)))
print("- the volume is {:.2f} cm".format(radius.sphere_volume(2)))

For a radius of 2 cm:


- the perimeter is 12.57 cm
- the area is 12.57 cm
- the volume is 33.51 cm
the os Module, Writing, and Reading a
file
Change your current directory to be your Documents directory using an
absolute path
Create two new directories dir_test, and dir_test2
Change your current directory to be dir_test
Display your current directory
Create a file named test.txt in dir_test in writing mode and write
'Hello' inside
Change your directory to be dir_test2 using a relative path
Using a relative path, open test.txt in reading mode and display its
content
Using a relative path, change your directory to be your Documents
directory
Delete test.txt and the two directories just created

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:

Enter commas-separated values for plotting the pie chart: 1,62,13,45

Assume we are creating groups of person, each entered value represents the
number of persons in a group.

In the previous example, we have 4 groups of 1, 62, 13, and 45 persons.

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.

Add labels to the plot: group1, group2, group3, etc.

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()

Add a title to your chart: Number of persons per group

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()

Enter commas-separated values for plotting the pie chart: 12,15,85,6

S-ar putea să vă placă și