Posts

Showing posts from July, 2022

Function in Python that counts the number of times a character is repeated in a given string

def countxo(string): x_count = f"{string}".count("x") o_count = f"{string}".count("o") if x_count == o_count: print(f"Number of x={x_count} and Number of o={o_count}. Hence", True) else: print(f"Number of x={x_count} and Number of o={o_count}. Hence", False) countxo("xoxox")

Function in Python that returns masked credit card number

  def hideCardNum(g,h,i,j): return f"******{g}{h}{i}{j}" a,b,c,d,e,f,g,h,i,j = input("Plz enter your 10 digits Credit card number: ") print(hideCardNum(g,h,i,j)) def hideCardNum(string): return f"******{string[6:10]}" number = input("Plz enter your 10 digits Credit card number: ") print(hideCardNum(number))

Function in Python that counts the number of vowels in a string

vowels = [] def vowelscount ( string ):     if "a" in string :         vowels . append ( "a" )     if "e" in string :         vowels . append ( "e" )     if "i" in string :         vowels . append ( "i" )     if "o" in string :         vowels . append ( "o" )     if "u" in string :         vowels . append ( "u" )     return len ( vowels )         print ( vowelscount ( "aeiouaeiou" ))

Function that convert a decimal number into binary in Python

  def d2b ( decimalN ):     return bin ( decimalN ). replace ( "0b" , "" ) print ( d2b ( 10 )) # bonus: One liner ninja technique print ( bin ( 10 )[ 2 :])

A function in Python that sorts a list

  def sortlist ( listname , string ):     if string == "asc" :         return sorted ( listname )     elif string == "desc" :         return sorted ( listname , reverse = True )     elif string == "none" :         return listname     else :         print ( "Wrong Input!" )         list1 = [ 4 , 8 , 6 , 1 , 9 , 56 , 33 , 19 , 2 , 55 , 14 ] list2 = [ "z" , "v" , "c" , "r" , "h" , "a" , "s" , "m" , "f" ] print ( sortlist ( list2 , "none" ))

Radians to Degrees and Degrees to Radians conversion in Python

Image
 Radians and Degrees are measures of angles. Method # 1 import math def rad2deg ( radians ):     degrees = math . degrees ( radians )     print ( f "The { radians } radian(s) is(are) equal to { degrees } degrees." )     def deg2rad ( degrees ):     radians = math . radians ( degrees )     print ( f "The { degrees } degrees are equal to { radians } radians." )     rad2deg ( 1 ) deg2rad ( 57.296 ) Method # 2 import math def rad2deg ( radians ):     degrees = radians * ( 180 / math . pi )     print ( f "The { radians } radian(s) is(are) equal to { degrees } degrees." )     def deg2rad ( degrees ):     radians = degrees * ( math . pi / 180 )     print ( f "The { degrees } degrees are equal to { radians } radians." )     rad2deg ( 1 ) deg2rad ( 57.296 )   Mathematical Notation:

printing local time in Python

  import time print ( time . asctime ( time . localtime ( time . time ())))

Finding out the execution time of programs in Python

  # we want to find out the execution time of printing "Abdur Rehman" 10 times # by for loop method and multiplication method import time timei = time . time () for i in range ( 1 , 11 ):     print ( "Abdur Rehman" ) print ( "The time taken by For loop method is" , time . time () - timei , "secs" ) time2 = time . time () print ( "abdur rehman \n " * 10 ) print ( "The time taken by * method is" , time . time () - time2 , "secs" ) # Result : For loop takes more time than * method.

*args and **kwargs In Python

# passing lists and dictionaries into *args and **kwargs def names ( monitor , * args , ** kwargs ):     print ( f "The monitor of our class is { monitor } . The students are;" )     for item in args :         print ( item )     print ( args )         print ( " \n Lets introduce our couples!" )     for key , value in kwargs . items ():         print ( f " { key } is the wife of { value } " )     print ( kwargs )         students = [ "abdur" , "kiran" , "rohit" , "mandela" , "kumar" , "asif" , "azad" ] mydict = { "kiran" : "rehman" , "maham" : "wadud" , "shazia" : "wahab" , "ashwarya" : "abishek" } names ( "hammad" , * students , ** mydict ) # passing arguments and keyword arguments directly into *args and **kwargs def names ( monitor , * args , ** kwargs ):     print ( monitor )     print...

Wikipedia module in Python

