0

Mini project to practice file handling and lists in python

ractice file handling and lists in python

file handling and lists in python – We’re going to create some summary data for a hardware store by reading their file of sales and creating some
departmental totals.

  1. The file name is inventory.txt. Download the file and save it in the same directory as your .py files will be.
  2. Open the file inventory.txt and look at it. You’ll see that each line has 3 pieces of information. The first
    is the department name. We only have a Lighting, a Plumbing and a Garden department at our little
    store. Be careful to not make any changes to this file. If you happen to make a change, feel free to
    download a “clean” version of the file and start over

Your job is to write a program that calculates the total sales for the hardware store as well as the total sales
for each department.(file handling and lists in python)
Your final output should look like this (with the correct numbers, though). Notice the line spacing and
formatting of the values.
Sales by Department:
Plumbing: $3568.24
Lighting: $241.34
Garden: $6423.21
Total Sales: $10232.79

Requirements:

  1. Each line in the file must be read as a string and then split into a list.
  2. Based on the department name in the line that was just read, add the value of the sales to the total
    sales for that department. Remember, we read the line as a string, converted it to a list of strings – but
    we can only add numbers. You will be ignoring the second data value in each line…..for now.
  3. At the end, print the total sales for the entire store.

Assumptions that you may make:

  1. The file exists and contains at least one line.
  2. There are no lines which have any department other than those 3 departments.
  3. All data is “valid” (i.e. the 3rd value in each line is a number, the 1st value is a valid department)

CODE

file_name = "inventory.txt" 

my_file = open(file_name,"r")

lines = my_file.readlines()

total_sales = 0.0
Plumbing = 0
Lighting = 0
Garden = 0
total = 0
for line in lines:

data = line.split(",")

department = data[0]

sales = float(data[2])

if department == "Plumbing":
Plumbing += sales

if department == "Lighting":
Lighting += sales
if department == "Garden":
Garden += sales

total += sales




print("Sales by Department:\n")

print("Plumbing: $",round(Plumbing,2))
print("Lighting: $",round(Lighting,2))
print("Garden : $",round(Garden,2))



print("\nTotal Sales: $",round(total,2))

keep visiting : shaadcoding

0

Employee Management System in C++/ CPP

Employee Management System

PROBLEM STATEMENT:

You are hired as an Application developer for a company called XYZ to facilitate the Human resource Management Department (HRM) to keep employee record. You are requested to write a program for HRM department to keep record of maximum 10 employees. Following is a menu and step by step guidance.

Menu: Welcome to Human Resource Management (HRM) Software of Company XYZ.

To do specific task please choose one of the following commands.

1. Add new employee

2. Delete employee information

3. Update employee information

4. Quit

Please enter the related number of your requested command?

Consider the following part of Person class which is containing some data members in it. Class Person should include following private fields:

• FirstName (String)

• LastName (String)

• PersonalID (Integer)

• Salary (Double)

Class Person should have public member functions for setting and getting the private fields. Member functions should have the following naming style:

• set_FieldName()

• get_FieldName() The field “PersonalID” of class Person should be unique and auto-increment with the initial value of 8248001 for the first employee. It means that user should not enter the value for “personalID”. Class HRM should include following private fields:

• Array of employees with the type Person (Private)

• The actual number of employees which is stored in Array of employees(private) Class HRM should include following public member functions:

• AddPerson()

• DeletePerson(…)

• UpdatePerson(…)

CODE:

