Create Multiplication Table with Python

This tutorial will show how to create a multiplication table using the programming language Python. The multiplication table will consist of two Python components input() and for loops .

input() will be used to get the user input and the for loop will loop through the range of multiples ( i.e 5 x 1, 5 x 2 , … 5 x 12 )

Here is a deeper explanation of input() and for loops .

# Multiplication table

# Get input from the user
num = int(input("Get multiple of :"))

# Iterate 12 times
for i in range(1, 13):
   print(num, 'x', i, '=', num*i)
Output
Get multiple of  : 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
7 x 11 = 77
7 x 12 = 84

Android Studio Loading Animation Between Activities

Progress Dialog is dialog showing a progress indicator and an optional text message or view. The methods of Progress Dialog being used in this tutorial are: ProgressDialog.setTitle() – Used to set title of dialog box ProgressDialog.setMessage() – Used to set dialog message being displayed ProgressDialog.setProgressStyle() – Choose the style of indicator ProgressDialog.dismiss() – Dismiss the…

Android Studio Tutorial SeekBar

SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch thumb and drag left or right to set the current progress level or various other task. In this example, the seekbar will be used to display a percentage. As the user moves the SeekBar left to right the percentage value…

Python Ethereum Block Chain Interaction with Web3

This tutorial will show how to interact with the Ethereum blockchain using Python. To start, the Python library Web3 will need to be installed. The Web3 library allows you to interact with a local or remote Ethereum node, using a HTTP or IPC connection. Using Web3 you will be able to create smart contracts on…

Python Dictionary

A Dictionary is a unordered , indexed collection of items. Each item is given a Key and a value to store. For this example, the dictionary will store Users information such as Name, Date of Birth and phone number.

userDict = {
  "Name": "Joe",
  "DoB": "01/12/1901",
  "Phone": 8001234567
}
print(userDict)

Add Item

Items can be added by creating a new Key and giving it a value

userDict = {
  "Name": "Joe",
  "DoB": "01/12/1901",
  "Phone": 8001234567
}

userDict["Last Name"] = "Smith"

print(userDict)

Remove Item

pop.() can be used to remove specific items from a dictionary

userDict = {
  "Name": "Joe",
  "DoB": "01/12/1901",
  "Phone": 8001234567
}

userDict.pop("DoB")

print(userDict)

Edit Values

A Key’s values can be changed or edited by referencing it’s name

userDict = {
  "Name": "Joe",
  "DoB": "01/12/1901",
  "Phone": 8001234567
}
userDict["DoB"] = "03/07/2020"

print(userDict)

Retrieve Item

Objects in dictionary can be retrieved by using brackets and the name of the Key

userDict = {
  "Name": "Joe",
  "DoB": "01/12/1901",
  "Phone": 8001234567
}

user = userDict["Name"]

print(userDict)

Get Length of Dictionary

Print number of items in dictionary

print(len(userDict))

Loop Through Dictionary

This will loop through the dictionary one by one.

for x in thisdict:
  print(thisdict[x])

Loop through both Keys and Values

for x, y in thisdict.items():
  print(x, y)

Python chr()

The chr() function returns a character that represents the specified unicode. Syntax chr(i) The chr() method takes only one integer as argument.The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).The chr() method returns a character whose unicode point is num, an integer.If an integer is passed that is outside the range then the method returns…

Python callable()

The callable() method checks if a object is callable. Callable objects are True if object is callable and False if object is not callable. Syntax & Parameters callable(object)  The callable() method takes one argument, an object and returns one of the two values: returns True, if the object appears to be callable.returns False, if the…

Python bytes()

bytes() returns an immutable bytes object, made up of a sequence of integers in the range 0 <=x < 256. The returned bytes sequence is immutable. A mutable bytes sequence can be used instead by calling is bytearry() . Syntax bytes(]]) bytes() takes three optional parameters: source – initialize the array of bytes. Can be String…

Python filter() Example

filter() is used to iterate through a sequence to check if each object is True or False.

filter() takes two parameters. Function that tests if elements of an iterable return true or false. Iterable which can be set, tuple , or list

Ex.

filter(function , iterable)

In the example below, user input will be filtered to check if it contains a multiple of 2. How it works is a number is inputted into the console and the filter checks if the put value is Ture or False. Learn more about getting User Input here

put = input()

# function that filters 2Xs multiple
def TwoTimes(put):
    twoX = ['2', '4', '6','8' ]

    if(put in twoX):
        return True
    else:
        return False

filtered = filter(TwoTimes, put)

print('Filtered Output :')
for times in filtered:
    print(times)

OutPut:

Filtered Output :
4

Python bytearray()

The bytearray() method returns an array of bytes. Syntax bytearray(]]) source – source to initialize the array of bytes string – Converts the string to bytes using str.encode()integer – Creates an array of provided size, all initialized to nulliterable – Creates an array of size equal to the iterable count . Iterable integers must be…

Python breakpoint()

The breakpoint() function is a debugging function that is built into Python 3.7 . Use this built in function by adding breakpoint() where you suspect the error or are wanting to check for bugs. The pdb (Python Debugger) is a interactive source code debugger for Python programs. Python Debugger Commands : Ex. Output Once code…

Python bool()

The bool() function converts a value to a Boolean expression, True or False . If no parameter is given, by default the Boolean returns False. Boolean returns True if the parameter or value is True. Syntax bool([x]) x – is the value being evaluated by standard truth testing procedures. Example Output

Python SQLite3 Database Tutorial

This tutorial will show how to start using the built in database that Python provides. The library comes pre-installed with Python and is named SQLite3 . SQLite can be used to create a tables , databases, and run queries.

To learn more about SQLite and what it can do, check out their site . They provide very good documentation , here is the link to reference for this tutorial.

Step One :

First, the sqlite3 library must be imported. Then the database file must be created. Connection or connect allows the sending and receiving of data such as strings. The Cursor instance allows the connection to send and receive data.

import sqlite3

#Creating table
dataBase = sqlite3.connect('Test.db')

cur = dataBase.cursor()

Step Two:

Now that the table has been created, the data it contains must be given a label. Here the table will store the user data. Each user will be given a Name and Phone number. In SQLite tables, the values each label is going to store needs to be set.

Notice how the Name label is set to store a text value and the Phone is set to store a real value. Once the label are created, user data can then be added to the table

#Setting table labels
cur.execute('''CREATE TABLE user
             (Name text, Phone real)''')

# Insert  data
cur.execute("INSERT INTO user VALUES ('Joe',1234567)")

Final Step

Lastly, the connection to the database must be closed and the changes to the database must be Committed.

# Save (commit) the changes. ALWAYS COMMIT any changes
dataBase.commit()

#Closing connection
dataBase.close()

Testing Database

Lets check if the database file is running correctly. Here the execute method is used to check if the SQL table is storing the user’s Name Joe“. If the table contains a user with a Name equal to Joe, it will print out that user’s info. The method fetchone() will be used because only one user will be returned

import sqlite3

#Creating table
dataBase = sqlite3.connect('Test.db')
cur = dataBase.cursor()

var = ('Joe',)
#Check if Name is being stored
cur.execute('SELECT * FROM user WHERE Name=?', var)
print (cur.fetchone())

Output:

('Joe', 1234567)

Python bin()

The bin() function converts an integer , both positive and negative, into binary form. Syntax bin(n) n – integer being converted Example Output

Python ascii()

ASCII – American Standard Code for Information Interchange The ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes. Syntax ascii(object) object – String , List , tuple etc. Ex. Output :

Python any()

The any() function returns True if any item in an iterable are true. If no item is true then False. Syntax & Parameters any(iterable) iterable – An iterable object list, tuple, dictionary etc. Ex. Output :

How to Use Variables from another Python File

This tutorial will show how to use variables from one Python file in another. The first step in using another Python file is to use the built in keyword import . Import is used to import Python libraries modules. Here is a List of useful keywords

When using import , the file being imported will be executed when the Python file importing it is ran.

For this example, there are two Python Files the first file is named Main.py and the file being imported is named Second.py

Main.py

import Second
#printing X var from Second
print(Second.X)

In the Main.py file the Second file will be imported. Then the X variable from the will be printed out.

Second.py

X= 5
try:
    # If X is Greater than 5
    if X> 3:
        print("Greater Value")
    # X less than five
    else:
        print("Nope")
#
finally:
    print("Run Complete")

The Second file consist of a try statement that checks if the X variable is greater than 3.

Note: the finally will always run.

Output :

Greater Value
Running
5

Python all()

The all() function returns Ture if all elements are itterable and False if elements are not. Parameters all(iterable) iterable – is an object that can be looped over such as list , string , tuple etc. Ex. Output :

Python abs( )

abs() function is used to return an absolute value Syntax abs(n)n is the required integer Example Output :

Top 10 Python Interview Questions 2021

