Posts

Showing posts from May, 2022

List comprehension in Python

List comprehensions in Python are a powerful and concise way to create new lists based on existing iterables (like lists, tuples, strings, etc.). They offer a more compact alternative to traditional for loops with append. Syntax: new_list = [ expression for item in iterable [if condition ]] expression:  This is what you want to do with each item in the iterable. It can be a simple variable representing the item, a calculation, a function call, or anything that evaluates to a value. item:  This represents the variable that takes on the value of each item in the iterable as you loop through it. Think of it as a temporary variable for each iteration. iterable:  This is the data source you're iterating over, like a list, tuple, string, or any object that can return its elements one at a time. condition (optional):  This is an optional  if  clause that acts as a filter. Only items that meet the condition will be included in the new list. Here are some examples to illustrate differen

Enumerate function in Python

  mlist = [ "abdur" , "banana" , "dog" , "gem" , "carbon" , "eyes" , "moon" ] index = 0 for item in mlist :     print ( index , item )     index += 1 # printing of item names along with indices can # be done with the enumerate function as below; for index , item in enumerate ( mlist ):     print ( index , item ) Also; another example l1 = [ "tomato" , "potato" , "laddoo" , "wresha" , "chawal" , "siwian" ] # return indexed list through ordinary method i = 1 for item in l1 :     print ( f " { i } . { item } " )     i += 1 # return indexed list through enumerate method for index , item in enumerate ( l1 , start = 1 ):     print ( f " { index } . { item } " )

You vs. Computer Guess Game (with error handling and Save-into-file high score capability)