#include<iostream>
#include<conio.h>
using namespace std;
int id=1234567,i=0;
class Person
{
	private:
		string FirstName;
		string LastName;
		int PersonalId;
		double Salary;
	public:
		void set_FirstName(string fn);
		void set_LastName(string ln);
		void set_PersonalId(int z);
		void set_Salary(double sal);
		string get_FirstName();
		string get_LastName();
		int get_PersonalId();
		double get_Salary();
		
};
class HRM
{
	private:
		Person p[15];
	public:
		void AddPerson();
		void DeletePerson();
		void UpdatePerson();	
};
	void Person::set_FirstName(string fn)
	{
		FirstName = fn;
	}
	void Person::set_LastName(string ln)
	{
		LastName = ln;
	}
	void Person::set_PersonalId(int z)
	{
		PersonalId = z;
	}
	void Person::set_Salary(double sal)
	{
		Salary = sal;
	}
	string Person::get_FirstName()
	{
		return FirstName;
	}
	string Person::get_LastName()
	{
		return LastName;
	}
	int Person::get_PersonalId()
	{
		return PersonalId;
	}
	double Person::get_Salary()
	{
		return Salary;
	}
	void HRM::AddPerson()
	{
		string fn,ln;
		double sal;
		cout<<"\n\n First Name : ";
		cin>>fn;
		p[i].set_FirstName(fn);
		cout<<" Last Name : ";
		cin>>ln;
		p[i].set_LastName(ln);
		p[i].set_PersonalId(id);
		id++;
		cout<<" How much is his/her Salary? =";
		cin>>sal;
		p[i].set_Salary(sal);
		i++;
		cout<<"\n\n New employee information added in the system";
		cout<<"\n\n First Name     Last Name     Personal ID     Salary per year (Rupees)";
		cout<<"\n -----------  ------------- ---------------    -----------------------";
		for(int a=0;a<i;a++)
		{
			cout<<"\n "<<p[a].get_FirstName()<<"          "<<p[a].get_LastName()<<"          "<<p[a].get_PersonalId()<<"               "<<p[a].get_Salary();
		}
	}
	void HRM::DeletePerson()
	{
		int t_id;
		char x;
		cout<<"\n\n ID of Employee to Remove : ";
		cin>>t_id;
		cout<<"\n Do you want to really delete employee (Y,N) : ";
		cin>>x;
		if(x == 'Y' || x == 'y')
		{
			for(int a=0;a<i;a++)
			{
				if(p[a].get_PersonalId() == t_id)
				{
					for(int k=a;k<i;k++)
					{
						p[k].set_FirstName(p[k+1].get_FirstName());
						p[k].set_LastName(p[k+1].get_LastName());
						p[k].set_PersonalId(p[k+1].get_PersonalId());
						p[k].set_Salary(p[k+1].get_Salary());
					}
					cout<<"\n\n Delete employee information from the system";
					i--;
				}
			}
		}
		cout<<"\n\n First Name     Last Name     Personal ID     Salary per year (Rupees)";
		cout<<"\n -----------  ------------- ---------------    -----------------------";
		for(int a=0;a<i;a++)
		{
			cout<<"\n "<<p[a].get_FirstName()<<"          "<<p[a].get_LastName()<<"          "<<p[a].get_PersonalId()<<"               "<<p[a].get_Salary();
		}
	}
	void HRM::UpdatePerson()
	{
		int t_id,x;
		double sal;
		char choice;
		string fn,ln;
		cout<<"\n\n Employee ID for modify information : ";
		cin>>t_id;
		do{
			cout<<"\n\n 1. First Name";
			cout<<"\n 2. Last Name";
			cout<<"\n 3. Salary";
			cout<<"\n\n Number of Field for modify : ";
			cin>>x;
			for(int a=0;a<i;a++)
			{
				if(p[a].get_PersonalId() == t_id)
				{
					if(x == 1)
					{
						cout<<"\n First Name : ";
						cin>>fn;
						p[a].set_FirstName(fn);
					}
					else if(x == 2)
					{
						cout<<"\n Last Name : ";
						cin>>ln;
						p[a].set_LastName(ln);
					}
					else if(x == 3)
					{
						cout<<"\n Salary : ";
						cin>>sal;
						p[a].set_Salary(sal);
					}
					cout<<"\n\n Modify employee information from the system";
				}
			}
			cout<<"\n\n Do you want modify another field (Y,N) : ";
			cin>>choice;
		}while(choice == 'Y' || choice == 'y');
		cout<<"\n\n First Name     Last Name     Personal ID     Salary per year (Rupees)";
		cout<<"\n -----------  ------------- ---------------    -----------------------";
		for(int a=0;a<i;a++)
		{
			cout<<"\n "<<p[a].get_FirstName()<<"          "<<p[a].get_LastName()<<"          "<<p[a].get_PersonalId()<<"               "<<p[a].get_Salary();
		}
	}
main()
{
	HRM obj;
	int choice;
	char x;
	p:
	cout<<"\n\n\t1. Add New Employee";
	cout<<"\n\t2. Delete Employee Information";
	cout<<"\n\t3. Update Employee Information";
	cout<<"\n\t4. Quit";
	cout<<"\n\n\tEnter Your Choice : ";
	cin>>choice;
	switch(choice)
	{
		case 1:
			cout<<"\n\n Enter the information of the new employee";
			do{
				obj.AddPerson();
				cout<<"\n\n Do you want to add another employee (Y,N) : ";
				cin>>x;
			}while(x == 'Y' || x == 'y');
			break;
		case 2:
			obj.DeletePerson();
			break;
		case 3:
			obj.UpdatePerson();
			break;
		case 4:
			exit(0);
		default:
			cout<<"\n\n\tInvalid Value...Please Try Again...";
	}
	goto p;
}

DEMO:

0

GUI Calculator In Python Using Tkinter

GUI Calculator In Python Using Tkinter

Learning Outcomes

  • Implement Tkinter GUI Python Application
  • Implement and utilize widgets
  • Implement Event Handlers
  • Develop logic

Program Overview

GUI Calculator In Python Using Tkinter – Create a basic five-function Calculator using the tkinter module. The calculator should allow
addition, subtraction, multiplication, and division of two numbers along with square root of a
single number (import math to access math.sqrt(value)). It should have an AC button, which
clears all the elements of the calculator as well as an “equals” and a decimal button. Include the
positive/negative which adds a – or removes it from the entered number and a backspace button.
Create your window in the below format (colors you are free to customize):

GUI Calculator In Python Using Tkinter

Look at the following online calculators to get acquainted with the 5-functions of a calculator in
the event you have not used one. It is important that you use one to gain an idea of how it works.
Calculators you use on your phone are far more sophisticated in behavior. Emulate the behavior
found in these online calculators: https://calculator-1.com/ and http://calculator-1.com/simple/

Functionality Requirements

Your Calculator should:

1) Allow users to enter numbers ONLY using buttons
•Number entry is via keyboard is not required
2) Have buttons for Add, Subtract, Multiply, and Divide
• Option1 – Be able to use the text being displayed as number 1. The text entered by
the user after the math operator should be used as number 2.
• Option2 – create a string in your display that is an equation and use eval(formula)
to determine the answer. Example: eval(‘2-1+3*5’) returns 16
3) Have a square root button. Ensure your display has an answer not a formula (perform =
first). Then do math.sqrt(answer) to get the square root and display.
4) Have a Clear button
• Clear resets all previous input
5) Offer the user the ability to use decimals.
• Allows only 1 decimal point in a number (two in a number isn’t valid)
6) Be able to show decimals in results and toggle negative or positive numbers
7) Show accurate results for all five math functions.
8) Be able to recover and not crash when a number is divided by zero.