# 1 What’s Pickling and Unpickling? Pickling –  the process of a Python object hierarchy being converted into a byte streamUnpickling – is the inverse operation, where a byte stream is converted back into an object hierarchy. Pickling is also called serialization, marshalling, or flattening. # 2 What Is the Difference Between range() and xrange() Functions in Python?…

Python Tutorial Magic 8 Ball

This tutorial will show how to make a magic 8 ball program in python. This program will have the same functions as a magic 8 ball , the user will input a question and the 8-ball will generate a reply to the question. The user’s input will by retrieved by using input() . Here is…

Christmas Count-down Clock with Java

This tutorial will show how to make a simple java program that will count how many day there are till Christmas. The package being used to handle the dates is java.time . If you are unfamiliar with this package here is a quick intro on how to use the package. The Christmas Count-down Clock code…

Java Time and Date

This tutorial will show how to create a time stamp with Java. Since Java does not have a built in package for handing dates and time, the package java.time will need to be imported. This package is an API for dates, times, instants, and durations. Here is a link to the java.time documentation if you…

Python Tkinter Dropdown Menu

This tutorial will show how to create a Dropdown menu feature using the Tkinter Library. The Tkinter library is used to create GUIs and various different elements and Dialog Windows.

To create a dropdown menu the Tkinter widget OptionMenu will be used.

This program will use an OptionMenu to let user selected size. If the “Print ” button is clicked it will print out the selected Size. When the user selects a size, the selected sizes will be given a 1 and the unselected sizes a 0

from tkinter import *

SIZES = ['Small','Med.','Large','XL']

#Get Selected Sizes
def print_SIZES(*args):
   values = [(Size, var.get()) for Size, var in data.items()]
   values
   print(values)

data = {} # dictionary to store all the IntVars

#tkinter option menu
TKINTER = Tk()
TKINTER.title("Size Selector")
bMenu=  Menubutton ( TKINTER, text="Select Size ", relief=RAISED )
bMenu.menu  =  Menu ( bMenu, tearoff = 0 )
bMenu["menu"]  =  bMenu.menu

#if selected 
for Size in SIZES:
    var = IntVar()
    bMenu.menu.add_checkbutton(label=Size, variable=var)
    data[Size] = var # add IntVar to the dictionary

btn = Button(TKINTER, text="Print", command=print_SIZES)

btn.pack()
bMenu.pack()
TKINTER.mainloop()

Output:

[('Small', 0), ('Med.', 1), ('Large', 1), ('XL', 0)]

Python Tutorial : Sets

Sets are unordered, unique elements. The objects in the set must be unique ,duplicates can not be used in sets.

set_objects = {"boat", "sock", "phone","lamp"}
print(set_objects)

Check if certain objects are in set. If object is in the list system will print true and if object is not will print false

set_objects = {"boat", "sock", "phone","lamp"}

print("boat" in set_objects)
print("pen" in set_objects)

Strings can be pass in Set. It will iterate through the characters of the string as an object boat becomes “b”,”o”,”a”,”t”

set_object = "boat"

print(set_object)

Add objects to Set with add() or update()

add() is used to add one object

update() is used to add more than one object

# add() one object 
set_objects.add("bike")
print(set_objects)

# update() more than one object
set_objects.update(["kite", "ball", "hat"])
print(set_objects)

To remove an item in a set, use remove() or discard()

set_objects.remove("ball")
print(set_objects)


set_objects.discard("kite")
print(set_objects)

Get number of objects in set, use len()

print(len(set_objects))

loop through set objects

# loop through set
for x in set_objects:
  print(x)

Checkout more Python tutorials here!

Python Dictionary

A Dictionary is a unordered , indexed collection of items. Each item is given a Key and a value to store. For this example, the dictionary will store Users information such as Name, Date of Birth and phone number. Add Item Items can be added by creating a new Key and giving it a value…

Python filter() Example

filter() is used to iterate through a sequence to check if each object is True or False. filter() takes two parameters. Function that tests if elements of an iterable return true or false. Iterable which can be set, tuple , or list Ex. In the example below, user input will be filtered to check if…

Python SQLite3 Database Tutorial

This tutorial will show how to start using the built in database that Python provides. The library comes pre-installed with Python and is named SQLite3 . SQLite can be used to create a tables , databases, and run queries. To learn more about SQLite and what it can do, check out their site . They…

Python Web Scraper with Only 4 Lines of Code