Image
Error handling syntax try: except: import random rNum = random . randint ( 1 , 100 ) guesses = 0 while True :     try :         gn = int ( input ( "We have chosen a number between 1 and 100. Guess what? " ))         guesses += 1         if gn < rNum :                 print ( "Hint: Choose a higer number" )         if gn > rNum :                 print ( "Hint: Choose a lower number" )         if gn == rNum :                 print ( f "You guessed it right. Your number was { gn } " )                 print ( f "Our chosen number was { rNum } " )                 print ( f "You geussed it right in { guesses } guesses" )                 break     except :         print ( "invalid input. Plz enter only whole numbers!" ) with open ( "hi-score2.txt" , "r" ) as f :         hiscore = int ( f . read ()) if guesses < hiscore :     with open ( "hi-score2.txt" , "w"

Guessing Game - Between You and Computer

 Guess the number?  import random rNum = random . randint ( 1 , 100 ) while True :     gn = int ( input ( "We have chosen a number between 1 and 100. Guess what? " ))     if gn < rNum :         print ( "Choose higer number" )     if gn > rNum :         print ( "Choose lower number" )     if gn == rNum :         print ( f "You guessed it right. Your number was { gn } " )         print ( f "Our chosen number was { rNum } " )         break

Multi-level Inheritance in python

  class Animals :     animalCategory1 = "vertebrates"     animalCategory2 = "invertibrates" class Pets ( Animals ):     petCategory1 = "cats"     petCategory2 = "dogs" class Dog ( Pets ):     @ staticmethod     def bark ():                 print ( "The dog barks" ) a = Animals () b = Pets () c = Dog () print ( a . animalCategory2 ) print ( b . animalCategory2 ) print ( c . animalCategory2 ) print ( b . petCategory2 ) print ( c . petCategory2 ) a . animalCategory1 = "mammals" print ( a . animalCategory1 )

Creating a Class of Job Application form in Python

  class JobApplication :     def __init__ ( self , name , phone , address , experience , appliedPosition ):         self . name1 = name         self . phone1 = phone         self . address1 = address         self . experience1 = experience         self . appliedPosition1 = appliedPosition     def name ( self ):         print ( f "The name of the job applicant is { self . name1 } " )     def phone ( self ):         print ( f "The phone number of the job applicant is { self . phone1 } " )     def address ( self ):         print ( f "The residential address of the job applicant is { self . address1 } " )     def experience ( self ):         print ( f "The relevant experience of the job applicant is { self . experience1 } " )     def appliedPosition ( self ):         print ( f "The job applicant applied for the post of { self . appliedPosition1 } " ) abdur = JobApplication ( "Abdur" , "03369085972" , "P

A program that calculates the square, cube and square root of a given number

  💓 💓 💓 💓 Hello, dear ones! The following code can be used to calculate the square, cube and square root of a given number. class Calculator :         def __init__ ( self , num ):         self . num = num     def square ( self ):         print ( f "The square of { self . num } is { self . num ** 2 } " )         def cube ( self ):         print ( f "The cube of { self . num } is { self . num ** 3 } " )         def sqrt ( self ):         print ( f "The sqrt of { self . num } is { self . num ** 0.5 } " ) calc = Calculator ( 6 ) calc . square () calc . cube () calc . sqrt () Note: The above program will return the square, cube, and square root of a given number because all the following three functions are being called, i.e. calc.square() calc.cube() calc.sqrt() *If you want to find the square of a given number only, put the given number in the Calculator class and call the respective function. In this case it is; calc.square() *If you want to f

Automate Sending of WhatsApp messages with Python

 All you need to do: Open the terminal of your favourite IDE and write in it; pip install pywhatkit After pywhatkit is installed, open a python file and enter the following two lines of code and you are good to go. import pywhatkit pywhatkit.sendwhatmsg("mobile number", "message", hr, min) Note: The time placeholder takes time in 24-hour format. That's all!

Writing a multiline string in Python by using backslash

Image
\ \ Hi, dear ones! 💗💗💗💗💗 Just use a backslash (\) in your multiline string where you want to carry your text to the next line.  f = "Hi XXXXXXXXXXX is AR from planet Earth. XXXXXXXXXXX \ thing that is very weird about the humans is that \ XXXXXXXXXXX make a 'gaali' out of lower XXXXXXXXXXX \ which they use for each other when they are angry. \ One such word is XXXXXXXXXXX. They will call one another \ by the name of XXXXXXXXXXX Saying that you are a \ XXXXXXXXXXX XXXXXXXXXXX you are a son of a XXXXXXXXXXX \ which is delaware bad as far as human behaviour is \ XXXXXXXXXXX. This should not be so btw." print ( f ) 💪💪💪💗💗💗👍👍👍

Finding out if the given two files are identical in Python

Image
✋✋✋💓💓 Following is the code you can use in python to find out if the given two files are identical to each other or not. file1 = "file name 1" file2 = "file name 2" with open ( file1 ) as f :     contentF = f . read () with open ( file2 ) as g :     contentG = g . read () if contentF in contentG :     print ( "yes" ) else :     print ( "No" ) 💓💓 💓💓 💓💓 💓💓 💓💓

Building Snake Water Gun Game from scratch in Python - Free Source Code

Image
💓 ✋✋✋✋✋   💓 Hello, my dear ones! You can copy-paste the following code into your IDE and start playing the Snake Water Gun game instantly. Snake Water Gun Game Source Code import re def swg_game ( computer , You ):     if computer == You :         return None     elif computer == "s" :         if You == "g" :             return True         if You == "w" :             return False     elif computer == "w" :         if You == "s" :             return True         if You == "g" :             return False     elif computer == "g" :         if You == "w" :             return True         if You == "s" :             return False     import random from tkinter . messagebox import NO rNum = random . randint ( 1 , 3 ) if rNum == 1 :     computer = "s" elif rNum == 2 :     computer = "w" elif rNum == 3 :     computer = "g" print (

Making a Function in Python that converts centimeters into inches

Image
Functions in Python are very convenient. The tasks that are to be performed multiple times in Python programming can become very tedious. Fort this reason 'functions' are employed.  We simply put some repetitive task into a function and after that, we have just to recall the defined function and the result will be thrown at us in an instant. That is the beauty of python functions. Below we have defined a function for converting centimeters into inches. Now we don't need to write the formula again and again in our code to convert centimeters into inches. We just have to call the function and put our value in centimeters and the same function will convert it into inches. That's all! Syntax of Functions: def ----------> define inches--------> function name ()--------------> parameter that takes an argument return ---------> keyword in python that returns the result formula---------> the body of function Centimeters into Inches Function Definition def inches

Building my first ever game in Python - Rock Scissor Paper Game

Image
Hi friends! ✋ ✋ ✋ Today I want to talk to you about my new achievement in the Python learning journey. I call it an achievement because it matters much to me as I am an absolute beginner in this computer science field.  Lately, I started watching some tutorials regarding Python learning. I am learning much from them and I will be sharing here with you guys also what I learn each day.  The notion of 'game creation' excites me tremendously. And just recently I learnt from the same tutorials how to build my first basic game. Games are fun to play now and then. But the idea of creating them is far more exciting (at least this is so in my mind).  This is what I learned today. I built my first ever game in Python. The game is called Rock Scissor Paper Game. It is a very simple and basic game. But the creation of it brought so much joy to me. Let me share the exact code with you people also. Following is The exact code that will create this Rock Scissor Paper Game is shared below. If

The First Ever Python Program - Learning print() function

Image
Hi Everyone! This is the first-ever Python program that I learned in my life and the same is true I bet pretty much about every absolute beginner like me. Anybody who newly steps into programming will encounter this program learning.  This is indeed a baby program but it matters much as far as the absolute newbie is concerned.  This program is learning to use the print function, i.e.  print() Let's learn how to use this function! This is actually a built-in function in Python and is used to print anything that we want to display to the user.  It is very simple to use. Just type in the round parenthesis of print function your desired text that you want to be shown at the terminal or displayed to the end-user. And don't forget to quote-unquote your text.  Let's understand this with an example; Let's say I want to print 'Good morning' to the user. All I have to do is the following; print("Good morning") . . .and the user should see the message   'Good