CODE – GUI Calculator In Python Using Tkinter:

from tkinter import *
import math
root = Tk()
root.title("CALCULATOR")
root.geometry("420x530")
root.configure(bg = "lightblue")

screen = StringVar()
screen.set('')


# removes the last character of text on screen
def clearScreenByOne():
screenText = screen.get()
screen.set(screenText[:-1])

# clear all screen
def clearScreen():
screen.set(' ')

#This function will handle the button click
def buttonClickHandler(buttonText):
screenText=screen.get()
#if button ± is clicked then multiply the value will -
if buttonText == '±':
screenText = str(-(float(screenText)))
#setting result to screen
screen.set(screenText)
return
#if button sqrt is click then finds squre root of number in screen and set result back to screen
if buttonText == '√':
screenText = str(math.sqrt(float(screenText)))
screen.set(screenText)
return
#if operator is already present at last of text on screen then it will do nothing
if buttonText in ['+','-','x','÷'] and screenText[-1] in ['+','-','x','÷']:
return

#if user tried to type 2 dots
screenText = screenText.replace('..','.')

screenText = screenText + buttonText
screen.set(screenText)


def main():
#get text from screen
screenText = screen.get()
screen.set(' ')
#replaced x wit * and ÷ with / inorder to easily pass to aval function
screenText = screenText.replace('x', '*')
screenText = screenText.replace('÷', '/')
try:
#generating result
answer = round(eval(screenText),2)
except:
#if any errorr occurs
answer = "Error"
#setting text to screen
screen.set(str(answer))

def run():
#generates label on window to show output
lbl_outputScreen = Label(root,text="",bg="white",width=18,height=2,font=('Arial','30'),textvariable=screen, anchor='se')
#placing label on screen on row 0 col 0 means on top and giving it space of 4 solumns to file entire width
lbl_outputScreen.grid(row=0,column=0,columnspan=4)

#below generates buttons in form of grid which will call button_clickhandler method when clicked
btn_clearScreenByOne = Button(root,text="➜",bg="lightgrey",fg="black",width = 3,height=1,font=('Arial','25'),command=clearScreenByOne)
btn_plus_minus = Button(root,text="±",bg="lightgrey",fg="black",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('+-'))
btn_sqrt = Button(root,text="√",bg="lightgrey",fg="black",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('√'))
btn_mul = Button(root,bg="orange",fg="black",text="x",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('x'))
btn_clearScreenByOne.grid(row=1,column=1,pady=10)
btn_plus_minus.grid(row=1,column=2,pady=10)
btn_sqrt.grid(row=1,column=3,pady=10)
btn_mul.grid(row=3,column=3,pady=10)

#second row
btn7 = Button(root,bg="grey",fg="black",text="7",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('7'))
btn8 = Button(root,bg="grey",fg="black",text="8",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('8'))
btn9 = Button(root,bg="grey",fg="black",text="9",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('9'))
btn_divide = Button(root,bg="orange",fg="black",text="÷",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('÷'))
btn7.grid(row=2,column=0,pady=10)
btn8.grid(row=2,column=1,pady=10)
btn9.grid(row=2,column=2,pady=10)
btn_divide.grid(row=2,column=3,pady=10)

# The third row
btn4 = Button(root,bg="grey",fg="black",text="4",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('4'))
btn5 = Button(root,bg="grey",fg="black",text="5",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('5'))
btn6 = Button(root,bg="grey",fg="black",text="6",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('6'))
btn_minus = Button(root,bg="orange",fg="black",text="-",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('-'))
btn4.grid(row=3,column=0,pady=10)
btn5.grid(row=3,column=1,pady=10)
btn6.grid(row=3,column=2,pady=10)
btn_minus.grid(row=4,column=3,pady=10)

# Fourth row
btn1 = Button(root,bg="grey",fg="black",text="1",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('1'))
btn2 = Button(root,bg="grey",fg="black",text="2",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('2'))
btn3 = Button(root,bg="grey",fg="black",text="3",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('3'))
btn_add = Button(root,bg="orange",fg="black",text="+",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('+'))
btn1.grid(row=4,column=0,pady=10)
btn2.grid(row=4,column=1,pady=10)
btn3.grid(row=4,column=2,pady=10)
btn_add.grid(row=5,column=3,pady=10)

# The fifth row
btn0 = Button(root,bg="grey",fg="black",text="0",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('0'))
btn_dot = Button(root,bg="grey",fg="black",text=".",width = 3,height=1,font=('Arial','25'),command=lambda: buttonClickHandler('.'))
btn_equal = Button(root,bg="orange",fg="black",text="=",width = 3,height=1,font=('Arial','25'),command=main)
btn_clear = Button(root,text="C",bg = "red",fg = "black",width = 3,height=1,font=('Arial','25'),command=clearScreen)
btn_clear.grid(row=1,column=0,pady=10)
btn0.grid(row=5,column=0,pady=10)
btn_dot.grid(row=5,column=1,pady=10)
btn_equal.grid(row=5,column=2,pady=10)
#calling run method
run()
#showing window until user don't closes it
root.mainloop()

keep visiting : shaadcoding

0

Python Math Quiz Project From Easy To Hardest Mode

python math quiz project

Keywords for python math quiz project

  • python random maths quiz
  • quiz in python
  • how to make a multiple choice quiz in python
  • python quiz code with the score
  • python math example
  • how to generate random maths questions in python
  • python mathematical programming
  • python chapter 5 math quiz

Code

import random

#inut user for levels and number of question per level
levels = int(input("Enter number of levels you want to play : "))
questions = int(input("ENter number of questions per level : "))
#i to checks level
i = 1

#As single digit is between 1 and 9 so start = 1 and end = 9
start = 1
end = 9
#to save score
score = 0
#looping until levels
while i <= levels:
print("level ",i)
j = 1
#looping until questions in each level
for q in range(questions):
#generating two random numbers and random operator from + and -
num1 = random.randint(start,end)
num2 = random.randint(start,end)
operator = random.choice(['+','-'])
#making question as string
questionStatement = str(num1) + operator + str(num2)
#using eval function getting result
result = int(eval(questionStatement))
#showing statement to user and getting user answer
useranswer = int(input(f"Q#{j} {questionStatement} ? "))
#if answer matches result then showing message and giving 1 point else showing right answer
if useranswer == result:
print("You answered correctly...")
score += 1
else:
print("Sorry , you'r answer is wrong,correct is ",result)
#incrementing to increase question by 1
j += 1
print()
#for next round let's say round 2 it have to be 2 digit and round 3 3 digit and so on
#so making 1 to 10 and 9 to 99 and then 10 to 100 and 99 to 999 and so on
start = start * 10
end = (end * 10) + 9
i += 1

#finally printing score
print("\n\n")
print("Your score is : ",score)

#Any question or suggestion?
#i will like to answers your query in comments
#Thanks and have a healthy life :)

DEMO

keep visiting : shaadcoding

0

Bank Management System in Python

Bank Management System Project in Python

Today we are going to build console based Bank Management System in Python

SO let get started our project,

Concepts Used:

Modules to imports

from random import randint

Account Class(parent class)

'''parent account class to be extending by three type of
accounts checking,business and saving'''
class Account:
#constructor to initialize class members
def __init__(self,firstName='',lastName='',uid='',address='',accType='',phoneNum='',initialBalance = 0.0):
self.firstName = firstName
self.lastName = lastName
self.uid = uid
self.address = address
self.accType = accType
self.phoneNum = phoneNum
self.initialBalance = initialBalance
def get_firstName(self):
return self.firstName

# setter method
def set_firstName(self, x):
self.firstName = x



def get_lastName(self):
return self.lastName

# setter method
def set_lastName(self, x):
self.lastName = x


def get_uid(self):
return self.uid

# setter method
def set_uid(self, x):
self.uid = x


def get_address(self):
return self.address

# setter method
def set_address(self, x):
self.address = x



def get_accType(self):
return self.accType

# setter method
def set_accType(self, x):
self.accType = x


def get_phoneNum(self):
return self.phoneNum

# setter method
def set_phoneNum(self, x):
self.phoneNum = x


def get_initialBalance(self):
return self.initialBalance

# setter method
def set_initialBalance(self, x):
self.initialBalance = x


def get_age(self):
return self.age

# setter method
def set_age(self, x):
self.age = x

'''This function will save the account holder info according to account type'''
def saveAccount(self):
'''This will check first account type then saves data according to it
It will generated random id and place account type key before it then appends the all user data to file'''
if self.get_accType() == 'c' or self.get_accType() == 'C':
secNum = randint(1000,10000)
secNum = 'che'+str(secNum)
print('your secret key is: ',secNum)
f= open("checkingAccount.txt","a+")
f.write(f"\n{self.get_firstName().replace(' ','_')} {self.get_lastName().replace(' ','_')} {self.get_uid().replace(' ','_')} {self.get_address().replace(' ','_')} {self.get_accType()} {self.get_phoneNum().replace(' ','_')} {secNum}")
f.close()
f1= open("checkingAccountBalance.txt","a+")
f1.write(f"\n{secNum} {self.get_initialBalance()}")
f1.close()
elif self.get_accType() == 's' or self.get_accType() == 'S':
secNum = randint(1000,10000)
secNum = 'sav'+str(secNum)
print('your secret key is: ',secNum)
f= open("savingAccount.txt","a+")
f.write(f"\n{self.get_firstName().replace(' ','_')} {self.get_lastName().replace(' ','_')} {self.get_uid().replace(' ','_')} {self.get_address().replace(' ','_')} {self.get_accType()} {self.get_phoneNum().replace(' ','_')} {secNum}")
f.close()
f1= open("savingAccountBalance.txt","a+")
f1.write(f"\n{secNum} {self.get_initialBalance()}")
f1.close()
elif self.get_accType() == 'b' or self.get_accType() == 'B':
secNum = randint(1000,10000)
secNum = 'bus'+str(secNum)
busiName = input('Enter your Business Name : ')
busiregNum = input('Enter your business registration number : ')
ownerName = input('Enter business owner name : ')
print('your secret key is: ',secNum)
f= open("businessAccount.txt","a+")
f.write(f"\n{self.get_firstName().replace(' ','_')} {self.get_lastName().replace(' ','_')} {self.get_uid().replace(' ','_')} {self.get_address().replace(' ','_')} {self.get_accType()} {self.get_phoneNum().replace(' ','_')} {secNum} {busiName.replace(' ','_')} {busiregNum.replace(' ','_')} {ownerName.replace(' ','_')}")
f.close()
f1= open("businessAccountBalance.txt","a+")
f1.write(f"\n{secNum} {self.get_initialBalance()}")
f1.close()
print(self.get_accType())