First step: pip install Wikipedia import wikipedia print ( wikipedia . summary ( "pakistan" , sentences = 2 )) wikipedia . set_lang ( "fr" ) print ( wikipedia . search ( "Coronavirus" )) print ( wikipedia . languages ()) wpage = wikipedia . page ( "coronavirus" ) print ( wpage .html) print ( wpage .links[ 0 : 10 ]) print ( wpage .original_title) result = wikipedia . search ( "air" , results = 5 ) print ( result ) print ( wikipedia . random ( pages = 6 ))  

Factorial calculation by Iterative and Recursive methods

  def factorial_iterative ( num ):     fac = 1     for i in range (num):                 fac = fac*(i+ 1 )     return fac def factorial_recursive ( num ):     if num== 0 or num== 1 :         return 1     else :         return num * factorial_recursive(num- 1 ) num = int ( input ( "Input your number: " )) print (factorial_iterative(num)) print (factorial_recursive(num))

Function in Python that determines the Fibonacci number at 'n' index

In mathematics, the Fibonacci numbers form a sequence, the Fibonacci sequence, in which each number is the sum of the two preceding ones. The sequence commonly starts from 0 and 1, although some authors omit the initial terms and start the sequence from 1 and 1 or from 1 and 2.  Starting from 0 and 1, the next few values in the sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... # The Fibonacci number present at nth index def fibo ( n ):     if n == 0 :         return 0     elif n == 1 :         return 1     else :         return fibo ( n - 1 ) + fibo ( n - 2 ) n = int ( input ( "Enter the number: " )) print ( fibo ( n ))

Store and Retrieve data in text files in Python

import datetime while input :     print ( "Welcome to Health Management System" )     print ( "Note: For correct operations, you must enter the keys as suggested." )     person = input ( "Whome? Enter 'hy' for harry, 'rn' rohan, 'hd' for hammad: " )     rl = input ( "Enter 'r' for retrieve, 'l' for lock: " )     en = input ( "Enter 'e' for exercise, 'n' for nutrition: " )     # retrieves files     def retrieve_harry_exercise ():         with open ( "harry_e.txt" ) as f :             harry_exercise = f . read ()             print ( harry_exercise )                 def retrieve_rohan_exercise ():         with open ( "rohan_e.txt" ) as f :             rohan_exercise = f . read ()             print ( rohan_exerci...

seek() and tell() functions on files in Python

  f = open ( "file_name.txt" ) print ( f . seek ( 55 )) #resets reading from 55th character print ( f . readline (), end = "" ) print ( f . tell ()) #shows where the file pointer currently is print ( f . readline (), end = "" ) print ( f . tell ()) #shows where the file pointer currently is print ( f . readline (), end = "" ) print ( f . tell ()) #shows where the file pointer currently is f . close ()

A program that takes user input and draws pattern of astrologer's stars

while True :     try :         print ( "How many rows of stars you want?" )         nr = int ( input ())     except :         print ( "Wrong input! Only numbers allowed." )         continue     print ( """Keys:     Just press Enter for inverted pattern or     Type anything and press Enter for upright pattern.""" )     tf = bool ( input ())     i = 0     if tf == True :         while i < nr :             print ( "*" *( i + 1 ))             i += 1     else :         while i < nr :             print ( "*" *( nr - i ))             i += 1

Read and write (update) a file in python

  f = open ( "file_name.txt" , "r+" ) f . read () f . write ( "You are not your body or your mind." ) f . close ()

readlines() function to store all the lines in a text document into list

  f = open ( "file_name.txt" ) content = f . readlines () print ( content ) f . close ()

How to open a file and read line by line in python

  1st method: using readline() function f = open ( " file_name .txt" ) # for line in f: #     print(line) content = f . readline () #reads line 1 print ( content ) content = f . readline () #reads line 2 print ( content ) content = f . readline () #reads line 3 print ( content ) content = f . readline () #reads line 4 print ( content ) f . close () 2nd method: using for loop f = open ( "file_name.txt" ) for line in f :     print ( line ) f . close ()

How to open a file in Python?

  f = open ( "file_name.txt" ) content = f . read () print ( content ) f . close ()

DOCSTRING gives info about a function

 How to print docstring? def prdct ( n1 , n2 ):     """This function gives product of two nums."""     result = n1 * n2     print ( result )     print ( prdct . __doc__ )

Guess the number GAME (Guess limit is 9) - You vs. Computer

