0% found this document useful (0 votes)
5 views

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

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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy