0% found this document useful (0 votes)
4 views3 pages

Python Programming Exercises for Beginners

The document provides 10 Python exercises involving various programming concepts like functions, dates, lists, tuples, files, and conditionals. The exercises cover skills like defining functions, working with dates, splitting strings, reading/writing files, and determining even/odd numbers.

Uploaded by

blossomb8090s
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)
4 views3 pages

Python Programming Exercises for Beginners

The document provides 10 Python exercises involving various programming concepts like functions, dates, lists, tuples, files, and conditionals. The exercises cover skills like defining functions, working with dates, splitting strings, reading/writing files, and determining even/odd numbers.

Uploaded by

blossomb8090s
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

BAI 3301

Python Exercises

1- Write a Python program to display the current date and me.

import datetime
now = [Link]()
print("Current date and time : ", now)

2- Write a Python func on that calculates and returns the area of a circle based on the radius.

from math import pi


Def CircleArea(r):

area = pi * r ** 2
return area

3- Write a Python func on that accepts the user's first and last name and store them in a file with
the name “[Link]”.

Def CircleArea(lastname, firstname):

filename = open(“[Link]”, a)
fullname = firstname + “ “ + lastname + “\n”
[Link](fullname)

4- Write a Python program that accepts a sequence of comma-separated numbers from the user
and generates a list and a tuple of those numbers.
Sample data : 3, 5, 7, 23

numbers = “3,5,7,23”
numbers_list = [Link](",")
numbers_tuple = tuple(list)
5- Write a Python program to switches the posi on of colors “Red” and “Black” in the following list.

color_list = ["Red","Green","White" ,"Black"]

color_list = ["Red", "Green", "White", "Black"]


temp = color_list[0]
color_list[0] = color_list[-1]
color_list[-1] = temp

6- Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.

Solu on 1:

a = 5
n1 = int("%s" % a)
n2 = int("%s%s" % (a, a))
n3 = int("%s%s%s" % (a, a, a))
n = n1 + n2 + n3

Solu on 2: (Hiba Msa a’s solu on)

a = 5
n = a*111 + a*11 + a

7- Write a Python program that will read the file name “[Link]” and store the second line in a list
called loaded_data’
[Link]:
Output: loaded_data=[20,45,66,71,25,120]
12,5,21,87,48,36

20,45,66,71,25,120
Filename = open(“[Link]”, r)
55,53,41,85,114,25
for line in range (0,2):
170,221,52,4,89,15
Line = [Link]()
loaded_data=[Link](“,”)
8- Write a Python program to calculate the number of days between two dates.
Sample dates : 10/20/2023 and 11/18/2023

from datetime import date


f_date = date(2023, 10, 10)
l_date = date(2023, 11, 18)
delta = l_date - f_date

print([Link])

9- Write a Python program that determines whether a given number is even or odd, and prints an
appropriate message to the user.

number = 5
mod = number % 2
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")

10- Write a Python func on called “list_count” to count and return the number 4 in a given list.
Example: list1 = [4, 12, 6, 7 , 4]
Print(list_count(list1) Output : 2

def list_count(numbers):
count = 0

for num in numbers:


if num == 4:
count = count + 1

return count

Common questions

Powered by AI

To calculate the area of a circle given its radius in Python, import the constant pi from the math module and use the formula for the area of a circle (A = πr²). Define a function `CircleArea` that takes the radius as an argument, calculates the area using `area = pi * r ** 2`, and returns the result .

To switch the positions of the first and last elements in a list in Python, use indexing to access and swap their positions. For a list `color_list`, this can be achieved by storing the first element in a temp variable, assigning the last element to the first position, and then assigning the temp variable to the last position: `temp = color_list[0]; color_list[0] = color_list[-1]; color_list[-1] = temp` .

To count occurrences of the integer 4 in a list using Python, define a function `list_count` that iterates through the list, increments a counter each time 4 is encountered, and returns the count. For example: `def list_count(numbers): count = 0; for num in numbers: if num == 4: count += 1; return count` .

To read specific lines from a CSV file and extract them into a list using Python, open the file, iterate over its lines till reaching the desired line, and split the line into a list based on commas. For example, to extract the second line: `filename = open('data.csv', 'r'); for line in range(0,2): Line = filename.readline(); loaded_data = line.split(',')` .

To determine if a number is even or odd in Python, use the modulus operator `%` to check the remainder when dividing by 2. If `number % 2` equals 0, the number is even; otherwise, it is odd. Implement a conditional check: `mod = number % 2; if mod > 0: print('This is an odd number.'); else: print('This is an even number.')` .

To compute the number of days between two specific dates in Python, use the `date` class from the `datetime` module, instantiate two date objects, and find the difference between them using subtraction which yields a timedelta object. For example: `f_date = date(2023, 10, 10); l_date = date(2023, 11, 18); delta = l_date - f_date; print(delta.days)` .

To compute the value of an integer expressed as n+nn+nnn, convert the integer into a string and repeatedly concatenate it to form 'nn' and 'nnn'. Then convert these strings back to integers and sum them: `n1 = int('%s' % a); n2 = int('%s%s' % (a, a)); n3 = int('%s%s%s' % (a, a, a)); n = n1 + n2 + n3`. Alternatively, use simple arithmetic with multiplication: `n = a*111 + a*11 + a` .

To store a user's full name in a text file using Python, open the file in append mode and write the name to it. Define a function that takes the last name and first name as inputs, opens 'users.txt' in append mode, concatenates the names with a space and newline, then writes it to the file: `filename = open('users.txt', 'a'); fullname = firstname + ' ' + lastname + '\n'; filename.write(fullname)` .

To generate both a list and a tuple from a sequence of comma-separated numbers in Python, use the string `split` method to break the sequence into a list, and then convert this list into a tuple. Assuming `numbers` is a string of numbers, apply `numbers_list = numbers.split(',')` to get a list. Convert to a tuple with `numbers_tuple = tuple(numbers_list)` .

To display the current date and time in Python, use the `datetime` module. First, import it, then call `now()` method of `datetime` class to get the current date and time: `import datetime; now = datetime.datetime.now(); print('Current date and time : ', now)` .

You might also like