Sunday, April 20, 2025

Python While Loops

While loops are extremely useful when we need specific lines of code to run constantly.

Basically, we need to define a starting point, ending point, and how to jump from one point to another.

Of course, in between those points, some useful part of code need to be executed:


x = 0

while x < 10:
    print("Value of x atm: ", x)
    x = x + 1

Result: 


Value of x atm:  0
Value of x atm:  1
Value of x atm:  2
Value of x atm:  3
Value of x atm:  4
Value of x atm:  5
Value of x atm:  6
Value of x atm:  7
Value of x atm:  8
Value of x atm:  9
>>> 

We will import os module, so we can run application inside our operating system - using Python script.

"x = x + 1" is used to gradually jump from 0 until 3 is reached - it's like a very simple algorithm.

If you run this code, calculator will pop-up 3 times on Desktop. Sure, we can run other apps, not just calc:


import os

x = 0

while x <= 3:
    os.system("calc")
    x = x + 1

In next tutorial, we will learn about Break and Continue options when looping with While Loops.

Python If, elif, else

With if statements we will do all kind of checks. For example, if x is smaller than y, we will just print: "x is smaller than y", and so on:


x = 20
y = 20

if x < y:
    print("x is smaller than y")
if x > y:
    print("x is bigger than y")
if x == y:
    print("They are Equal")

Result: 


They are Equal
>>> 

We can add "else" at the end of check, as the last possible case. In the middle of check you can use "elif", which is short for "else if":


x = 20
y = 20

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


They are Equal
>>> 

It's fun to take input from keyboard:


x = input("Please enter x: ")
y = input("Please enter y: ")

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


Please enter x: 555
Please enter y: 10
x is bigger than y
>>> 

When you know that you will need numbers, and not strings, convert what you take from keyboard into integers/floats with int() or float() function.


x = input("Please enter x: ")
y = input("Please enter y: ")

print("Before x and y are strings: ")
print(type(x))
print(type(y))

print("After we convert them, they are integers: ")
x = int(x)
y = int(y)

print(type(x))
print(type(y))

Result: 


Please enter x: 10
Please enter y: 50
Before x and y are strings: 
<class 'str'>
<class 'str'>
After we convert them, they are integers: 
<class 'int'>
<class 'int'>
>>> 

Now, we are absolutely sure that things from keyboard will be used as numbers, and not as strings (words):


x = int(input("Please enter x: "))
y = int(input("Please enter y: "))

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


Please enter x: 50
Please enter y: 100
x is smaller than y
>>> 

In next tutorial, we will learn about While Loops.

Python Dictionary Operations

We can easily add new key-value pairs:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba["Address"] = "No Name 123"
dba["Tel"] = 555888

print(dba)

Result: 


{'Name': 'Anastasia', 'SSN': 123456, 'Address': 'No Name 123', 'Tel': 555888}
>>> 

Use pop() function to remove specific key-value pair:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.pop("SSN")

print(dba)

Result:  


{'Name': 'Anastasia'}
>>> 

To remove k-v pair from dictionary end, use popitem() function. Here, we will use it two times:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.popitem()
dba.popitem()

print(dba)

Result:  


{}
>>> 

To remove all pairs, use clear() function:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.clear()

print(dba)

Result:  


{}
>>> 

Well known del() function to destroy everything:


dba = {"Name" : "Anastasia", "SSN" : 123456}

del dba

We can take keys and values from keyboard:


dba = {"Name" : "Anastasia", "SSN" : 123456}

k = input("New Key: ")
v = input("New Value: ")

dba[k] = v

print(dba)

Result:  


New Key: Telephone
New Value: 555888
{'Name': 'Anastasia', 'SSN': 123456, 'Telephone': '555888'}
>>> 

Now we know a lot about Python.

It's time to talk about if-else statements - they are just simple checks that we will use all the time in programming.

Python Dictionaries

Dictionaries are collections with "left and right side", or, "key and value pairs".

Basically keys, (left) describe data on right (value) side.

Dictionaries are created with curly brackets:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba)

Result: 


{'Name': 'Anastasia', 'SSN': 123456}
>>> 

We will get values using keys:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba["Name"])
print(dba["SSN"])

Result: 


Anastasia
123456
>>> 

Small reports/explanations are easy:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print("Name: ", dba["Name"])
print("SSN: ", dba["SSN"])

Result: 


Name:  Anastasia
SSN:  123456
>>> 