This tutorial will show how to create a web scraper with only 4 line of code. A web scraper copies all of the data from a web page and converts the html to readable text. To get started you will need to import two Python libraries BeautifulSoup and urllib

urllib will be used to to handle URLs and BeautifulSoup will be used to parse web site html.

  1. Line : Setting variable to web link
  2. Line : Opening Webpage of the link done by using urlopen()
  3. Line : Reading and decoding html using .read().decode()
  4. Line : Parsing text from html using BeautifulSoup() and html.parser which is a built in HTML parser
from bs4 import BeautifulSoup
from urllib.request import urlopen

# website being scraped
url = "https://codeit.blog/beginner-python-tutorial-1-the-basics/"

# opening URL
webpage = urlopen(url)

# Reading and decoding 
html = webpage .read().decode("utf-8")

# Parsing text from html 
bs = BeautifulSoup(html, "html.parser")

print(bs.get_text())
Output :
Python for Beginners #1 The Basics
Python is a user friendly, object oriented programming language. It was created in 1991 by  Guido van Rossum. Python was designed to be easily read and uses simple syntax. This makes Python great for beginners. 
Python can be used for:
Web Development Data Science Data Analysis Machine Learning 

How to Use Variables from another Python File

This tutorial will show how to use variables from one Python file in another. The first step in using another Python file is to use the built in keyword import . Import is used to import Python libraries modules. Here is a List of useful keywords When using import , the file being imported will…

Python Tkinter Dropdown Menu

This tutorial will show how to create a Dropdown menu feature using the Tkinter Library. The Tkinter library is used to create GUIs and various different elements and Dialog Windows. To create a dropdown menu the Tkinter widget OptionMenu will be used. This program will use an OptionMenu to let user selected size. If the…

Python Tutorial : Sets

Sets are unordered, unique elements. The objects in the set must be unique ,duplicates can not be used in sets. Check if certain objects are in set. If object is in the list system will print true and if object is not will print false Strings can be pass in Set. It will iterate through…

Java Thread

Threads are used to to run multiple programs simultaneously. Primarily, Threads execute a given program.

There are two ways to create threads extends and implements

  • extends Thread class cannot extend any other classes
  • implements Thread class can extend to other classes
Extends
public class Example extends Thread {

 public static void main(String[] args) {

// Creating thread
    Example thread = new Example();
//  Running the thread
    thread.start();

    System.out.println("Main Program");
  }
  public void run() {

    System.out.println("This is the Thread");
  }
}
Implements
public class Example implements Runnable {

  public static void main(String[] args) {

// Object Constructor 
    Example Object = new Example ();
// Creating new thread
    Thread thread = new Thread(Object );
// Starting Run 
    thread.start();

    System.out.println("Main Program");
  }
  public void run() {
    System.out.println("This is the Thread");
  }
}

Python Web Scraper with Only 4 Lines of Code

This tutorial will show how to create a web scraper with only 4 line of code. A web scraper copies all of the data from a web page and converts the html to readable text. To get started you will need to import two Python libraries BeautifulSoup and urllib urllib will be used to to…

Java Tutorial : Switch

The Switch key word is used to choose what code block to run given a certain criteria break ; is used to separate each code block Output :

Java Tutorial : CountDownLatch

CountDownLatch are used to control to flow of multiple running task. CDL delays the run time of tasks before the main thread is ran. Its simply a timer that counts down to zero and when timer hits zero the main thread is ran but during its count down it is also running other tasks .…

Java Tutorial : Switch

The Switch key word is used to choose what code block to run given a certain criteria

break ; is used to separate each code block

public class Switch {

	public static void main(String[] args) {
//	Setting Variable 	
		String Acccess = "User Passed!";
// Creating Switch 		
		switch (Acccess) {
		  case "User Passed!":
		    System.out.println("Access Granted");
		    break;
		  case " User Failed!":
		    System.out.println("Denied");
		    break;  
		}
		
		 System.out.println("www.codeit.blog");
	}
}
Output :
Access Granted
 www.codeit.blog

Java Thread

Threads are used to to run multiple programs simultaneously. Primarily, Threads execute a given program. There are two ways to create threads extends and implements extends Thread class cannot extend any other classesimplements Thread class can extend to other classes Extends Implements

Java Tutorial : Distance Between two Places in Miles

This tutorial will show to to get the distance between two places using Java programming. First, to start this project we need the Longitude and Latitude from two separate locations. For this example, I used Random.org to find two different GPS coordinates. Once the coordinates are chosen, next have to convert those coordinates into radiants.…