import random rNum = random . randint ( 1 , 100 ) i = 0 while i < 10 :     gn = int ( input ( "We have chosen a number between 1 and 100. Guess what? " ))     i += 1     print ( "Total guess limit is 9" )     print ( f "Guess number { i } " )     print ( "Total guesses left are" , 9 - i )         if i == 9 :         print ( "You exhausted your guess limit. Game over!" )         break     if gn < rNum :         print ( "Suggestion: Choose higer number" )     if gn > rNum :         print ( "Suggestion: Choose lower number" )             if gn == rNum :         print ( f "You Won the game in { i } guesses!. Your number was { gn } " )         print ( f "Our chosen number was { rNum } " )         break

Using CONTINUE and BREAK keywords in Python

  i = 0 while True :     if i == 13 :         i += 1         continue     print ( i )     i += 1     if i == 28 :         break

Sorting out numbers from a miscellaneous list of items

  ml = [ 34 , "abdur" , 55 , 5 , "lala" , 78 , "jamil" , 53 , 3 , 99 , "Ruhee" , 66 , 45 , 12 , 1 , 2 ] for item in ml :     if str ( item ). isnumeric () and item > 6 :         print ( item )

Creating a faulty calculator that returns all the values correctly except 3 values that are given in an exam

  while True :     try :                 num1 = int ( input ( "number 1: " ))         num2 = int ( input ( "number 2: " ))         operator = input ( "Operator: " )         if operator == "+" :             a = num1 + num2             if ( num1 == 56 and num2 == 9 ) or ( num1 == 9 and num2 == 56 ):                 print ( "77" )             else : print ( f "The sum of your numbers is { a } " )                     elif operator == "-" :             b = num1 - num2             print ( f "Subtracting Number-2 from Number-1, the result is { b } " )         elif operator == "/" :      ...

A program that accepts user input then determines whether they can drive or not

  try :     age = int ( input ( "Your age: " ))     if age > 18 and age <= 100 :         print ( "You can drive!" )     elif age < 18 :         print ( "Sorry! You cannot drive!" )     elif age == 18 :         print ( "Come on site and take the test." )     elif age > 100 and age < 200 :         print ( "You are overage. Sorry!" )     else :         print ( "Humans do not have this age size" ) except :     print ( "Only numeric input acceptable" )

Create a dictionary in which the meaning of a word is shown after user input

  word = input ( "Enter the word to know its meaning: " ) mydict = {     "geek" : "enthusiast" ,     "gloomy" : "sad" ,     "mob" : "crowd" ,     "infinity" : "unlimited" ,     "dementia" : "memory loss" ,     "pensive" : "thoughtful" ,     "sibling" : "brother or sister"     } print ( f "THe moeaning of { word } is { mydict [ word ] } " )

I created a GUI in TKINTER PYTHON that takes 2 numbers from a user and adds them

  from tkinter import * root = Tk () root . geometry ( "400x230" ) root . title ( "Add Two Numbers" ) def clear ():     screen . delete ( 0 , END )     myint1_val . delete ( 0 , END )     myint2_val . delete ( 0 , END ) def clicked ():     screen . delete ( 0 , END )     a = int ( myint1_val . get ()) + int ( myint2_val . get ())     screen . insert ( 0 , a )         Label ( root , text = "Add Your TWO numbers" , font = "verdana 23 underline" ). pack () Label ( root , text = "Enter your 1st number:" , font = "verdana 13 bold" ). pack () myint1 = StringVar myint1_val = Entry ( root , textvariable = myint1 ) myint1_val . pack () Label ( root , text = "Enter your 2nd number:" , font = "verdana 13 bold" ). pack () myint2 = StringVar myint2_val = Entry ( root , textvariable = myint2 ) myint2_val . pack () Label ( root , text = "The sum of your numbers is:" , font = "verdana 13 bold...

Creating Notepad in Tkinter Python

  from tkinter import * import tkinter . messagebox as tmsg from tkinter . filedialog import askopenfilename , asksaveasfilename import os root = Tk ()   root . title ( "Notepad" ) root . geometry ( "1200x600" ) root . wm_iconbitmap ( "Notepad.ico" ) def new_file ():     global file     root . title ( "Untitled - Notepad" )     file = None     textwd . delete ( 1.0 , END )     def open_file ():     global file     file = askopenfilename ( defaultextension = ".txt" , filetypes =[( "All Types" , "*.*" ), ( "Text Documents" , "*.txt" )])     if file == "" :         file = None     else :         root . title ( os . path . basename ( file ) + " - Notepad" )         textwd . delete ( 1.0 , END )         f = open ( file , "r" )         textwd . insert ( 1.0 , f . read ()) ...