Simple one-line extraction:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba["Name"], " -> ", dba["SSN"])

Result: 


Anastasia  ->  123456
>>> 

Dictionaries are not "fixed in time", to change values - target keys first:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba["Name"] = "Michael"
dba["SSN"] = 555444

print(dba)

Result: 


{'Name': 'Michael', 'SSN': 555444}
>>> 

If you like parentheses more than brackets, use get() function:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba.get("Name"))

Result: 


Anastasia
>>> 

We will talk about Dictionary Operations more in next tutorial.

Python Sets, Remove, Discard

To remove element from set use remove() function:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.remove("Yellow")
print("After: ", colors)
print("Number of colors: ", len(colors))

Result:

Colors are:  {'Green', 'Black', 'Yellow', 'Red'}
Number of colors:  4
--------------------------------------------------
After:  {'Green', 'Black', 'Red'}
Number of colors:  3
>>> 

Error on multiple Remove Operations:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.remove("Yellow")
colors.remove("Yellow")
colors.remove("Yellow")

print("After: ", colors)
print("Number of colors: ", len(colors))

Result: 


Colors are:  {'Yellow', 'Green', 'Black', 'Red'}
Number of colors:  4
--------------------------------------------------
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 8, in <module>
    colors.remove("Yellow")
KeyError: 'Yellow'
>>> 

But we can use discard() function to evade errors:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.discard("Yellow")
colors.discard("Yellow")
colors.discard("Yellow")

print("After: ", colors)
print("Number of colors: ", len(colors))

Result:

Colors are:  {'Green', 'Red', 'Yellow', 'Black'}
Number of colors:  4
--------------------------------------------------
After:  {'Green', 'Red', 'Black'}
Number of colors:  3
>>> 

Function clear() will remove all elements:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.clear()

print("After: ", colors)
print("Number of colors: ", len(colors))

Result: 


Colors are:  {'Black', 'Red', 'Green', 'Yellow'}
Number of colors:  4
--------------------------------------------------
After:  set()
Number of colors:  0
>>> 

To destroy set, use del() function:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)

del colors

print(colors)

We can't use something we destroyed:


Colors are:  {'Green', 'Red', 'Black', 'Yellow'}
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 7, in <module>
    print(colors)
NameError: name 'colors' is not defined
>>> 

Next tutorial will be about Dictionaries.

Python Sets, Add, Update

We can create sets with multiple same elements, but duplicates are disregarded in usage.

This is how to add new element to set - function add() will get the job done:


colors = {"Green", "Yellow", "Red", "Black", "Black"}
print(colors)

colors.add("Orange")
print(colors)

Result: 


{'Black', 'Red', 'Green', 'Yellow'}
{'Black', 'Yellow', 'Red', 'Orange', 'Green'}
>>> 

We can't use indexes here - you will get Traceback (Error):


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print(colors[0])

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 3, in <module>
    print(colors[0])
TypeError: 'set' object is not subscriptable
>>> 

We can't replace one element with another one using "string replace" approach. This will result in mess:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

colors.update("Green", "OrangeRed")

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'e', 'd', 'Black', 'n', 'R', 'Yellow', 'Green', 'Red', 'r', 'g', 'a', 'O', 'G'}
>>> 

But we can add new things to sets with update() function with brackets inside parentheses:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

colors.update(["OrangeRed"])

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Green', 'OrangeRed', 'Red', 'Black', 'Yellow'}
>>> 

Sure, we can grab new elements using keyboard:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

x = input("New Color for x: ")
y = input("New Color for y: ")

colors.update([x, y])

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
New Color for x: Magenta
New Color for y: Navy
{'Yellow', 'Black', 'Red', 'Green', 'Magenta', 'Navy'}
>>> 

Function len() will work here, just as with strings or tuples:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
Colors are:  {'Red', 'Black', 'Green', 'Yellow'}
Number of colors:  4
>>> 

In next tutorial, we will learn how Remove and Discard elements of sets.

Python Sets

Sets are collections of unique elements. We don't care about positions here. That's why we will have different result every time sets are printed.

To create set, use curly bracket:


colors = {"Green", "Yellow", "Red", "Black"}

print(colors)
print(type(colors))

Result: 


{'Black', 'Yellow', 'Green', 'Red'}
<class 'set'>
>>> 

Or dedicated set() function. Don't forget to use double parentheses:


colors_2 = set(("White", "Blue"))

print(colors_2)
print(type(colors_2))

Result: 


