├── Day3 ├── README.md ├── bubblesort.py ├── binarysearch.py ├── random_password_generator.py └── collatz.py ├── Day1 ├── README.md └── day1_program_assignment.md ├── Day2 ├── README.md └── day2_programs ├── Day8 ├── sort_dict_value ├── audiobook.py ├── password-validator.py └── try_and_except_examples.py ├── Day5 ├── dejavu.py ├── average_word_length.py ├── piglatin.py └── intro_to_enumerate.md ├── mini_project_to_try ├── clock.py ├── image_to_sketch.py ├── company_stocks.py ├── alarm.py ├── you_vs_kazuma_rock_paper_scissor.py ├── library.py ├── high_low_game │ └── bungou_simple_game.py └── hangman.py ├── Day6 ├── word_frequency_counter.py ├── numeral.py ├── mall_shopping.py └── phonebook.py ├── Day9 ├── oops.py ├── inheritance.py └── library.py ├── Day7 ├── moorse_code.py ├── moorse_code │ ├── text_to_moorse.py │ └── moorse_code.py ├── remove_punctuation.py ├── word_character_calculator.py └── caser_cipher.py ├── Day4 ├── anagrams.py ├── palindrome.py ├── tax.py ├── secret.py └── password.py ├── README.md └── Day10 ├── types_of_errors.md └── exception_handling.md /Day3/README.md: -------------------------------------------------------------------------------- 1 | Day 3 Tutorials: [Functions](https://animevyuh.org/learn-python-part3/) 2 | -------------------------------------------------------------------------------- /Day1/README.md: -------------------------------------------------------------------------------- 1 | ### Complete Day 1 Task 2 | 3 | Day 1 Tutorial: [Variable, Data Types, User Input](https://animevyuh.org/learn-python) 4 | -------------------------------------------------------------------------------- /Day2/README.md: -------------------------------------------------------------------------------- 1 | ### Complete Day-2 Task 2 | 3 | Day-2 Tutorial: [Conditional Statements](https://animevyuh.org/learn-python-part2/) 4 | -------------------------------------------------------------------------------- /Day8/sort_dict_value: -------------------------------------------------------------------------------- 1 | manual = {"apple":12,"mango":23,"cake":2,"pastries":4,"chocolate":56} 2 | sorted_dict = dict(sorted(manual.items(),reverse=True,key=lambda x:x[1])) 3 | print(sorted_dict) 4 | """ 5 | sorted returns in list with a tuple of dictionary items with values at index one 6 | """ 7 | 8 | 9 | -------------------------------------------------------------------------------- /Day3/bubblesort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(container): 2 | for i in range(len(container)): 3 | for j in range(i+1,len(container)): 4 | if container[i]>container[j]: 5 | container[i],container[j]=container[j],container[i] 6 | 7 | return container 8 | 9 | print(bubble_sort([5,1,4,2,8])) -------------------------------------------------------------------------------- /Day5/dejavu.py: -------------------------------------------------------------------------------- 1 | def dejavu(text): 2 | count=0 3 | new=list() 4 | for i in text: 5 | if i not in new: 6 | new.append(i) 7 | else: 8 | count=1 9 | return count 10 | 11 | word=list(input()) 12 | count=dejavu(word) 13 | if count==1: 14 | print('Deja Vu') 15 | else: 16 | print('Unique') -------------------------------------------------------------------------------- /mini_project_to_try/clock.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from time import strftime 3 | 4 | root=tk.Tk() 5 | root.title("Clock") 6 | 7 | timing=tk.Label(root,font=("arial",100),bg="black",fg="white") 8 | timing.pack() 9 | 10 | def clock(): 11 | clock_time=strftime('%X %p') 12 | timing.config(text=clock_time) 13 | timing.after(1000,clock) 14 | 15 | clock() 16 | 17 | root.mainloop() -------------------------------------------------------------------------------- /Day3/binarysearch.py: -------------------------------------------------------------------------------- 1 | def search(nums,target): 2 | nums.sort() 3 | beg,end=0,len(nums)-1 4 | while beg<=end: 5 | mid = (beg+end)//2 6 | if nums[mid]==target: 7 | return mid 8 | elif target>nums[mid]: 9 | beg=mid+1 10 | else: 11 | end=mid-1 12 | return -1 13 | 14 | target = int(input("Enter a target element")) 15 | print(search([1,22,4,56,446,56,2,5],target)) -------------------------------------------------------------------------------- /Day6/word_frequency_counter.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | def remove_punction(para): 4 | new = "" 5 | for i in para: 6 | if i in string.punctuation: 7 | pass 8 | else: 9 | new+=i 10 | return new 11 | 12 | sample_input = input("Enter a sentence:") 13 | word_dictionary = dict() # or {} 14 | sentence = remove_punction(sample_input) 15 | 16 | for word in sentence.split(): 17 | word_dictionary[word] = 1 if word not in word_dictionary else word_dictionary[word]+1 18 | 19 | print(word_dictionary) -------------------------------------------------------------------------------- /Day9/oops.py: -------------------------------------------------------------------------------- 1 | class Anime: 2 | def __init__(self,anime_name,anime_episode): 3 | self.name = anime_name 4 | self.episode = anime_episode 5 | 6 | def overview(self): 7 | print("Anime Name:",self.name) 8 | print("Its Episode:",self.episode) 9 | 10 | anime1 = Anime("Psycho Pass",41) #first instance 11 | anime1.overview() 12 | anime2 = Anime("Vinland Saga",24) #second instance 13 | anime2.overview() 14 | anime3 = Anime("Ergo Proxy",23) #third instance 15 | anime3.overview() 16 | anime4 = Anime() #error, it cant be empty 17 | anime4.overview() -------------------------------------------------------------------------------- /Day7/moorse_code.py: -------------------------------------------------------------------------------- 1 | """ 2 | Moorse Code: A-Z alphabets is replaced with sequence of dits(.) and dahs(-) 3 | 4 | Here let us create two Python file. In one .py file store the Moorse Code. And In other .py file write a code to convert Text to Moorse Code 5 | 6 | """ 7 | import string 8 | 9 | alpha = string.ascii_uppercase 10 | mc=['.-','-...','-.-.','-...','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..'] 11 | moorse = dict() 12 | for code in range(len(alpha)): 13 | moorse[alpha[code]]=mc[code] -------------------------------------------------------------------------------- /Day8/audiobook.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 as ts #import python text to speech module 2 | import PyPDF2 as pdf #import pythn pdf reader module 3 | import os 4 | 5 | path = os.path.join("Desktop","Books","Do the Work.pdf") 6 | 7 | open_pdf=open(path,'rb') 8 | 9 | read_pdf=pdf.PdfFileReader(open_pdf) 10 | 11 | #speak from page asssigned 12 | speak=ts.init() 13 | speak.setProperty("rate", 178) 14 | #read first 10 pages 15 | for start_read in range(10): 16 | starting_page=read_pdf.getPage(start_read) 17 | text=starting_page.extractText() 18 | speak.say(text) 19 | speak.runAndWait() 20 | -------------------------------------------------------------------------------- /Day7/moorse_code/text_to_moorse.py: -------------------------------------------------------------------------------- 1 | from moorse_code import moorse 2 | 3 | text = input("Enter the Text: ").upper() 4 | with open("Before.txt","w") as file: 5 | file.write(text) 6 | file.close() 7 | 8 | #double space means new letter, while single space is gap between two moose converted letter 9 | moorse_converted = "" 10 | for letter in text: 11 | if letter==" ": 12 | moorse_converted+=" " 13 | if letter in moorse: 14 | moorse_converted+=moorse[letter]+" " 15 | 16 | with open("After.txt","w") as new: 17 | new.write(moorse_converted) 18 | 19 | new.close() -------------------------------------------------------------------------------- /Day4/anagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | Program 2: Anagrams 3 | Input : s1 = "luffy" 4 | s2 = "fufly" 5 | Output : Pair of words are anagrams 6 | 7 | Sample Input : s1 = "luffy" 8 | s2 = "naruto" 9 | Sample Output : Not a anagrams 10 | 11 | Sample Input : s1 = "bad" 12 | s2 = "dad" 13 | Sample Output : Not a anagrams 14 | 15 | Sample Input : s1 = "cool" 16 | s2 = "loco" 17 | Sample Output : Pair of words are anagrams 18 | """ 19 | word1=input("Enter first string:").lower() 20 | word2=input("Enter second string:").lower() 21 | if(sorted(word1)==sorted(word2)): 22 | print('Pair of words are anagrams') 23 | else: 24 | print('Not a anagrams') -------------------------------------------------------------------------------- /Day4/palindrome.py: -------------------------------------------------------------------------------- 1 | """Program 1: Palindrome 2 | Malayalam, madam, civic. Now why am I mentioning this words. Palindrome are 3 | those words which are pronounced the same even if you read them in reverse 4 | way. The word is Palindrome if it is equal to the reverse of the word. 5 | Sample Input: madam 6 | the reverse of the word is also madam 7 | Thus it is a Palindrome 8 | Sample Input: professor 9 | the reverse of the word is also rosseforp 10 | Thus it is not a Palindrome 11 | """ 12 | palindrome = input("Enter a word: ") 13 | reverse = palindrome[::-1] 14 | if reverse == palindrome: 15 | print("Yes it is a Palindrome") 16 | else: 17 | print("No it is not a Palindrome") 18 | -------------------------------------------------------------------------------- /Day7/remove_punctuation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove Punctuation From a Sentence 3 | Read a File with Text inside it and remove punctuations from the text. 4 | 5 | Sample Input: T%hi/s senten$ce, th@is diffi&^cu)()lt t*o re!a+d| 6 | Sample Output: This sentence this difficult to read 7 | 8 | [Note: Save the Sample Input in some file] 9 | """ 10 | import string 11 | 12 | punc = string.punctuation 13 | with open("reference.txt") as ref_file: 14 | content = ref_file.read() 15 | ref_file.close() 16 | 17 | print("Before: {}".format(content)) 18 | 19 | proper_text = "" 20 | for word in content: 21 | if word in punc: 22 | pass 23 | else: 24 | proper_text+=word 25 | 26 | print("After: {}".format(proper_text)) 27 | -------------------------------------------------------------------------------- /Day4/tax.py: -------------------------------------------------------------------------------- 1 | name=input("Enter your name: ") 2 | age=int(input('Enter your age:')) 3 | while True: 4 | gender=input('Enter M for male and F for Female:').lower() 5 | if gender not in 'm f': 6 | continue 7 | else: 8 | break 9 | 10 | if(age>=65 or gender.startswith('f')): 11 | tax='Nile' 12 | if(age<=65 and gender.startswith('m')): 13 | tax_amt=int(input('Enter your Taxable Income: ')) 14 | if tax_amt<0 or tax_amt in range(0,16001): 15 | tax=0 16 | elif tax_amt in range(160001,500001): 17 | tax=(tax_amt-160000)*0.1 18 | elif tax_amt in range(500001,800001): 19 | tax=((tax_amt-500000)*0.2)+34000 20 | elif(tax_amt>800000): 21 | tax=((tax_amt-160000)*0.3)+94000 22 | print('Tax to be paid',tax) -------------------------------------------------------------------------------- /Day6/numeral.py: -------------------------------------------------------------------------------- 1 | """ 2 | Input Format: 3 | A string of the phrase in its original form (lowercase). 4 | 5 | Output Format: 6 | A string of the updated phrase that has changed the numerals to words. 7 | Sample Input: I need 2 pumpkins and 3 apples 8 | 9 | Sample Output: I need two pumpkins and three apples 10 | """ 11 | 12 | def numeral(num,n): 13 | nonum=dict() 14 | for i in n: 15 | nonum[str(i)]=num[i-1] 16 | return(nonum) 17 | 18 | num=['one','two','three','four','five','six','seven','eight','nine','ten'] 19 | n=range(1,11) 20 | nonumeral=numeral(num,n) 21 | data=input('').split() 22 | new_data=[] 23 | for word in data: 24 | if word in nonumeral.keys(): 25 | word=nonumeral[word] 26 | new_data.append(word) 27 | print(' '.join(new_data)) 28 | -------------------------------------------------------------------------------- /mini_project_to_try/image_to_sketch.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import os 3 | 4 | path = os.path.join("Pictures","Anime","aot_cast.jpg") 5 | 6 | img = cv2.imread(path) 7 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 8 | 9 | #find threshold: to convert gray image into binary image 10 | #there are two ways: Sime Threshold and Adaptive Threshold 11 | #we shall use adaptive threshold 12 | manga = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,9) 13 | 14 | #filter the color of main image and applying masking technique using the threshold value 15 | color = cv2.bilateralFilter(img,9,250,250) 16 | comic = cv2.bitwise_and(color,color,mask=manga) 17 | 18 | cv2.imshow('Anime',img) 19 | cv2.imshow("Manga",manga) 20 | cv2.imshow("Comic",comic) 21 | 22 | cv2.waitKey(0) 23 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /Day9/inheritance.py: -------------------------------------------------------------------------------- 1 | class Kurama: 2 | def powers(self): 3 | return "Nine Tails Chakra" 4 | 5 | class Naruto(Kurama): 6 | def battle(self): 7 | return "Sage Mode" 8 | def superpowers(self): 9 | return "I will just Talk" 10 | 11 | war = Naruto() 12 | print(war.battle()) 13 | print(war.powers()) 14 | print(war.superpowers()) 15 | 16 | """ 17 | class SliceOfLife: 18 | def inside(self): 19 | return "Inside Slice of Anime" 20 | 21 | class Romance(SliceOfLife): 22 | def inside(self): 23 | return "Inside Romance" 24 | 25 | class Comedy(Romance): 26 | def inside(self): 27 | return "Inside Comedy" 28 | 29 | genre = Comedy() 30 | print(genre.inside()) 31 | genre1 = Romance() 32 | print(genre1.inside()) 33 | genre2 = SliceOfLife() 34 | print(genre2.inside()) 35 | 36 | """ -------------------------------------------------------------------------------- /Day5/average_word_length.py: -------------------------------------------------------------------------------- 1 | """ 2 | Takes in a string, figure out the average length of all the words and return a number representing the average length. Remove all punctuation. Round up to the nearest whole number. 3 | 4 | Input Format: 5 | A string containing multiple words. Input: What a drag Shikamaru 6 | 7 | Output Format: 8 | A number representing the average length of each word, rounded up to the nearest whole number. Output: 5 9 | 10 | Explanation: 11 | The string in question has 4 words with a total of 18 letters (spaces do not count). The average word length is 4.50 letters, rounding it up to the nearest whole numbers results in 5. 12 | """ 13 | import math 14 | import string 15 | data = input().split(' ') 16 | avg_word = [] 17 | for calc in data: 18 | for check in calc: 19 | if check in string.punctuation: 20 | pass 21 | else: 22 | avg_word.append(check) 23 | 24 | print(math.ceil(len(avg_word)/len(data))) 25 | -------------------------------------------------------------------------------- /Day7/word_character_calculator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Character and Word Calculator 3 | Write a program to print total words, total characters including spaces and total characters excluding characters from the reference.txt. 4 | 5 | reference.txt : 6 | 7 | Anime Quotes of Main Characters: 8 | Naruto: "Until I become Hokage, I can't die" 9 | Luffy: "I will become the Pirate King, I dont care if I die trying" 10 | Hinata: "Do you need a reason to win?" 11 | Gintoki: "The night is dark before dawn, But don't close your eyes" 12 | """ 13 | with open("reference.txt") as ref_file: 14 | content = ref_file.read() 15 | 16 | space,without_space=0,0 17 | for word in content: 18 | if word == "\n": 19 | pass 20 | elif word == ' ': 21 | without_space+=1 22 | else: 23 | without_space+=1 24 | space+=1 25 | 26 | print(" Total Words:{} \n Total Characters:{} \n Total Characters without space:{}".format(len(content.split()),without_space,space)) -------------------------------------------------------------------------------- /Day4/secret.py: -------------------------------------------------------------------------------- 1 | """ 2 | Program 4: Secret Message 3 | A string of your message in its normal form. Ask user for a input and convert that 4 | message into a secret message. The way you should do this is, say the message is 5 | converted based on backwards alphabets i.e., a is replaced with z, a=z, b=y, c=x, 6 | d=w, e=v, f=u, g=t and so on.. 7 | Output Format: 8 | A string of your message once you have encoded it (all lower case). 9 | Sample Input: Pirate King 10 | Sample Output: krizgv prmt 11 | Explanation: 12 | If you replace each letter in 'Pirate King' with the corresponding letter in a 13 | backwards version of the alphabet, you get 'krizgv prmt'. 14 | """ 15 | 16 | import string 17 | user_data = input().lower() 18 | backwards = string.ascii_lowercase[::-1] 19 | back_alpha = '' 20 | for alpha in user_data: 21 | if alpha == ' ': 22 | back_alpha+=' ' 23 | else: 24 | index = string.ascii_lowercase.index(alpha) 25 | back_alpha+=backwards[index] 26 | print(back_alpha) -------------------------------------------------------------------------------- /Day5/piglatin.py: -------------------------------------------------------------------------------- 1 | """ 2 | Program 1: Piglatin 3 | 4 | Input Format 5 | A string of the sentence in English that you need to translate into Pig Latin. (no punctuation or capitalization), e.g., "nevermind you’ve got them" 6 | 7 | Output Format 8 | A string of the same sentence in Pig Latin. 9 | e.g., output: "evermindnay ouveyay otgay hemtay" 10 | 11 | Explanation 12 | The output should be the original sentence with each word changed so that they first letter is at the end and then -ay is added after that. 13 | """ 14 | 15 | word=input().lower().split() 16 | new=[] 17 | for i in word: 18 | k=i[1:]+i[0]+'ay' 19 | new.append(k) 20 | print(' '.join(new)) 21 | 22 | #or 23 | """ 24 | import string 25 | l=input('Enter a text:').lower().split() 26 | new=[] 27 | punc=string.punctuation 28 | for i in l: 29 | for j in i: 30 | if j in punc: 31 | del j 32 | else: 33 | new.append(j) 34 | k=''.join(new) 35 | new.append(' ') 36 | 37 | print(len(''.join(k.rstrip()))) 38 | """ -------------------------------------------------------------------------------- /Day3/random_password_generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | def satisfied(): 5 | while True: 6 | response=input('Are you Satisfied?(Y/n)').lower() 7 | if response[0] not in ['y','n']: 8 | print("***Invalid entry(enter y/n)***") 9 | continue 10 | if response.startswith('y'): 11 | return True 12 | else: 13 | return False 14 | 15 | def main(): 16 | upper_case = string.ascii_uppercase 17 | lower_case = string.ascii_lowercase 18 | numbers=string.digits 19 | symbols = string.punctuation 20 | password = [] 21 | for _ in range(2): 22 | password.append(random.choice(upper_case)+random.choice(numbers)+random.choice(symbols)) 23 | for _ in range(8): 24 | password.append(random.choice(lower_case)) 25 | print(''.join(password)) 26 | if satisfied(): 27 | print("Your Password is:{}".format(''.join(password))) 28 | print("Thank You") 29 | else: 30 | main() 31 | 32 | main() 33 | 34 | -------------------------------------------------------------------------------- /mini_project_to_try/company_stocks.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | import yfinance as finance 3 | 4 | def get_ticker(name): 5 | company = finance.Ticker(name) #google 6 | return company 7 | 8 | st.title("Build and Deploy Stock Market App Using Streamlit") 9 | st.header("A Basic Data Science Web Application") 10 | 11 | st.sidebar.header("Geeksforgeeks \n TrueGeeks") 12 | 13 | company1 = get_ticker("GOOGL") 14 | company2 = get_ticker("MSFT") 15 | 16 | google = finance.download("GOOGL", start="2021-10-01", end="2021-10-01") 17 | microsoft = finance.download("MSFT", start="2021-10-01", end="2021-10-01") 18 | 19 | data1 = company1.history(period="3mo") 20 | data2 = company2.history(period="3mo") 21 | 22 | company2.history() 23 | st.write(company1.info) 24 | st.write(""" 25 | ### Google 26 | """) 27 | st.write(company1.info['longBusinessSummary']) 28 | st.write(google) 29 | st.line_chart(data1.values) 30 | 31 | st.write(""" 32 | ### Microsoft 33 | """) 34 | st.write(company2.info['longBusinessSummary'],"\n",microsoft) 35 | st.line_chart(data2.values) -------------------------------------------------------------------------------- /Day7/moorse_code/moorse_code.py: -------------------------------------------------------------------------------- 1 | Program 4: Moorse Code 2 | 3 | Here let us create two Python file. In one .py file store the Moorse Code. And In other .py file write a code to convert Text to Moorse Code 4 | 5 | 6 | import string 7 | 8 | alpha = string.ascii_uppercase 9 | mc=['.-','-...','-.-.','-...','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..'] 10 | moorse = dict() 11 | for code in range(len(alpha)): 12 | moorse[alpha[code]]=mc[code] 13 | 14 | 15 | text = input("Enter the Text: ").upper() 16 | with open("Before.txt","w") as file: 17 | file.write(text) 18 | file.close() 19 | 20 | #double space means new letter, while single space is gap between two moose converted letter 21 | moorse_converted = "" 22 | for letter in text: 23 | if letter==" ": 24 | moorse_converted+=" " 25 | if letter in moorse: 26 | moorse_converted+=moorse[letter]+" " 27 | 28 | with open("After.txt","w") as new: 29 | new.write(moorse_converted) 30 | 31 | new.close() -------------------------------------------------------------------------------- /mini_project_to_try/alarm.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from playsound import playsound 3 | import pyttsx3 as ts 4 | import time 5 | speak = ts.init() 6 | 7 | def gettime(): 8 | try: 9 | alarm = input("Enter the time to be alarmed(hr:min PM/AM):") 10 | return alarm 11 | except TypeError: 12 | print('Invalid') 13 | except ValueError: 14 | print("Invalid") 15 | 16 | def time_based(alarm_time): 17 | alarm_hour=alarm_time[0:2] 18 | alarm_min=alarm_time[3:5] 19 | alarm_period=alarm_time[6:8].upper() 20 | print("Alarm Set") 21 | speak.say("Alarm Set") 22 | speak.runAndWait() 23 | while True: 24 | now = datetime.now() 25 | current_hour = now.strftime("%H") 26 | current_min = now.strftime("%M") 27 | current_period = now.strftime("%p") 28 | if current_hour==alarm_hour and current_min==alarm_min and current_period==alarm_period: 29 | speak.say("Wake up tarun") 30 | speak.runAndWait() 31 | time.sleep(2) 32 | playsound("/home/lucifertrj/Music/Arcade.mp3") 33 | break 34 | 35 | alarm_time = gettime() 36 | time_based(alarm_time) 37 | 38 | -------------------------------------------------------------------------------- /Day4/password.py: -------------------------------------------------------------------------------- 1 | """ 2 | Program 5: Strong or Weak password 3 | Let a user enter a password you just have to print Strong or weak, and nothing 4 | else. 5 | A password is said to be strong: 6 |  If password should at-least be 8 letters long 7 |  Password must contain at least one upper case characters [A-Z] 8 |  Password must contain at least 2 numbers [0-9] 9 |  Password must contain at least one 1 special symbol [.,%$#@!^&*():"] 10 | If the above criteria as meet then print Strong, else Weak. 11 | Sample Input: password?!123 12 | Sample Output: Weak [because no upper case character] 13 | Sample Input: LuffyKing&100 14 | Sample Output: Strong 15 | """ 16 | import string 17 | import sys 18 | password = input("Enter your password:") 19 | if len(password)<8: 20 | print("Weak") 21 | sys.exit() 22 | 23 | numbers,upper_case,symbol = 0,0,0 24 | for check in password: 25 | if check in string.ascii_uppercase: 26 | upper_case+=1 27 | elif check in string.punctuation: 28 | symbol+=1 29 | elif check in string.digits: 30 | numbers+=1 31 | else: 32 | pass 33 | 34 | if upper_case>=1 and numbers>=2 and symbol>=1: 35 | print("Strong") 36 | else: 37 | print("Weak") -------------------------------------------------------------------------------- /Day3/collatz.py: -------------------------------------------------------------------------------- 1 | """" 2 | Write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer sooner or later, using this sequence, you'll arrive at 1! Even mathematicians aren't sure why. Your program is exploring what's called the Collatz sequence, sometimes called the simplest impossible math problem.) Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value. Hint: An integer number is even if number % 2 == 0, and it's odd if number % 2 == 1. The output of this program could look something like this: 3 | 4 | Sample input: 3 5 | Sample output: 6 | 10 7 | 5 8 | 16 9 | 8 10 | 4 11 | 2 12 | 1 13 | 14 | Sample input: 5 15 | Sample output: 16 | 16 17 | 8 18 | 4 19 | 2 20 | 1 21 | """ 22 | def collatz(number): 23 | try: 24 | num=int(input(number)) 25 | while num>1: 26 | if num%2==0: 27 | num=k=num//2 28 | print(k) 29 | else: 30 | num=g=num*3+1 31 | print(g) 32 | except ValueError: 33 | print('Number should be integer and not string') 34 | 35 | collatz('Enter a number:') -------------------------------------------------------------------------------- /Day8/password-validator.py: -------------------------------------------------------------------------------- 1 | import string 2 | import time 3 | 4 | def login(): 5 | username=input('Enter your name:') 6 | password=input('Enter the password:') 7 | return password 8 | 9 | def passdetails(): 10 | print('*'*35) 11 | print('The password must contain total of 14 charachters') 12 | print('It must contain one upper case with total of minimum 8 letters') 13 | print('it must contain 2 numbers') 14 | print('It must contain atleast one special character') 15 | print('*'*35) 16 | 17 | def passtype(pword): 18 | lower=string.ascii_lowercase 19 | upper=string.ascii_uppercase 20 | number=string.digits 21 | symbol=string.punctuation 22 | lower_count=upper_count=number_count=symbol_count=0 23 | for letter in pword: 24 | if letter in lower: 25 | lower_count+=1 26 | if letter in upper: 27 | upper_count+=1 28 | if letter in number: 29 | number_count+=1 30 | if letter in symbol: 31 | symbol_count+=1 32 | if(lower_count>=7 and upper_count>=1 and number_count>=2 and symbol_count>=1): 33 | return('Strong') 34 | else: 35 | return('Weak') 36 | 37 | passdetails() 38 | time.sleep(5) 39 | password=login() 40 | print(passtype(password)) -------------------------------------------------------------------------------- /Day5/intro_to_enumerate.md: -------------------------------------------------------------------------------- 1 | ## Introduction to Enumerate 2 | 3 | Before knowing Enumerate lets look into an example as usual. Consider a List and print the elements of the list with their index number. 4 | ```py 5 | >>> myanimelist = ["One Piece","Gintama","Attack On Titan","Code Geass","Monster"] 6 | 7 | >>> for i in range(len(myanimelist)): 8 | ... print(i+1,myanimelist[i]) 9 | ... 10 | 1 One Piece 11 | 2 Gintama 12 | 3 Attack On Titan 13 | 4 Code Geass 14 | 5 Monster 15 | ``` 16 | 17 | The same code lets code it with enumerate. 18 | 19 | ```py 20 | >>> for index,anime in enumerate(myanimelist,1): 21 | ... print("{}:{}".format(index,anime)) 22 | ... 23 | 1:One Piece 24 | 2:Gintama 25 | 3:Attack On Titan 26 | 4:Code Geass 27 | 5:Monster 28 | 29 | >>> for index,anime in enumerate(myanimelist): 30 | ... print("{}:{}".format(index,anime)) 31 | … 32 | 33 | 0:One Piece 34 | 1:Gintama 35 | 2:Attack On Titan 36 | 3:Code Geass 37 | 4:Monster 38 | ``` 39 | 40 | ``Enumerate`` makes our job easy by taking both index and values in one go. Understanding enumerate is easy. We have taken two examples in enumerate function. Enumerate takes two parameters, the first parameter is the iterable sequence such as lists, string, range. And the second parameter is the start index includes a integer value. -------------------------------------------------------------------------------- /Day7/caser_cipher.py: -------------------------------------------------------------------------------- 1 | """ 2 | Caesar Cipher 3 | Caesar cipher uses keys, which encrypt the message differently 4 | depending on which key is used. The keys for the Caesar cipher are the 5 | integers from 1 to 26(a-z). Based On the key from 1-26, the given message is encoded ahead with the given key. 6 | 7 | Sample Input: 8 | Security key: 3 9 | Message: anime 10 | 11 | Sample Output: 12 | dqlph 13 | 14 | Explaination: key=3, first character of message=a a+3=d(b,c,d), 15 | in the same way, n+3 = q (o,p,q) 16 | i+3 = l (j,k,l) 17 | m+3 = p (n,o,p) 18 | e+3 = h (f,g,h) 19 | """ 20 | import string 21 | 22 | with open("actual_message.txt","w") as file: 23 | message = input("Enter the Best Anime you have watched:") 24 | file.write(message) 25 | file.close() 26 | 27 | def security_key(): 28 | while True: 29 | key = int(input("Security Key(1-26):")) 30 | if key not in range(1,27): 31 | continue 32 | return key 33 | 34 | key = security_key() 35 | encrypt = open("actual_message.txt","r").read() 36 | upper_c = string.ascii_uppercase 37 | lower_c = string.ascii_lowercase 38 | 39 | encode = '' 40 | for i in encrypt: 41 | if i in upper_c: 42 | encode+=upper_c[upper_c.index(i)+key-26] if upper_c.index(i)+key>25 else upper_c[upper_c.index(i)+key] 43 | elif i in lower_c: 44 | encode+=lower_c[lower_c.index(i)+key-26] if lower_c.index(i)+key>25 else lower_c[lower_c.index(i)+key] 45 | else: 46 | encode+=' ' 47 | 48 | with open("encrypted.txt","w") as new_file: 49 | new_file.write(encode) 50 | new_file.close() 51 | print("Success, Message Encrypted") 52 | -------------------------------------------------------------------------------- /Day6/mall_shopping.py: -------------------------------------------------------------------------------- 1 | """ 2 | Imagine your in a Mall for Shopping, you come across a store that serves good food. The Menu is displayed to you, you decide the food you like and add it in cart. Once you decided your meal, you now need to order and pay the amount for you meal. And at end display a Thank You message. 3 | """ 4 | import termcolor 5 | def display_menu(): 6 | menu = { 7 | "Papad Salad":60, 8 | "Manchurian Soup":100, 9 | "Jalebi And Fafda":150, 10 | "Baby-Corn Machuri":85, 11 | "Paneer Tikka":100, 12 | "Hamburger":120, 13 | "Double Cheese Decker Pizza":199, 14 | "Butter Kulcha":45, 15 | "Roti":30, 16 | "Malai Kofta":100, 17 | "Dal Fry":80, 18 | "Fried Rice":140, 19 | "Death By Chocolate Desert":200, 20 | "Hot Chocolate":180 21 | } 22 | 23 | termcolor.cprint("\n\t****Welcome To Anime Vyuh Foods****\t\n",color="red") 24 | termcolor.cprint("\n\tHere is the Menu:\n\n",color="yellow") 25 | for food,price in menu.items(): 26 | termcolor.cprint("{} {} :{}INR".format(food,''*20,price),"blue") 27 | 28 | return menu 29 | 30 | course_menu = display_menu() 31 | cart = [] 32 | print("What could you like to eat? Enter the name from the menu") 33 | while True: 34 | eat = input("\nAdd Food Name?(q to quit):") 35 | if eat.lower().startswith('q'): 36 | break 37 | if eat not in course_menu.keys(): 38 | print("Invalid Entry! Check the Spelling and Try again:") 39 | else: 40 | print(eat,"added to eat list.") 41 | cart.append(eat) 42 | 43 | print("The Amount To Be Paid:",end="") 44 | amt = 0 45 | for i in cart: 46 | amt=amt+course_menu[i] 47 | 48 | print(" {} INR\n".format(float(amt))) 49 | print("Thank You For Visiting Us") -------------------------------------------------------------------------------- /Day6/phonebook.py: -------------------------------------------------------------------------------- 1 | phonebook = dict() 2 | 3 | def is_valid(number,name): 4 | # check for valid name and number 5 | # observe we have used if else in single statement 6 | # number should be exactly 10 digit & name should be >3 letters 7 | response = True if len(number)==10 and number.isdigit() and len(name)>=3 else False 8 | return response 9 | 10 | def keep_searching(): 11 | while True: 12 | #ask user if he wants to continue or quit 13 | move = input("Do you want to continue(c) or quit(q)?").lower() 14 | if move not in ['c','q']: #if user enters other than c or q 15 | print("Enter c to continue or q to quit: ") 16 | continue 17 | else: 18 | if move.startswith('c'): 19 | return True 20 | return False 21 | 22 | while True: 23 | name = input("Enter your name:").lower() 24 | phone_number = input("Enter your number:") 25 | if is_valid(phone_number,name): 26 | phonebook[name]=phone_number 27 | else: 28 | print("Invalid Entry..") 29 | continue 30 | 31 | print("Look Into PhoneBook") 32 | search_name = input("Search the name in the Phonebook: ").lower() 33 | if search_name in phonebook: 34 | print(search_name,"number is",phonebook[search_name]) 35 | else: 36 | avaiable = input("Name and number not stored, Do you want add it?(Y/n):").lower() 37 | if avaiable.startswith('y'): 38 | new_number = input("Enter the number to be stored: ") 39 | if is_valid(new_number,search_name): 40 | phone_number[search_name]=new_number 41 | else: 42 | print("Failed to Update") 43 | 44 | if keep_searching(): 45 | continue 46 | else: 47 | print("Thank you for visiting..") 48 | break -------------------------------------------------------------------------------- /Day8/try_and_except_examples.py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose you want your program to run error free, well everyone wants that. 3 | But what if we need our program to run even if there is an error, is there any possibility? Yes There sure is. 4 | Python provides Try and except, using this you can show user the message when certain error is occurred we call it exception. 5 | User get the feedback where he went wrong, using Try And Except Technique. 6 | Giving feedback for your program is every important. 7 | I hope even I do get some feedback about this 30DaysOfPython, I will be waiting for your feedback. 8 | Back to Try and Except again, here you will require the knowledge of some common errors 9 | """ 10 | #example 1 11 | 12 | try: 13 | a = int(input("Enter a number: ")) #integer inputs required 14 | b = int(input("Enter a number2: ")) 15 | div = a/b 16 | if a>b: 17 | print("{} is greater than {}. Quotient is:{}".format(a,b,div)) 18 | else: 19 | print("{} is greater than {}. Quotient is:{}".format(b,a,div)) 20 | 21 | except ValueError as e: 22 | #this except block is printed when user enters a string instead of integer 23 | print("This Occured:",e) 24 | except ZeroDivisionError as e: 25 | #this except block is printed when user inputs 0 to number 2, b 26 | print("This occured:",e) 27 | 28 | #example 2 29 | try: 30 | ceo = {"Google":"Sundar Pichai", 31 | "Microsoft":"Satya Nadella", 32 | "Adobe":"Shantanu Narayen", 33 | "Tesla":"Elon Musk", 34 | "Apple":"Tim Cook", 35 | "Facebook":"Mark Zuckerberg"} 36 | 37 | ceo['Amazon'] = "Andy Jassy" 38 | 39 | print(ceo["PayTM"]) 40 | print(ceo["Google"]) 41 | print(ceo["Tesla"]) 42 | print(ceo["Amazon"]) 43 | print(ceo["Apple"]) 44 | 45 | except KeyError as k: 46 | #this except block is executed when invalid key is entered 47 | print("This key is not found in the dictionary",k) 48 | except Exception as e: 49 | print("Something went wrong",e) 50 | 51 | #example 3 52 | 53 | try: 54 | with open("unknownfile.txt") as file: 55 | content = file.read() 56 | print(content) 57 | except FileNotFoundError: 58 | print("Oops! No File Found, Check Folder of the file and Try Again:)") 59 | -------------------------------------------------------------------------------- /mini_project_to_try/you_vs_kazuma_rock_paper_scissor.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def play(rock_paper_scissor): 4 | while True: 5 | player_choice=input('Enter Rock/Paper/Scissors: ').capitalize() 6 | if player_choice not in rock_paper_scissor: 7 | continue 8 | else: 9 | return player_choice 10 | 11 | def winner(player_choice,kazuma_choice,kazuma_score,player_score): 12 | if player_choice==kazuma_choice: 13 | print('Draw') #the winner is rewarded by 2 points but on draw both player and kazuma gets 1 point 14 | kazuma_score+=1 15 | player_score+=1 16 | print(f'Player Choice:{player_choice} || Kazuma Choice:{kazuma_choice}') 17 | print(f'Player score:{player_score} || Kazuma score:{kazuma_score}') 18 | elif (player_choice=='Rock' and kazuma_choice=='Paper') or (player_choice=='Paper' and kazuma_choice=='Scissor') or (player_choice=='Scissor' and kazuma_choice=='Rock'): 19 | print(f'Kazuma won') 20 | player_score+=0 21 | kazuma_score+=2 22 | print(f'Player Choice:{player_choice} || kazuma Choice:{kazuma_choice}') 23 | print(f'Player score:{player_score} || kazuma score:{kazuma_score}') 24 | elif (player_choice=='Rock' and kazuma_choice=='Scissor') or (player_choice=='Scissor' and kazuma_choice=='Paper') or (player_choice=='Paper' and kazuma_choice=='Rock'): 25 | print(f'Player won') 26 | player_score+=2 27 | kazuma_score+=0 28 | print(f'Player Choice:{player_choice} || kazuma Choice:{kazuma_choice}') 29 | print(f'Player score:{player_score} || kazuma score:{kazuma_score}') 30 | else: 31 | print('Invalid') 32 | 33 | def permission(): 34 | ask=input('Are you ready?(Y/n)').lower() 35 | if ask.startswith('y'): 36 | return True 37 | else: 38 | return False 39 | 40 | def play_again(): 41 | print('*'*30) 42 | again=input('Do you want to play again?(Y/n)').lower() 43 | print('*'*30) 44 | if again.startswith('y'): 45 | return True 46 | else: 47 | print('Thank You for playing') 48 | 49 | choice=['Rock','Paper','Scissor'] 50 | player=input('Enter Your Name:') 51 | ps=cs=0 52 | kazuma_choice=random.choice(choice) 53 | if permission(): 54 | player_choice=play(choice) 55 | winner(player_choice,kazuma_choice,cs,ps) 56 | while play_again(): 57 | kazuma_choice=random.choice(choice) 58 | player_choice=play(choice) 59 | winner(player_choice,kazuma_choice,cs,ps) 60 | else: 61 | print("Thank You for playing") -------------------------------------------------------------------------------- /Day9/library.py: -------------------------------------------------------------------------------- 1 | from typing import SupportsIndex 2 | import termcolor 3 | class Library: 4 | def __init__(self,book_category): 5 | self.books = book_category 6 | 7 | def intro(self): 8 | message = """\n\t****** Welcome To Anime Vyuh Library ******\n 1. List Of Books\n 2. Request A Book\n 3. Return A Book\n 4. Exit""" 9 | print(f"\t{message}") 10 | 11 | def listofbooks(self): 12 | print("\t *** Here Are The List Of Book *** ") 13 | for index,book in enumerate(self.books,start=1): 14 | print(f"{index}:{book}") 15 | 16 | def returnbook(self,bookname): 17 | if bookname not in self.books: 18 | self.books.append(bookname) 19 | termcolor.cprint("\nThank You For Returning Book Back",color="green") 20 | termcolor.cprint(f"{bookname} book is added",color="blue") 21 | else: 22 | termcolor.cprint("\nBook Exists",color="yellow") 23 | 24 | def requestbook(self,bookname): 25 | if bookname in self.books: 26 | self.books.remove(bookname) 27 | termcolor.cprint(f"\n{bookname} book is borrowed",color="blue") 28 | termcolor.cprint("Enjoy Your Read",color="green") 29 | else: 30 | termcolor.cprint("\nSorry We Don't Have Such Book",color="yellow") 31 | 32 | class Student: 33 | def __init__(self,id): 34 | self.usn = id 35 | 36 | def askuser(self): 37 | ask = int(input("\nEnter Your Choice:")) 38 | return ask 39 | 40 | def return_book(self): 41 | request_b = input("\nWhich book could you like to return?") 42 | return request_b 43 | 44 | def request_book(self): 45 | borrow = input("\nWhich book could you like to borrow?") 46 | return borrow 47 | 48 | if __name__ == '__main__': 49 | scan_id = input("Enter your id:") 50 | student = Student(scan_id) 51 | books = ['Automate Stuff With Python','EcmaJavascript','ProGit','Java Fundamentals','Arduino With C'] 52 | library_books = Library(books) 53 | while True: 54 | try: 55 | library_books.intro() 56 | choice = student.askuser() 57 | if choice in range(1,5): 58 | if choice == 1: 59 | library_books.listofbooks() 60 | elif choice == 2: 61 | library_books.requestbook(student.request_book()) 62 | elif choice == 3: 63 | library_books.returnbook(student.return_book()) 64 | elif choice == 4: 65 | print("\nThank you for visting! \nHappy Reading") 66 | exit() 67 | else: 68 | termcolor.cprint("Enter A Valid Choice between (1-4)",color="red") 69 | except ValueError: 70 | termcolor.cprint("Invalid Choice",color="red") -------------------------------------------------------------------------------- /mini_project_to_try/library.py: -------------------------------------------------------------------------------- 1 | from typing import SupportsIndex 2 | import termcolor 3 | class Library: 4 | def __init__(self,book_category): 5 | self.books = book_category 6 | 7 | def intro(self): 8 | message = """\n\t****** Welcome To Anime Vyuh Library ******\n 1. List Of Books\n 2. Request A Book\n 3. Return A Book\n 4. Exit""" 9 | print(f"\t{message}") 10 | 11 | def listofbooks(self): 12 | print("\t *** Here Are The List Of Book *** ") 13 | for index,book in enumerate(self.books,start=1): 14 | print(f"{index}:{book}") 15 | 16 | def returnbook(self,bookname): 17 | if bookname not in self.books: 18 | self.books.append(bookname) 19 | termcolor.cprint("\nThank You For Returning Book Back",color="green") 20 | termcolor.cprint(f"{bookname} book is added",color="blue") 21 | else: 22 | termcolor.cprint("\nBook Exists",color="yellow") 23 | 24 | def requestbook(self,bookname): 25 | if bookname in self.books: 26 | self.books.remove(bookname) 27 | termcolor.cprint(f"\n{bookname} book is borrowed",color="blue") 28 | termcolor.cprint("Enjoy Your Read",color="green") 29 | else: 30 | termcolor.cprint("\nSorry We Don't Have Such Book",color="yellow") 31 | 32 | class Student: 33 | def __init__(self,id): 34 | self.usn = id 35 | 36 | def askuser(self): 37 | ask = int(input("\nEnter Your Choice:")) 38 | return ask 39 | 40 | def return_book(self): 41 | request_b = input("\nWhich book could you like to return?") 42 | return request_b 43 | 44 | def request_book(self): 45 | borrow = input("\nWhich book could you like to borrow?") 46 | return borrow 47 | 48 | if __name__ == '__main__': 49 | scan_id = input("Enter your id:") 50 | student = Student(scan_id) 51 | books = ['Automate Stuff With Python','EcmaJavascript','ProGit','Java Fundamentals','Arduino With C'] 52 | library_books = Library(books) 53 | while True: 54 | try: 55 | library_books.intro() 56 | choice = student.askuser() 57 | if choice in range(1,5): 58 | if choice == 1: 59 | library_books.listofbooks() 60 | elif choice == 2: 61 | library_books.requestbook(student.request_book()) 62 | elif choice == 3: 63 | library_books.returnbook(student.return_book()) 64 | elif choice == 4: 65 | print("\nThank you for visting! \nHappy Reading") 66 | exit() 67 | else: 68 | termcolor.cprint("Enter A Valid Choice between (1-4)",color="red") 69 | except ValueError: 70 | termcolor.cprint("Invalid Choice",color="red") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 30DaysOfPython 2 | 3 | 4 | Learn Python With Anime Vyuh In Easy Way. Tutorials available in detail in our Blog pag: [Anime Vyuh Blog: A Fusion Of Coding And Anime](https://animevyuh.org/blog) 5 | 6 | 7 | ```py 8 | try: 9 | print("Share Anime Vyuh Blogs to your friends") 10 | print("Watch Anime and enjoy") 11 | print("Coding is Fun") 12 | except ShareError: 13 | print("Seems like you haven't shared Anime Vyuh blog post") 14 | except AnimeError: 15 | print("Watch Anime and become a weeb") 16 | finally: 17 | print("Do you like my content?support by Buying me a coffee") 18 | ``` 19 | 20 | ## Python Tutorial Series 21 | 22 | Each day complete the assigned by programs with tutorial avaiable on [Anime Vyuh Website](https://animevyuh.org) 23 | 24 | - `Part 1`: [Variable, Data Types, User Input](https://animevyuh.org/learn-python) 25 | - `Part 2`: [Conditions](https://animevyuh.org/learn-python-part2/) 26 | - `Extra`: [Import In Python](https://animevyuh.org/import-in-python/) 27 | - `Part 3`: [Functions](https://animevyuh.org/learn-python-part3/) 28 | - `Part 4`: Data Structures 29 | - `4a`: [Strings](https://animevyuh.org/learn-python-strings/) 30 | - `4b`: [Lists](https://animevyuh.org/learn-python-lists/) 31 | - `4c`: [Tuples](https://animevyuh.org/tuples-in-python/) 32 | - `4d`: [Dictionary](https://animevyuh.org/dictionary-in-python/) 33 | - `4e`: [Sets](https://animevyuh.org/sets-in-python/) 34 | - `Part 5`: [File Handling](https://animevyuh.org/files-in-python/) 35 | - `Extra 2`: [Error Handling](https://animevyuh.org/error-handing-in-python/) 36 | 37 | Extra: Intermediate Python Concepts: coming soon, 38 | ### 📧 Stay tuned by subscribing to [Anime Vyuh Newsletter](https://animevyuh.org/newsletter/) 📧 39 | 40 | #### Complete [Anime Vyuh Python Series](https://animevyuh.org/category/python-tutorials) 41 | 42 | ## Contribute 43 | 44 | You can contribute to see this repo, follow the below steps to contribute 45 | 46 | - `clone` the project and open your terminal and type the below command 47 | - `git clone [project-url]` 48 | - Create a new branch and work on it, `don't make the changes on master branch` 49 | - `git checkout -b [your_branch_name]` 50 | [Now your in new branch, check git branch, it will show the branch name you created] 51 | - Contibute and add your code 52 | - Add the changes made in modified file 53 | - `git add .` 54 | - Commit your changes with a good message 55 | - `git commit -m "about code changes"` 56 | - Push your changes to remote 57 | - `git push --set-upstream origin your_branch_name` 58 | - Don't push the `master` branch 59 | - Open GitHub and Make a `Pull Request` 60 | 61 | ## Support 62 | 63 | Donate: 64 | - [Buy Me A Coffee](https://www.buymeacoffee.com/trjtarun) 65 | - [Ko-Fi](https://ko-fi.com/tarunrjain751) 66 | 67 | ### Author 68 | 69 | - Twitter: [Tarun Jain](https://twitter.com/TRJ_0751) 70 | - Linkedin: [Tarun Jain](https://www.linkedin.com/in/jaintarun75/) 71 | -------------------------------------------------------------------------------- /Day10/types_of_errors.md: -------------------------------------------------------------------------------- 1 | We can check for exception using Try and Except method. But before that in the beginning of the book I had said that I will explain SyntaxError and other Errors in detail, Here are the major Error which we encounter very often: 2 | 1. SyntaxError 3 | 2. NameError 4 | 3. ValueError 5 | 4. TypeError 6 | 5. IndexError 7 | 8 | ### 1. SyntaxError 9 | 10 | You get syntax SyntaxError when you don’t follow rules and regulations provided by 11 | Python. Major exampled missing of parenthesis, missing of clone, Invalid naming of 12 | variable, Spelling mistake for the keywords and many more. 13 | 14 | Examples of SyntaxError: 15 | 16 | ```py 17 | >>> 10 = 32 18 | SyntaxError: cannot assign to literal 19 | >>> print "Very good" 20 | SyntaxError: Missing parentheses in call to 'print'. 21 | >>>if (a>b) #missing colon 22 | File "", line 1 23 | if (a>b) 24 | ^ 25 | SyntaxError: invalid syntax 26 | >>> ife(20>10): 27 | SyntaxError: invalid syntax 28 | ``` 29 | 30 | ### 2. NameError 31 | 32 | You get NameError when you try to use a variable or a function name that is not 33 | valid. This means that if Python encounters a name that it doesn’t recognize, you’ll 34 | probably get this error. Some common causes are: Misspelling the name of a build-in function, Forgetting to give a value to a variable before using it in a different 35 | statement. 36 | 37 | Examples of NameError: 38 | 39 | ```py 40 | >>>x+=1 41 | NameError: name 'x' is not defined 42 | >>>name=(manhwa) 43 | NameError: name 'manhwa' is not defined 44 | >>>print(hello) 45 | NameError: name 'hello' is not defined 46 | >>> prin("Python is easy to learn") 47 | NameError: name 'prin' is not defined 48 | ``` 49 | 50 | ### 3. Value Error 51 | 52 | You get ValueError when a value is not the expected type. 53 | 54 | Examples of ValueError: 55 | 56 | ```py 57 | >>> x=int("Can you write a Python Program") 58 | ValueError: invalid literal for int() with base 10: 'what about this statement' 59 | >>> z=[1,3,5,7,9] 60 | >>> x,y = z 61 | >>> print(x) 62 | >>> print(y) 63 | ValueError: too many values to unpack (expected 2) 64 | >>>points=float(“int”) 65 | ValueError: could not convert string to float: 'int' 66 | ``` 67 | 68 | ### 4. Type Error 69 | 70 | You get TypeError when an operation is performed on an inappropriate object type. 71 | 72 | Examples of TypeError: 73 | 74 | ```py 75 | >>>a=input(‘Enter a number:’) 76 | >>>b=a+10 77 | … print(“10 more is {}”.format(y)) 78 | TypeError: can only concatenate str (not "int") to str 79 | >>>x=5 80 | >>>y=”123” 81 | … print(x+y)TypeError: unsupported operand type(s) for +: 'int' and 'str' 82 | ``` 83 | 84 | ### 5. Index Error 85 | 86 | You get IndexError when your code try to access an Index value that is not valid. This 87 | usually happen because the index out of bonds due to being too large. 88 | 89 | Examples of IndexError: 90 | 91 | ```py 92 | >>>s=[1,2,4,6,8} 93 | >>>print(s[5]) 94 | IndexError: list index out of range 95 | >>>name=[“Itachi”, “Naruto”, “Madara”, “Sasuke”, “Luffy”] 96 | >>>name.pop(6) 97 | … print(name) 98 | IndexError: pop index out of range 99 | ``` -------------------------------------------------------------------------------- /Day2/day2_programs: -------------------------------------------------------------------------------- 1 | #Program 1: Factorial 2 | 3 | Find factorial of any number given 4 | Factorial of number is calculated by multiplying n*(n-1) 5 | Sample Input:4 6 | Factorial: 4*3*2*1 7 | Output: 24 8 | Sample input:6 9 | Factorial: 6*5*4*3*2*1 10 | Output:720 11 | 12 | Method 1 using For loop 13 | 14 | f=1 15 | n = int(input('Sample input:')) 16 | for i in range(1,n+1): 17 | f=f*i 18 | print(f) 19 | 20 | Method 2 using while loop 21 | 22 | f=1 23 | n = int(input(‘Sample input:’)) 24 | while(n>0): 25 | f=f*n 26 | n=n-1 27 | print(f) 28 | 29 | #Program 2: Guess a Number 30 | 31 | Ask a user to guess a number between 1 to 50. He gets only 5 chance to guess. Give user a feedback if his guess is high or low. 32 | 33 | import random 34 | 35 | num=random.randint(1,50) 36 | print("Guess a Number from 1-50 \n You have only 5 chance\n") 37 | chances=0 38 | while chances<5: #you only get 5 chances to guess 39 | guess=int(input('Take a guess:')) 40 | if guessnum: 44 | print('Your guess is too high') 45 | chances+=1 46 | if guess==num: 47 | chances+=1 48 | break 49 | else: 50 | print("You ran out of chances") 51 | if guess==num: 52 | print('Nicely Done! You guessed the number in ',chances,' guesses') 53 | 54 | #Program 3: FizzBuzz 55 | 56 | Consider ‘n’ numbers, print all the numbers from 1 to n and replace some number according to this criteria: 57 | • If the number is divisible by 3, write Fizz instead of the number 58 | • If the number is divisible by 5, write Buzz instead of the number 59 | • If the number is divisible by 3 and 5 both, write FizzBuzz instead of the number 60 | [Constraints n should be more than 1 and less than 100; i.e., 1<=n<100] 61 | 62 | while True: 63 | n = int(input("Enter a number(1-100):")) 64 | if n>=1 and n<=100: 65 | for i in range(1,n+1): 66 | if i%3 == 0 and i%5==0: 67 | print("FizzBuzz") 68 | elif i%3==0: 69 | print("Fizz") 70 | elif i%5==0: 71 | print("Buzz") 72 | else: 73 | print(i) 74 | break 75 | else: 76 | continue 77 | 78 | #Program 4: Neon Number 79 | 80 | Enter a number and check whether the number is neon number or not 81 | Sample input: 9 82 | Sample output: Yes it is a neon number 83 | Sample input: 6 84 | Sample output: No it is not a neon number 85 | 86 | ***[Neon number explanation: input=9 87 | Step one: 9*9 =81 88 | Step two: 81 = 8+1 = 9 89 | Step three: 9 == sample input 90 | Yes it is a neon number]*** 91 | 92 | n = int(input("Sample input:")) 93 | first_step=n*n 94 | sum=0 95 | while(first_step>0): 96 | second_step=first_step%10 97 | sum+=second_step 98 | first_step=first_step//10 99 | if(sum==n): 100 | print('The given number',n,'is neon number') 101 | else: 102 | print('The given number',n,'is not neon number') 103 | -------------------------------------------------------------------------------- /Day1/day1_program_assignment.md: -------------------------------------------------------------------------------- 1 | For Tutorials: [Check Anime Vyuh](https://animevyuh.org/category/python-tutorials 2 | 3 | ### Program 1: 4 | 5 | Write a Program to swap data between two variables 6 | 7 | Open your Interactive shell or text editor or IDE anything you are comfortable with it 8 | 9 | Method 1 to swap with temp 10 | 11 | ```py 12 | main_character = "Light yagami" 13 | loved_character = "L Lawleit" 14 | print(‘Before Swap:’) 15 | print(‘Main Character:’,main_character) #light is output 16 | print(‘Side Character:’,loved_character) #l is output 17 | temp = main_character #create a temporary variable to store main variable in it 18 | main_character = loved_character #loved_character name Is successfully swaped to main 19 | loved_character = temp #temp which had main in it is swaped to loved 20 | print(‘After Swap:’) 21 | print(‘Main Character:’,main_character) #l is output 22 | print(‘Side Character:’,loved_character) #light is output 23 | ``` 24 | 25 | Results are swapped, run the program to see changes. 26 | 27 | Method 2 to swap without temp 28 | 29 | ```py 30 | main_character = "Light yagami" 31 | loved_character = "L Lawleit" 32 | print(‘Before Swap:’) 33 | print(‘Main Character:’,main_character) #light is output 34 | print(‘Side Character:’,loved_character) #l is output 35 | main_character,loved_character = loved_character,main_character #swap successful 36 | print(‘After Swap:’) 37 | print(‘Main Character:’,main_character) #l is output 38 | print(‘Side Character:’,loved_character) #light is output 39 | ``` 40 | 41 | ### Program 2: 42 | 43 | Write a Program to convert Dollar to Rupee and add 50 rupee as tip 44 | 45 | ```py 46 | dollar = 56.76 47 | dollar_to_INR = 77.76 48 | rupee = dollar * dollar_to_INR 49 | final_amt = rupee + 50.00 50 | print(final_amt) 51 | ``` 52 | 53 | ### Program 3: 54 | 55 | You are the owner of restaurant greet your customer with specific inputs 56 | [user input includes name and dish he could like to eat] 57 | 58 | ```py 59 | name = input("Enter Customer Name:") 60 | dish = input("What could you like to it? ") 61 | print("Welcome to Anime Foods "+name) #you can also use comma, instead of + 62 | print("We could love to serve "+dish) 63 | print("Thank you for coming") 64 | ``` 65 | 66 | ### Program 4 67 | 68 | Take two input numbers and perform addition, subtraction, multiplication and division 69 | 70 | ```py 71 | num1 = int(input("Enter num1: ")) #ask for integer input 72 | num2 = int(input("Enter num2: ")) 73 | add = num1+num2 74 | sub = num1-num2 75 | mul = num1*num2 76 | divide = num1/num2 77 | print("Sum =",add) 78 | print("Difference =",sub) 79 | print("Multiply =",mul) 80 | print("Division =",divide) 81 | ``` 82 | 83 | ### Program 5 84 | 85 | Write a program for a conversation between two people. [USE: input()] 86 | 87 | ```py 88 | person1 = input("Enter Person1 name:") 89 | person2 = input("Enter Person2 name:") 90 | print(person2,":Hello",person1) 91 | print(person1,":Nice to meet you",person2) 92 | print(person2,":Can I know your age?") 93 | age_person1 = int(input()) 94 | age_person2 = int(input()) 95 | print(person1,":I am",age_person1,"years old, May I know your age?") 96 | print(person2,":I am",age_person2) 97 | ``` 98 | 99 | Check [Anime Vyuh](https://animevyuh.org/) For more 100 | Follow on [Twitter](https://twitter.com/TRJ_0751) 101 | -------------------------------------------------------------------------------- /mini_project_to_try/high_low_game/bungou_simple_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | 4 | def game_rules(): 5 | rules = """ 6 | Rules: A simple 2 player game [Bungou Stray Dogs Season 3 Episode 4] 7 | 1. Inially open one card, i.e., display one card from shuffled deck 8 | 2. Now player1 takes a card from the deck 9 | 3. Now it begins, the other player:[player2] should guess if the taken card is higher or lower from than the previous card 10 | **[ say the first card is 9, now one player should guess if the next card is high or low 11 | i.e., if 1-8 appears it is low, 10-12 and A appears then it is high 12 | now player1 reveals the next card, say it is 10. 13 | Now 10 is the previous card, now guess high or low based on number 10. 14 | ]** 15 | 4. If the player2 guessed correctly then player1 is again suppose to take another card 16 | 5. Now when player2 guessed correctly, that drawn card is added in player1 penalty. 17 | 6. If the player2 guess is wrong, then player2 will take the card and player1 will guess 18 | 7. Since player2 guessed wrong, that card will be counted as player2 penalty. 19 | 8. The game continues till all 51 cards are revealed [1 card will be opened in beginning so 51] 20 | 9. At end who as more penalty cards loses, and player with less penalty cards win. 21 | *********** 22 | 10. Penalty card calculation: 23 | if player1 guessed wrong, player1 gets penalty, now player2 have to guess 24 | if player1 guessed correctly, player2 gets penalty, since guess is correct player1 itself should guess again 25 | *********** 26 | """ 27 | return rules 28 | 29 | def deck_52_cards(): 30 | deck = list() 31 | deck.clear() 32 | suits = ['H','S','D','C'] #Hearts, Spades, Diamond, Club 33 | for suit in suits: 34 | for card in range(1,14): 35 | deck.append(suit+str(card)) 36 | random.shuffle(deck) 37 | return deck 38 | 39 | def winner(guess_cards,p1_name,p2_name): 40 | base=first_card = random.choice(guess_cards) 41 | print("First Card:",first_card) 42 | guess_cards.remove(first_card) 43 | player1_penalty_scores,player2_penalty_scores = 0,0 44 | turn = p2_name 45 | no_turn = p1_name 46 | 47 | while True: 48 | if len(guess_cards)==0: 49 | print("\n\t Match Over \n") 50 | break 51 | 52 | guess=input("{} guess High or Low:".format(turn)).lower() 53 | if guess not in ['high','low']: 54 | continue 55 | 56 | next_card = random.choice(guess_cards) 57 | guess_cards.remove(next_card) 58 | print("Previous card:",base) 59 | print("New Card:",next_card) 60 | 61 | correct = "low" if(int(base[1:])>int(next_card[1:])) else "high" #correct is low for True if condition else correct=High 62 | if guess==correct: 63 | print("{} Correct {}".format('*'*10,'*'*10)) 64 | if turn==p1_name: 65 | player2_penalty_scores+=1 66 | else: 67 | player1_penalty_scores+=1 68 | else: 69 | print("{} Wrong, Next {}".format('*'*10,'*'*10)) 70 | if turn==p2_name: 71 | turn=p1_name 72 | player2_penalty_scores+=1 73 | else: 74 | turn=p2_name 75 | player1_penalty_scores+=1 76 | 77 | base=next_card 78 | 79 | return(p1_name if(player2_penalty_scores>player1_penalty_scores) else p2_name) 80 | 81 | def play_again(): 82 | ask = input("Do you want to play again(Y/n)? ").lower() 83 | if ask.startswith('y'): 84 | main() 85 | return True 86 | print("Thank You ") 87 | 88 | def main(): 89 | #guess high or low 90 | game_details = input("Do you want to see the rules(Y/n)? ").lower() 91 | if game_details.startswith('y'): 92 | print(game_rules()) 93 | time.sleep(15) 94 | print("Game will start in 5 seconds .....") 95 | time.sleep(5) 96 | 97 | print("\n\n\t Let the Game Begin \n\n") 98 | cards = deck_52_cards() 99 | player1 = input("Player 1 enter your name: ") 100 | player2 = input("Player 2 enter your name: ") 101 | winner_of_the_game = winner(cards,player1,player2) 102 | print("Winner is",winner_of_the_game) 103 | play_again() 104 | 105 | if __name__ == '__main__': 106 | main() -------------------------------------------------------------------------------- /mini_project_to_try/hangman.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | hangman_body = [''' 5 | ------ 6 | | 7 | | 8 | | 9 | | 10 | ========''',''' 11 | ------ 12 | | | 13 | | 14 | | 15 | | 16 | ========''' ,''' 17 | ------ 18 | | | 19 | o | 20 | | 21 | | 22 | ========''',''' 23 | ------ 24 | | | 25 | o | 26 | | | 27 | | 28 | ========''',''' 29 | ------ 30 | | | 31 | o | 32 | /| | 33 | | 34 | ========''',''' 35 | ------ 36 | | | 37 | o | 38 | /|\ | 39 | | 40 | ========''',''' 41 | ------ 42 | | | 43 | o | 44 | /|\ | 45 | / | 46 | ========''',''' 47 | ------ 48 | | | 49 | o | 50 | /|\ | 51 | / \ | 52 | ========''', 53 | ] 54 | def displayhangman(wrong_guess,correct_guess,anime_character,hangman_body): 55 | if len(wrong_guess)<8: 56 | print(hangman_body[len(wrong_guess)]) 57 | 58 | print('Wrong guesses:',end='') 59 | for wrong in wrong_guess: 60 | print(wrong,end='') 61 | print('') 62 | 63 | blanks = "_" * len(anime_character) 64 | 65 | for i in range(len(anime_character)): 66 | if anime_character[i] in correct_guess: 67 | blanks = blanks[:i] + anime_character[i] + blanks[i+1:] 68 | 69 | for letters in blanks: 70 | print(letters,end='') 71 | print('') 72 | 73 | def guessTaken(alreadyexist): 74 | while True: 75 | guess = input('\n Start guessing:').lower() 76 | if guess not in string.ascii_lowercase: 77 | guess = input('Enter valid guess:') 78 | if not len(guess)== 1: 79 | guess=input('Enter a single character:') 80 | if guess==alreadyexist: 81 | guess=input('Guess again,guess already exist:') 82 | else: 83 | return guess 84 | 85 | def playagain(): 86 | again = input('Do you want to play again(Y/n)?').lower() 87 | if again.startswith('y'): 88 | return True 89 | else: 90 | return False 91 | 92 | print('Anime Hangman') 93 | characters="jabamiyumeko,ishigamisenku,satomemary,darkness,nifuji,narumi,koyanagi,kabakura,megumin,sabo,sukuna,gojo,yuji" \ 94 | "sakatagintoki,shinpachi,kagura,hijikata,makisekurisu,light,l,karma,kageyama," \ 95 | "kazuma,okabe,hachiman,yukino,yui,orekihotaru,chitandaeru,narutouzumaki," \ 96 | "monkeydLuffy,Lelouch,tatsumi,esdeath,akame,arima,kaori,fujinuma,kakeru,naho," \ 97 | "suwa,ichigokurosaki,uryuishida,giyuutomika,kenkaneki,saiki,zerotwo,hiro,chizuru,shuohuma,jintan,menma,norman," \ 98 | "ray,emma,sakakibara,akira,maisakurajima,sakuta,Ayanokouji,suzune,roronoazoro," \ 99 | "vinsmokesanji,boahancock,hinatahyuga,sasukeuchiha,CC,tenma,johan,,suzakukururugi," \ 100 | "karen,shikamarunara,kakashihatake,itachi uchiha,tanjiro,zenitsu,deku" \ 101 | "inosuke,portazdace,jiraiya,minato,god yato,hiyori,yukine,leviackerman,erenyeager," \ 102 | "mikasaackerman,erwinsmith,edwardelric,alphonseelric,roymustang,kenma,oikawa,bokuto,erza" \ 103 | "rayleigh,shanks,trafalgarlaw,killua,gon,hisoka,komi,ginko,natsu,goku,vegeta".lower().split(',') 104 | 105 | wrong_guess = '' 106 | correct_guess = '' 107 | anime_character = random.choice(characters) 108 | finish=False 109 | streaks=0 110 | 111 | while True: 112 | displayhangman(wrong_guess, correct_guess,anime_character,hangman_body) 113 | guess=guessTaken(wrong_guess+correct_guess) 114 | if guess in anime_character: 115 | correct_guess = correct_guess + guess 116 | complete = True 117 | for i in range(len(anime_character)): 118 | if anime_character[i] not in correct_guess: 119 | complete = False 120 | break 121 | if complete: 122 | streaks=streaks+1 123 | print(f'The Anime character is {anime_character}, You guessed it right') 124 | print('Winning Streaks:',streaks) 125 | finish = True 126 | else: 127 | wrong_guess = wrong_guess + guess 128 | if len(wrong_guess) == len(hangman_body) - 1: 129 | displayhangman(hangman_body, wrong_guess, correct_guess,anime_character) 130 | print(f'Oops!!...You are out of guesses, the anime character was {anime_character}') 131 | streaks=0 132 | finish = True 133 | 134 | if finish: 135 | if playagain(): 136 | wrong_guess = '' 137 | correct_guess = '' 138 | finish = False 139 | anime_character = random.choice(characters) 140 | else: 141 | print("Thank you playing") 142 | break -------------------------------------------------------------------------------- /Day10/exception_handling.md: -------------------------------------------------------------------------------- 1 | # Try and Except 2 | 3 | We know of errors now. Suppose you want your program to run error free, well of course everyone wants that. But you need your program to run even if there is error, is there any possibility? Yes There is. Python provides `Try and except`, using this you can show user the message when certain error is occurred, so user get the feedback where he went wrong. Giving feedback for your program is every 4 | important. I hope even I do get some feedback about this repo, I will be waiting for your feedback. Back to `Try and Except` again, here you will require the knowledge of Error, that’s the reason why we covered about Error before starting it. 5 | 6 | ```py 7 | manga = "Vagabond" 8 | try: 9 | print(manhwa) 10 | except: 11 | print("Name Error occurred") 12 | 13 | Name Error occurred 14 | 15 | try: 16 | print(manhwa) 17 | except NameError as error: 18 | print("This is what happened:",error) 19 | ``` 20 | 21 | This is what happened: name `manhwa` is not defined. Now, suppose you have declared a variable of name x and print y, you will get into `NameError`. What try and except does here is, you will execute your code inside try block and if in case you run into some error 22 | 23 | ```py 24 | try: 25 | print(manga) 26 | except: 27 | print("This is what happened:",error) 28 | 29 | Vagabond 30 | ``` 31 | 32 | ```py 33 | number = 100 34 | episode = 24 35 | try: 36 | print(episode-4) 37 | print(episode/0) 38 | except ZeroDivisionError as error: 39 | print("This happened:",error) 40 | Output: 41 | 20 42 | This happened: division by zero 43 | ``` 44 | 45 | We have added error name `ZeroDivisionError` in except block, if you don’t know what error you are dealing with then you can mention except Exception as e and 46 | deal with the problem. 47 | 48 | ## Finally 49 | 50 | Finally is a add-on option that comes handy with try and except. 51 | 52 | ```py 53 | try: 54 | print(episode/0) 55 | except ZeroDivisionError as error: 56 | print("This happened:",error) 57 | finally: 58 | print("We have reached the end of code") 59 | 60 | Output: 61 | This happened: division by zero 62 | We have reached the end of code 63 | 64 | try: 65 | pass 66 | except: 67 | print("Somethings not Good") 68 | finally: 69 | print("I will be executed no matter what") 70 | 71 | Output: 72 | I will be executed no matter what 73 | ``` 74 | 75 | Lets look at some programs where we can put `try and except` in amazing use. 76 | 77 | ```py 78 | try: 79 | a = int(input("Enter a number: ")) #integer inputs required 80 | b = int(input("Enter a number2: ")) 81 | div = a/b 82 | if a>b: 83 | print("{} is greater than {}. Quotient is:{}".format(a,b,div)) 84 | else: 85 | print("{} is greater than {}. Quotient is:{}".format(b,a,div)) 86 | except ValueError as e: 87 | print("This Occured:",e) 88 | except ZeroDivisionError as e: 89 | print("This occured:",e) 90 | 91 | Output for different input cases: 92 | Enter a number: 10 93 | Enter a number2: 5 94 | 10 is greater than 5. Quotient is:2.0 95 | Enter a number: 5 96 | Enter a number2: 10 97 | 10 is greater than 5. Quotient is:0.5 98 | Enter a number: p 99 | This Occured: invalid literal for int() with base 10: 'p' 100 | Enter a number: 10 101 | Enter a number2: 0This occured: division by zero 102 | Enter a number: 0 103 | Enter a number2: p 104 | This Occured: invalid literal for int() with base 10: 'p' 105 | ``` 106 | 107 | Example 2, 108 | 109 | In Dictionary we had taken the example of CEO, lets consider that example again but with try and except method. 110 | 111 | ```py 112 | ceo = { 113 | "Google":"Sundar Pichai", "Microsoft":"Satya Nadella", 114 | "Adobe":"Shantanu Narayen","Tesla":"Elon Musk", 115 | "Apple":"Tim Cook","Facebook":"Mark Zuckerberg"} 116 | print(ceo["Google"]) 117 | print(ceo["Tesla"]) 118 | print(ceo["Amazon"]) 119 | print(ceo["Apple"]) 120 | 121 | Output: 122 | Sundar Pichai 123 | Elon Musk 124 | KeyError: 'Amazon' 125 | ``` 126 | 127 | We get a `KeyError` because we haven’t declared Amazon name yet. Now add a new 128 | key entry for Amazon and also add `Try and Except` method so that user gets the feedback on what he should do if he gets into some error. 129 | 130 | ```py 131 | try: 132 | ceo = {"Google":"Sundar Pichai", 133 | "Microsoft":"Satya Nadella", 134 | "Adobe":"Shantanu Narayen", 135 | "Tesla":"Elon Musk", 136 | "Apple":"Tim Cook", 137 | "Facebook":"Mark Zuckerberg"} 138 | ceo['Amazon'] = "Andy Jassy" 139 | print(ceo["PayTM"])print(ceo["Google"]) 140 | print(ceo["Tesla"]) 141 | print(ceo["Amazon"]) 142 | print(ceo["Apple"]) 143 | except KeyError as k: 144 | print("This key is not found in the dictionary",k) 145 | except Exception as e: 146 | print("Something went wrong",e) 147 | Output: 148 | This key is not found in the dictionary 'PayTM' 149 | ``` 150 | 151 | `Try and except` is the best way to deal with error. And with this you can generate your own message every time you run into error, this enables you to understand the code in better way. 152 | 153 | ## How To Deal With FileNotFoundError? 154 | 155 | We discussed about `FileNotFoundError` while discussing [files]( https://animevyuh.org/files-in-python/), and we will deal with it using `Exception Handling`. This is no big task to you, isn’t? You are supposed to follow the same steps we followed in rest of the Exception handling programs. 156 | 157 | ```py 158 | try: 159 | with open("unknownfile.txt") as file: 160 | content = file.read() 161 | print(content) 162 | except FileNotFoundError: 163 | print("Oops! No File Found, Check Folder of the file and Try Again:)") 164 | Output: 165 | Oops! No File Found, Check Folder of the file and Try Again:) 166 | ``` 167 | 168 | We have a good error message for displaying File not Found. 169 | 170 | ### Raise Exception 171 | 172 | So far in try and except, whenever we encountered an error a normal message was 173 | executed. But what if you need to generate an error in addition with a meaning 174 | message. `raise` keyword does that job by returning an error with the message we 175 | provide in except block. 176 | 177 | ```py 178 | try: 179 | a = int(input("Enter the a value:")) 180 | b = int(input('Enter the b value:')) 181 | result = a/b 182 | print(result) 183 | except ValueError: 184 | #first method to raise an exception by mentioning error name in except : 185 | raise "Enter a valid number" 186 | except: 187 | #second method to raise an exception without mentioning name in except: 188 | raise ZeroDivisionError("Enter non zero number for b") 189 | 190 | Output: 191 | Enter the a value:a 192 | Traceback (most recent call last): 193 | File "/home/pythonbook/s.py", line 2, in 194 | a = int(input("Enter the a value:")) 195 | ValueError: invalid literal for int() with base 10: 'a' 196 | During handling of the above exception, another exception occurred: 197 | Traceback (most recent call last): 198 | File "/home/pythonbook/s.py", line 7, in 199 | raise "Enter a valid number" 200 | TypeError: exceptions must derive from BaseException 201 | 202 | Enter the a value:2 203 | Enter the b value:0 204 | Traceback (most recent call last): 205 | File "/home/pythonbook/s.py", line 11, in 206 | raise ZeroDivisionError("Enter non zero number for b") 207 | ZeroDivisionError: Enter non zero number for b 208 | ``` 209 | --------------------------------------------------------------------------------