[go: up one dir, main page]

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

Python_Exercises_with_Examples

Uploaded by

Sibling War
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

Python_Exercises_with_Examples

Uploaded by

Sibling War
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Python Programming Exercises with Solutions

Fibonacci Series using Function


Code:

def fibonacci_series(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

n_terms = int(input("Enter the number of terms: "))


fibonacci_series(n_terms)

Example:

Input: 5
Output: 0 1 1 2 3

Palindrome Check using Function


Code:

def is_palindrome(s):
return s == s[::-1]

string = input("Enter a string: ")


if is_palindrome(string):
print(f"{string} is a palindrome.")
else:
print(f"{string} is not a palindrome.")

Example:

Input: 'madam'
Output: madam is a palindrome.

Random Number Generator (Dice Simulator


Code:
import random

def roll_dice():
return random.randint(1, 6)

print(f"You rolled a {roll_dice()}")

Example:

Output: You rolled a 4

Creating and Importing a Library


Code:

# library.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b

# main.py
import library

print(library.add(5, 3))
print(library.subtract(5, 3))

Example:

Output: 8
2

Reading Text File Line by Line and Separating Words


Code:

with open('sample.txt', 'r') as file:


for line in file:
words = line.split()
print('#'.join(words))
Example:

Input file: 'hello world\npython programming'


Output: 'hello#world\npython#programming'

Removing Lines Containing 'a' and Writing to Another File


Code:

with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:


for line in infile:
if 'a' not in line:
outfile.write(line)

Example:

Input file: 'apple\nbanana\ngrape'


Output file: 'grape'

You might also like