{'Blue', 'White'}
<class 'set'>
>>> 

Try to print set multiple times - positions will be different every time:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print(colors)

Results: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Red', 'Black', 'Yellow', 'Green'}
>>> 
============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Green', 'Yellow', 'Red', 'Black'}
>>> 
============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Black', 'Yellow', 'Red', 'Green'}
>>> 

In next tutorial, we will learn how to Add or Update Sets with new elements.

Python Tuples, Operations

To get number of specific elements (by value), we can use count() function:


tuple_names = ("Samantha", "Madonna", "Michael")

result = tuple_names.count("Samantha")

print("Number of Samantha's: ", result)

Result: 


Number of Samantha's:  1
>>> 

We can locate position of specific element (by value) using index() function:


tuple_names = ("Samantha", "Madonna", "Michael")

pos = tuple_names.index("Madonna")

print(pos)

Result: 


1
>>> 

If we grab value from keyboard, it's easy to find first location, and total number of elements:


tuple_names = ("Samantha", "Madonna", "Michael")

x = input("Enter name to check: ")

print("Number of them: ", tuple_names.count(x))
print("First occurence at position: ", tuple_names.index(x))

Result: 


Enter name to check: Madonna
Number of them:  1
First occurence at position:  1
>>> 

Tuples are easy to work with.

Next tutorial will be dedicated to Sets.

Python Tuples

Think about tuples as collection of elements that you can't change. They are "fixed in time".

To create them use parentheses:


tuple_names = ("Samantha", "Madonna", "Michael")

print(tuple_names)
print(type(tuple_names))

Result: 


('Samantha', 'Madonna', 'Michael')
<class 'tuple'>
>>> 

Positions work here too:


tuple_names = ("Samantha", "Madonna", "Michael")

print(tuple_names[0])
print(tuple_names[1])
print(tuple_names[2])

Result: 


Samantha
Madonna
Michael
>>> 

And we can do very simple checks with if statement:


tuple_names = ("Samantha", "Madonna", "Michael")

if "Samantha" in tuple_names:
    print("Samantha is there")

Result: 


Samantha is there
>>> 

Ok, in next tutorial we will talk about tuple operations.

Python Search, Clear

To detect do we have specific element in list we can use simple if statement - this is "yes or no" situation:


names =["Michael", "Samantha", "Anastasia", "John"]

if "Samantha" in names:
    print("Samantha is there")

Result: 


Samantha is there
>>> 

What if Samantha is not element of list:


names =["Michael", "Anastasia", "John"]

if "Samantha" in names:
    print("Samantha is there")
else:
    print("Samantha is not there")

Result: 


Samantha is not there
>>> 

If we create multiple lists based on one original list, all changes will replicate to those lists, too:


names =["Michael", "Samantha", "Anastasia", "John"]

a = names
b = names
c = names

names[0] = "New Name"
print(names)
print()
print(a)
print(b)
print(b)

Result: 


['New Name', 'Samantha', 'Anastasia', 'John']

['New Name', 'Samantha', 'Anastasia', 'John']
['New Name', 'Samantha', 'Anastasia', 'John']
['New Name', 'Samantha', 'Anastasia', 'John']
>>> 

To delete all elements, there's dedicated clear() function:


names =["Michael", "Samantha", "Anastasia", "John"]

names.clear()
print(names)

Result: 


[]
>>> 

To delete whole list, use del() function:


names =["Michael", "Samantha", "Anastasia", "John"]

#List destruction
del names

You can't print from something you destroyed:


names =["Michael", "Samantha", "Anastasia", "John"]

del names
print(names)

Result: 


Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 4, in <module>
    print(names)
NameError: name 'names' is not defined
>>> 

In next tutorial, we will learn about Tuples.

Python Delete, Remove, Pop

To delete one element from list, again, indexes will be used:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

del names[0]
del names[0]
del names[0]

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['John']
>>> 

Actually, we can delete all of them using index 0 and for loop:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

for x in range(4):
    del names[0]

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
[]
>>> 

If we know what we are searching for, we can remove() by value:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

names.remove("Michael")
names.remove("John")

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['Samantha', 'Anastasia']
>>> 

Sometimes it's useful to target element at the end of list:


names =["Michael", "Samantha", "Anastasia", "John"]
print(names)

names.pop()
print(names)

names.pop()
print(names)

names.pop()
print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['Michael', 'Samantha', 'Anastasia']
['Michael', 'Samantha']
['Michael']
>>> 

