Python Exercises with Solutions
1. Basic Python Exercises
1 Write a Python program to swap two variables.
Solution: a, b = b, a
2 Write a program to check if a number is even or odd.
Solution: if n % 2 == 0: print('Even') else: print('Odd')
3 Write a program to find the factorial of a number using recursion.
Solution: def fact(n): return 1 if n==0 else n*fact(n-1)
4 Write a program to generate the Fibonacci sequence up to n terms.
Solution: use loop with a, b = 0, 1 and update
2. Web Scraping Exercises
1 Write a program using requests to fetch the HTML content of '[Link]
Solution: import requests; r = [Link]('[Link] print([Link])
2 Parse the HTML page and extract all hyperlinks.
Solution: from bs4 import BeautifulSoup; soup=BeautifulSoup([Link],'[Link]');
print([a['href'] for a in soup.find_all('a', href=True)])
3 Scrape all headings (h1, h2, h3) from a given webpage.
Solution: [h.get_text() for h in soup.find_all(['h1','h2','h3'])]
4 Using Selenium, open a page and extract the page title.
Solution: from selenium import webdriver; driver=[Link](); [Link](url);
print([Link])
3. Password Manager Exercises
1 Write a program to hash a password using SHA256.
Solution: import hashlib; print(hashlib.sha256(b'mypassword').hexdigest())
2 Generate a random password of 12 characters (letters, digits, symbols).
Solution: import random, string;
''.join([Link](string.ascii_letters+[Link]+[Link], k=12))
3 Encrypt and decrypt a message using Fernet.
Solution: from [Link] import Fernet; key=Fernet.generate_key();
f=Fernet(key); token=[Link](b'secret'); print([Link](token))
4 Create a simple console menu: 1) Add password 2) View password 3) Exit.
Solution: use while True loop with input() and dict to store data