#This function will check id id randomly generated already present
def checkDuplication(self):
print(self.get_uid())
if self.get_accType() == 'c' or self.get_accType() == 'C':
with open('checkingAccount.txt','r') as f:
if self.get_uid() in f.read():
return True
elif self.get_accType() == 's' or self.get_accType() == 'S':
with open('savingAccount.txt','r') as f:
if self.get_uid() in f.read():
return True

elif self.get_accType() == 'b' or self.get_accType() == 'B':
with open('businessAccount.txt','r') as f:
if self.get_uid() in f.read():
return True

CheckingAccount class(child class of Account class)

#CheckingAccount class when is child class of Account class                    
class CheckingAccount(Account):
def displayAccount(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
#reading all data from file and matching user secret num to numbers in file,if it finds then it will show their info
f = open('checkingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
accdata = line
find = 1
f1 = open('checkingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
find = 1
if find == 1:
accdata = accdata.split()
name = accdata[0]+' '+accdata[1]
ide = accdata[2]
address = accdata[3].replace('_',' ')
accountType = 'Checking Account'
phone = accdata[5]
pin = accdata[6]
balance = accbalance.split()[-1]
print('Name : '+name)
print('Id : '+ide)
print('Address : '+address)
print('Account Type : ',accountType)
print('Phone Number : ',phone)
print('Balance : ',balance,' AED')

else:
print('No Account Found!')
tr = 1
return tr

def depositMoney(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
'''reading all data from file and matching user secret num to numbers in file,
if it finds then it will ask for amount to deposit,user will enter amount then amount will be replace by adding new amount'''
f = open('checkingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
while True:
try:
f1 = open('checkingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
Balance = float(input('Enter balance to deposit: '))
newbalance = balance + Balance
f1.close()
with open('checkingAccountBalance.txt', 'r') as file :
filedata = file.read()

# Replace the target string
filedata = filedata.replace(str(balance), str(newbalance))

# Write the file out again
with open('checkingAccountBalance.txt', 'w') as file:
file.write(filedata)
print('Amount deposited successfuly!')
break
except ValueError:
print('invalid input!')
else:
print('No Account Found!')
tr = 1
return tr

def withdrawMoney(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
'''reading all data from file and matching user secret num to numbers in file,
if it finds then it will ask for amount to withdraw,user will enter amount then after validation amount will be replace by subtracting new amount'''
f = open('checkingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
while True:
try:
f1 = open('checkingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
Balance = float(input('Enter balance to withdraw: '))
if Balance+100>balance:
print('Balance to withdraw must be less than Available balance(their must be AED 100 Always in Account)')
continue

newbalance = balance - Balance
f1.close()
with open('checkingAccountBalance.txt', 'r') as file :
filedata = file.read()

# Replace the target string
filedata = filedata.replace(str(balance), str(newbalance))

# Write the file out again
with open('checkingAccountBalance.txt', 'w') as file:
file.write(filedata)
print('Amount withdrawn successfuly!')
break
except ValueError:
print('invalid input!')
else:
print('No Account Found!')
tr = 1
return tr
#This method will read balance from account,and calculates 3% interest
def callInterest(self,secNum):
find = 0
accdata = ''
accbalance = ''
balance = 0.0
tr = 1
f = open('checkingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
f1 = open('checkingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
print('your interest per annum is : ',(3/100)*balance,' AED')
tr = 0
else:
print('No Account Found!')
return tr

SavingAccount Class(child class of Account class)

#SavingAccount class when is child class of Account class
class SavingAccount(Account):
#reading all data from file and matching user secret num to numbers in file,if it finds then it will show their info
def displayAccount(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
f = open('savingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
accdata = line
find = 1
f1 = open('savingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
find = 1
if find == 1:
accdata = accdata.split()
name = accdata[0]+' '+accdata[1]
ide = accdata[2]
address = accdata[3].replace('_',' ')
accountType = 'Saving Account'
phone = accdata[5]
pin = accdata[6]
balance = accbalance.split()[-1]
print('Name : '+name)
print('Id : '+ide)
print('Address : '+address)
print('Account Type : ',accountType)
print('Phone Number : ',phone)
print('Balance : ',balance,' AED')
else:
print('No Account Found!')
tr = 1
return tr
def depositMoney(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
'''reading all data from file and matching user secret num to numbers in file,
if it finds then it will ask for amount to deposit,user will enter amount then amount will be replace by adding new amount'''
f = open('savingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
while True:
try:
f1 = open('savingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
Balance = float(input('Enter balance to deposit: '))
newbalance = balance + Balance
f1.close()
with open('savingAccountBalance.txt', 'r') as file :
filedata = file.read()

# Replace the target string
filedata = filedata.replace(str(balance), str(newbalance))

# Write the file out again
with open('savingAccountBalance.txt', 'w') as file:
file.write(filedata)
print('Amount deposited successfuly!')
break
except ValueError:
print('invalid input!')
else:
print('No Account Found!')
tr = 1
return tr

def withdrawMoney(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
'''reading all data from file and matching user secret num to numbers in file,
if it finds then it will ask for amount to withdraw,user will enter amount then after validation amount will be replace by subtracting new amount'''

f = open('savingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
while True:
try:
f1 = open('savingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
Balance = float(input('Enter balance to withdrawn: '))
if Balance+1000>balance:
print('Balance to withdraw must be less than Available balance(their must be AED 100 Always in Account)')
continue

newbalance = balance - Balance
f1.close()
with open('savingAccountBalance.txt', 'r') as file :
filedata = file.read()

# Replace the target string
filedata = filedata.replace(str(balance), str(newbalance))

# Write the file out again
with open('savingAccountBalance.txt', 'w') as file:
file.write(filedata)
print('Amount withdrawn successfuly!')
break
except ValueError:
print('invalid input!')
else:
print('No Account Found!')
tr = 1
return tr
#This method will read balance from account,and calculates 7% interest
def callInterest(self,secNum):
find = 0
accdata = ''
accbalance = ''
balance = 0.0
tr = 1
f = open('savingAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
f1 = open('savingAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
print('your interest per annum is : ',(7/100)*balance,' AED')
tr = 0
else:
print('No Account Found!')
return tr

BusinessAccount Class(child class of Account class)

#BusinessAccount class when is child class of Account class
class BusinessAccount(Account):
#reading all data from file and matching user secret num to numbers in file,if it finds then it will show their info
def displayAccount(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
f = open('businessAccount.txt','r')
for line in f.readlines() :
if secNum in line :
accdata = line
find = 1
#print(accdata)
f1 = open('businessAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
find = 1

if find == 1:
accdata = accdata.split()
name = accdata[0]+' '+accdata[1]
ide = accdata[2]
address = accdata[3].replace('_',' ')
accountType = 'Business Account'
phone = accdata[5]
bname = accdata[6]
brn = accdata[7]
bon = accdata[8]
balance = accbalance.split()[-1]
print('Name : '+name)
print('Id : '+ide)
print('Address : '+address)
print('Account Type : ',accountType)
print('Phone Number : ',phone)
print('Balance : ',balance,' AED')
print('Business Name : ',bname)
print('Business Registration Number : ',brn)
print('Business owner Name : ',bon)
else:
print('No Account Found!')
tr = 1
return tr
def depositMoney(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
'''reading all data from file and matching user secret num to numbers in file,
if it finds then it will ask for amount to deposit,user will enter amount then amount will be replace by adding new amount'''
f = open('businessAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
while True:
try:
f1 = open('businessAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
Balance = float(input('Enter balance to deposit: '))
newbalance = balance + Balance
f1.close()
with open('businessAccountBalance.txt', 'r') as file :
filedata = file.read()

# Replace the target string
filedata = filedata.replace(str(balance), str(newbalance))

# Write the file out again
with open('businessAccountBalance.txt', 'w') as file:
file.write(filedata)
print('Amount deposited successfuly!')
break
except ValueError:
print('invalid input!')
else:
print('No Account Found!')
tr = 1
return tr


def withdrawMoney(self,secNum):
find = 0
accdata = ''
accbalance = ''
tr = 0
'''reading all data from file and matching user secret num to numbers in file,
if it finds then it will ask for amount to withdraw,user will enter amount then after validation amount will be replace by subtracting new amount'''
f = open('businessAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
while True:
try:
f1 = open('businessAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
Balance = float(input('Enter balance to withdrawn: '))
if Balance+2000>balance:
print('Balance to withdraw must be less than Available balance(their must be AED 100 Always in Account)')
continue

newbalance = balance - Balance
f1.close()
with open('businessAccountBalance.txt', 'r') as file :
filedata = file.read()

# Replace the target string
filedata = filedata.replace(str(balance), str(newbalance))

# Write the file out again
with open('businessAccountBalance.txt', 'w') as file:
file.write(filedata)
print('Amount withdrawn successfuly!')
break
except ValueError:
print('invalid input!')
else:
print('No Account Found!')
tr = 1
return tr
#This method will read balance from account,and calculates 3% interest
def callInterest(self,secNum):
find = 0
accdata = ''
accbalance = ''
balance = 0.0
tr = 1
f = open('businessAccount.txt','r')
for line in f.readlines() :
if secNum in line :
find = 1
if find == 1:
f1 = open('businessAccountBalance.txt','r')
for line in f1.readlines() :
if secNum in line :
accbalance = line
balance = float(accbalance.split()[-1])
print('your interest per annum is : ',(3/100)*balance,' AED')
tr = 0
else:
print('No Account Found!')
return tr

main method to start execution

def main():
ch=''
num=0
#creating files to read and write data
f1 = open("checkingAccountBalance.txt", "a+")
f2 = open("savingAccountBalance.txt", "a+")
f3 = open("businessAccountBalance.txt", "a+")
f4 = open("checkingAccount.txt", "a+")
f5 = open("savingAccount.txt", "a+")
f6 = open("businessAccount.txt", "a+")
while ch != '6':
#display menu
print("MAIN MENU")
print("1. OPEN ACCOUNT")
print("2. DISPLAY AMOUNT")
print("3. DEPOSIT AMOUNT")
print("4. WITHDRAW AMOUNT")
print("5 CHECK INTEREST")
print("6. EXIT")
print("\tSelect Your Option (1-6) ")
ch = input()
if ch == '1':
try:
#user will enter required data to open account
initialBalance = 0.0
firstName = input('Enter your first name :')
lastName = input('Enter your last name :')
uid = input('Enter your id number :')
address = input('Enter your address: ')
while True:
accType = input('Enter your Account Type:[c = Checking Account,s = Saving Account,b = Business Account] ')
if accType == 'c' or accType == 'C' or accType == 's' or accType == 'S' or accType == 'b' or accType == 'B':
break
else:
print('invalid Account Type!')
print("Enter 'c' = Checking Account,'s' = Saving Account,'b' = Business Account")
continue
phoneNum = input('Enter your Phone Number :')
#loop will continues untill user enter valid amount
while True:
try:
initialBalance = float(input('Enter intial balance(AED) : '))
if accType == 'c' or accType == 'C':
if initialBalance<100:
print('balance should be greater than 100')
continue
else:
break
elif accType == 's' or accType == 'S':
if initialBalance<1000:
print('balance should be greater than 1000')
continue
else:
break
elif accType == 'b' or accType == 'B':
if initialBalance<2000:
print('balance should be greater than 2000')
continue
else:
break


except ValueError:
print('invalid input!')
if not firstName or not lastName or not uid or not address or not accType or not phoneNum or not initialBalance:
print('Fill all required feilds!')
raise ValueError
input('Enter to continue... ')
a = Account(firstName,lastName,uid,address,accType,phoneNum,initialBalance)
if a.checkDuplication():
print(f'Account with id number {uid} already exist')
continue
a.saveAccount()
except ValueError:
print('invalid input!')
#this will display account of user after user will enter its secret number
elif ch == '2':
tryi = 3
tr = 1
while tryi>0:
secNum = input('Enter your secret Number :')
secNum = secNum.lower()
if secNum[0] == 'c':
c = CheckingAccount()
tr = c.displayAccount(secNum)
elif secNum[0] == 's':
c = SavingAccount()
tr = c.displayAccount(secNum)
elif secNum[0] == 'b':
c = BusinessAccount()
tr = c.displayAccount(secNum)
else:
print('invalid Number!')
if tr == 0:
break
elif tr == 1:
tryi -= 1
if tryi == 0:
print('3 tries done!')
#this will deposit money after user will enter its secret number
elif ch == '3':
tryi = 3
tr = 1
while tryi>0:
secNum = input('Enter your secret Number :')
secNum = secNum.lower()
if secNum[0] == 'c':
c = CheckingAccount()
tr = c.depositMoney(secNum)
elif secNum[0] == 's':
c = SavingAccount()
tr = c.depositMoney(secNum)
elif secNum[0] == 'b':
c = BusinessAccount()
tr = c.depositMoney(secNum)
else:
print('invalid Number!')
if tr == 0:
break
elif tr == 1:
tryi -= 1
if tryi == 0:
print('3 tries done!')

#this will withdraw money after user will enter its secret number
elif ch == '4':
tryi = 3
tr = 1
while tryi>0:
secNum = input('Enter your secret Number :')
secNum = secNum.lower()
if secNum[0] == 'c':
c = CheckingAccount()
tr = c.withdrawMoney(secNum)
elif secNum[0] == 's':
c = SavingAccount()
tr = c.withdrawMoney(secNum)
elif secNum[0] == 'b':
c = BusinessAccount()
tr = c.withdrawMoney(secNum)
else:
print('invalid Number!')
if tr == 0:
break
elif tr == 1:
tryi -= 1
if tryi == 0:
print('3 tries done!')
break
#this will calculate interest rate after user will enter its secret number
elif ch == '5':
tryi = 3
tr = 1
while tryi>0:
secNum = input('Enter your secret Number :')
secNum = secNum.lower()
if secNum[0] == 'c':
c = CheckingAccount()
tr = c.callInterest(secNum)
#print(tr)
elif secNum[0] == 's':
c = SavingAccount()
tr = c.callInterest(secNum)
elif secNum[0] == 'b':
c = BusinessAccount()
tr = c.callInterest(secNum)
else:
print('invalid Number!')
if tr == 0:
break
elif tr == 1:
tryi -= 1
if tryi == 0:
print('3 tries done!')
break

Finally calling main method

if __name__=='__main__':
main()

keep visiting : shaadcoding

2

Tic Tac Toe GUI based game in python Tkinter

tic tac toe using python tkinter module gui based

topic – tic toe game in python tkinter

Learning Outcomes

  • Implement Tkinter GUI Python Application
  • Implement and utilize widgets
  • Develop logic

Program Overview – tic toe game in python tkinter

Your task is to build the game Tic Tac Toe in a GUI application. The form consists of 9 buttons that each player takes turns clicking trying to mark 3 in a row. Player 1 goes first and will mark a button with an X. Next Player 2 takes a turn marking a button with an O. The winner is the first to get 3 marks in a row, column, or diagonal. If all 9 buttons are marked and no winner, declare a message which is a tie. After a game (win or tie), reset the board and start over with player 1’s turn.

It is recommended to use functions to keep your code to a minimum.

tic tac toe python code for beginners continue…

Functionality Requirements

Your game should:

  1. Create a GUI that has 9 buttons. Consider ways to store the buttons in a way that allow you to access them and modify the buttonObject.config(text=’X or O’) field to Mark the button for player 1 or 2. If you were to store all button in a structure that has an index of some kind you could easily determine which button is being clicked. You’ll need some way to know the button that was clicked was the upper left which is index 0 (this is an example).
  2. Create a function to link the click event for all buttons. This event handler must be invoked when any of the 9 buttons are clicked and I suggest using a lambda to allow you the ability to pass data to indicate which button was pressed similar to how you did the calculator. Follow the provided psuedo-code to complete the code. Declare variables for the needed information. The process of the game is players alternate turns clicking a button (player 1 goes first and marks X while player 2 marks O). Each button click is the exact same logic which follows:
    • Determine which player is taking a turn (clicking the button)
      • If player 1, change the button text to X and state to DISABLED
      • If player 2, change the button text to O and state to DISABLED
    • Change Players alternating players each turn
    • Keep a count of the number of turns taken place because only 9 turns are possible at which point you have a cats game or tie.
  3. Create a function check_for_winner. Complete the following:
    • Create a decision to check for all possible winning combinations.
    • Things to consider to perform this operation:
      • Which player are we checking won?
      • Which buttons has this player selected? You could check all buttons for their mark (X or O), or maybe you stored this players marks in a data structure saving a number to specify the button location.
      • Know the winning combinations. Example I could create a number system for the game board like below:
        • 012
        • 345
        • 678
        • So combos are: 012, 036, 048, etc.

Now, does the player your checking have any of these combos, but if you find 1 the game is over.

Note: After each user moves, the program needs to check if the user has won or not. There are 8 ways a user can win. He or she can complete any one of the 3 rows, or the 3 columns, or the 2 diagonals. If the game has been won, as determined by this method, clear_board() and reset the game data to the beginning.

CODE – tic toe game in python tkinter:

import tkinter as tk


player1Color = "tomato"
player2Color = "sea green"
textColorPlayer1 = "sea green"
textColorPlayer2 = "tomato"
labelColor = "orange"
labelTextColor = "blue"
btnResetColor = "black"
btnResetTextColor = "grey"


'''This function will be called when user
click on RESET button
This function will clear all the text on
button and set color to default
outer loop is for rows and while inner loop
is for columns it will reset all 9 buttons'''
def reset():
for i in range(3):
for j in range(3):
board[i][j].configure(text='',
bg="SystemButtonFace")


'''This function will be called when ever user
played any move,it will check if any of
condition is fullfilled or not
if condition is fullfilled then return 1
if still no one has won it will return
0 and if the games draw it will return -1'''
def isWin():
for i in range(3):
if board[i][0]['text'] == board[i][1]['text'] \
== board[i][2]['text'] != '':
return 1
for j in range(3):
if board[0][j]['text'] == board[1][j]['text'] \
== board[2][j]['text'] != '':
return 1
if board[0][0]['text'] == board[1][1]['text'] \
== board[2][2]['text'] != '':
return 1
elif board[0][2]['text'] == board[1][1]['text'] \
== board[2][0]['text'] != '':
return 1
elif EmptyCells() == []:
return 0
else:
return -1


#this function will return empty list of all
# the buttons which are stilled on used by player
def EmptyCells():
h=[]
for i in range(3):
for j in range(3):
#it will check if button has not any text on it
if board[i][j]['text'] == '':
h.append((i,j))
return h

#for first run first player will be given
# character 'O'
player = 'O'

#here's the main flow of game
def main_gameflow(r,c):
#global variable player to
# store currentplayer
#it is global because global
# variable can be access from any where in program
global player
#if current button on board is empty the
# it will add respected text on button i.e: O or X and after move checks if anyone wins

if board[r][c]['text'] == '' and isWin() == -1:
if player == 'O':
board[r][c].configure(text='O',bg = player1Color, fg= textColorPlayer1)
if isWin() == -1:
player = 'X'
winAndTurnLabel.configure(text=("It's X's turn"))
elif isWin() == 1:
winAndTurnLabel.configure(text=("O win"))
elif isWin() == 0:
winAndTurnLabel.configure(text="Draw!")
elif player == 'X':
board[r][c].configure(text='X',bg = player2Color, fg= textColorPlayer2)
if isWin() == -1:
player = 'O'
winAndTurnLabel.configure(text=("It's O's turn"))
elif isWin() == 1:
winAndTurnLabel.configure(text=("X win"))
elif isWin() == 0:
winAndTurnLabel.configure(text="Draw!")

#making Tkinter object
screen=tk.Tk()
#setting screen title
screen.title('Tic Tac Toe')
#creating 3 * 3 matrix
board=[[0,0,0],[0,0,0],[0,0,0]]
#generating buttons with 3 rows and 3 columns and
#each row and columns will contain 3 buttons
for i in range(3):
for j in range(3):
#creating button where command takes an lambda funtion
#means lambda is any funtion which will be exexuted whenever any button is clicked
board[i][j]=tk.Button(text='',font=('normal',60,'normal'),width=4,height=1,command=lambda row = i,col = j: main_gameflow(row,col))
#placing button in grid so their will be no space between buttons
board[i][j].grid(row=i,column=j)

#generating label to tell which player turn and who wins / Draw
winAndTurnLabel=tk.Label(text="It's O's turn",font=('normal',22,'bold')
,bg = labelColor,fg = labelTextColor)
winAndTurnLabel.grid(row=3,column=1)
#Generating Reset button to reset game / board
ResetButton=tk.Button(text='RESET',font=('Courier',18,'bold')
,fg=btnResetTextColor,bg = btnResetColor,command=reset)
ResetButton.grid(row=4,column=1)
screen.mainloop()

DEMO

Tags :

tic toe game in python Tkinter
tic tac toe python tkinter
2 player tic tac toe python beginner

keep visiting : shaadcoding