Function pop() is useful when we need to grab that last element we removed, so we can do something more with it:


names =["Michael", "Samantha", "Anastasia", "John"]

last_element = names.pop()

print("What we pop-ed: ", last_element)
print("Names after pop:", names)

Result: 


What we pop-ed:  John
Names after pop: ['Michael', 'Samantha', 'Anastasia']
>>> 

In next tutorial, we will learn how to search for specific element, and how to use clear() function to remove all of them.

Python Change, Insert, Append

We can change element using positions:


names =["Michael", "Samantha", "Anastasia", "John"]

names[0] = "Patrick"
print(names)

Result: 


['Patrick', 'Samantha', 'Anastasia', 'John']
>>> 

New elements can be inserted using insert() function. Even duplicates:


names =["Michael", "Samantha", "Anastasia", "John"]

names[0] = "Patrick"
names.insert(1, "Madona")
names.insert(2, "Madona")

print(names)

Result: 


['Patrick', 'Madona', 'Madona', 'Samantha', 'Anastasia', 'John']
>>> 

Sure, we can append new elements at the end of list using append() function:


names =["Michael", "Samantha", "Anastasia", "John"]

names[0] = "Patrick"
names.append("Brian")
names.append("Larry")

print(names)

Result: 


['Patrick', 'Samantha', 'Anastasia', 'John', 'Brian', 'Larry']
>>> 

We can also transfer elements of one list into another one - using for loop:


names =["Michael", "Samantha", "Anastasia", "John"]
names1 = ["Patrick", "Madona", "Larry"]

for x in names1:
    names.append(x)

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John', 'Patrick', 'Madona', 'Larry']
>>> 

In next tutorial, we will learn how to Delete, Remove and Pop elements from lists.

Python Length, Indexes

From last tutorial we know how to get total number of elemens in list:


names =["Michael", "Samantha", "Anastasia"]

lol = len(names)
print("Number of elements: ", lol)

Result: 


Number of elements:  3
>>> 

Also, as with strings, to get specific character we can use positions/indexes enclosed in brackets. First element is at position 0:


names =["Michael", "Samantha", "Anastasia"]

print("Element 0 :", names[0])
print("Element 1 :", names[1])
print("Element 2 :", names[2])

Result: 


Element 0 : Michael
Element 1 : Samantha
Element 2 : Anastasia
>>> 

Often, it's useful to grab elements of one list and store it in another one, changing order of them:


names =["Michael", "Samantha", "Anastasia"]

mix = (names[2], names[0], names[1])

print(mix)

print("Element 0 :", mix[0])
print("Element 1 :", mix[1])
print("Element 2 :", mix[2])

Result: 


('Anastasia', 'Michael', 'Samantha')
Element 0 : Anastasia
Element 1 : Michael
Element 2 : Samantha
>>> 

In next tutorial, we will learn how to Change, Append and Insert elements in existing lists.

Python Lists

In lists, we can have numbers, characters, words - you are not limited by data type:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
names = ["Samantha", "John", "Michael"]

print(numbers)
print(names)

Result: 


[1, 2, 3, 4, 5, 6, 7, 8, 9]
['Samantha', 'John', 'Michael']
>>> 

Here, just as for strings, we can use type() function:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
names = ["Samantha", "John", "Michael"]

print(type(numbers))
print(type(names))

Result: 


<class 'list'>
<class 'list'>
>>> 

Function len() will return number of elements:


numbers = [1, 2, 1, 2, 1, 2]
names = ["Samantha", "John", "Samantha", "John"]

print(len(numbers))
print(len(names))

Result: 


6
4
>>> 

Tu turn string into list, we will use list() function:


x = "something"
y = list(x)

print(y)
print(len(y))
print(type(y))

Result: 


['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
9
<class 'list'>
>>> 

In next tutorial, we will extract elements of lists using indexes.

Python Keyboard Input

It's extremely easy to grab input from the keyboard in Python:


print("Your First App v0.00001")
print("-----------------------")

x = input("Please, enter your name: ")
print("Name: ", x)

We can do some immediate calculations:


print("Your First App v0.00001")
print("-----------------------")

x = int(input("Please, enter some number: "))
print("Result: ", x + x)

And sure, use as much inputs as you need:


print("Your First App v0.00001")
print("-----------------------")

x = (input("Please, enter your Name: "))
y = (input("Please, enter your LastName: "))

print(x, y)

In next tutorial we will work with Lists. They are just collections of elements enclosed in brackets.

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...