Why is this code showing number 2 multiple times? - python

So I'm trying to make a calculator but when i do plus (also with other things but for example) it does work but after the outcome comes it asks for number 2 again, I just want the code to start again.
this is the plus piece of the code:
q = input(str("Wil je de bewerkingsteken legende zien? (j/n): "))
if q == "J" or q == "j" :
print ("\nplus = + ")
print ("min = -")
print ("maal = X")
print ("delen door = :")
print ("quadrateren = Q")
print ("tot de kracht van = P")
print ("Worteltrekken = W")
print ("Procent = %")
num1 = float(input("\n Nummer 1: "))
bew = input("\n Bewerkingsteken: ")
num1_word = (str(num1))
if bew == "+" :
plus_num2 = input(float("\nNummer 2: "))
plus_num2_con = (str(plus_num2))
plus_out = (num1 + plus_num2)
plus_out1 = (str(plus_out))
print ("\n" + num1_con +" + " + num2_con + " = " + plus_out1)

First, you write the input wrong for plus_num2. Try this;
plus_num2 = float(input("\nNummer 2: "))
Second, you define the number's name different from last print function. Try This;
print ("\n" + num1_word +" + " + plus_num2_con + " = " + plus_out1)
Third, if you want to start the code again you can add while True on first line.

Related

I have problem with 2nd input it show word "None". how delete it

print(input("Enter invoice number :- "))
t=0
for x in range (1,5,1):
p=int(input(print("Enter",x,"st ",end='')))
print(p)
t+=p
print("product",x," price = ",p)
print("Total Bill = ",t)
In the line p=int(input(print("Enter",x,"st ",end=''))), the print function does not return anything so what is is happening is you are printing "Enter 1 st" then printing None as print return None.
To fix:
p=int(input("Enter " + str(x) + " st "))
Change:
p=int(input(print("Enter",x,"st ",end='')))
to:
prompt = "Enter {}st ".format(x)
p = int(input(prompt))
input prints its argument, so you don't need to call print when passing an argument as a prompt. If you do, then print will print it, and will then return None, which input will then print.
This should fix it
print(input("Enter invoice number :- "))
t=0
for x in range(1, 5):
string = "Enter " + str(x) + "st "
p = int(input(string))
print(p)
t+=p
print("product", x, " price = ", p)
print("Total Bill = ",t)

Python tkinter can't use Entry.get() fucntion

So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()

Trouble with restarting a program - Python

I'm trying to make a very simple blackjack game in python and it works well. The problem is that I want to restart it when it finishes, but doesn't restart. Any ideas?
Piece of code
import random
class BlackjackGame():
def __init__(self):
self.randomNumberMachine = random.randint(4,24)
self.randomNumberUser = random.randint(4,24)
self.conditionalBoolean = False
def blackjackMain(self):
self.numberInput = int(input("Introduzca la apuesta "))
while not self.conditionalBoolean:
if self.randomNumberUser > 21:
print("Desgraciadamente has perdido\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
self.numberInput = self.numberInput / 2
if self.numberInput <= 0:
print("Tienes solo 0 euros")
else:
print("Tienes " + str(self.numberInput) + " euros")
self.conditionalBoolean = True
else:
userChoice = int(input(("Tienes " + str(self.randomNumberUser) + "puntos, deseas:\n1)Retirarte\n2)Aumentar\n")))
if userChoice == 1:
if self.randomNumberUser > self.randomNumberMachine or self.randomNumberMachine > 21:
print("Enhorabuena, has ganado\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
self.numberInput = self.numberInput * 2
print("Ahora tienes " + str(self.numberInput) + " euros")
elif self.randomNumberMachine == self.randomNumberUser:
print("Empate\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
else:
print("Desgraciadamente has perdido\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
self.numberInput = self.numberInput / 2
if self.numberInput <= 0:
print("Tienes solo 0 euros")
else:
print("Tienes " + str(self.numberInput) + " euros")
self.conditionalBoolean = True
elif userChoice == 2:
self.aumentPoints = random.randint(2,10)
self.randomNumberUser = self.randomNumberUser + self.aumentPoints
self.blackjackMain()
jugador1 = BlackjackGame()
jugador1.blackjackMain()
The self.numerInput input it keeps asking the same thing and doesn't restart the program.
Inside blackjackMain(self), the variable self.conditionalBoolean is only set to True. When this happens, you while condition is always False and the code inside is not executed anymore.
If you want to enter the while block, you need to set the variable somewhere outside of this block.

How to call a function within a class wit .self in Pyton3

So i've been trying to create a calculator with more complex structure. The problem that am facing is that i'm trying to create a function that calls another function, i know it seems unneccesary but it will be needed in the future. I have a problem calling the function.
class Calculator:
class Variables:
# Start by defining the variables that you are going to use. I created a subclass because I think is better and
# easier for the code-reader to understand the code. For the early stages all variables are going to mainly
# assigned to 0.
n = 0 # n is the number that is going to be used as the main number before making the math calculation
n_for_add = 0 # n_for_add is the number that is going to added to "n" in addition
n_from_add = 0 # n_from_add is the result from the addition
self = 0
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
except ValueError: # if the value is not an integer it will raise an error
print("you must enter an integer!") # and print you this. This will automatically kill the program
self.n = n
self.n_for_add = n_for_add
n_from_add = n + n_for_add # this is actually the main calculation adding n and n_for_add
self.n_from_add = n_from_add
print(str(n) + " plus " + str(n_for_add) + " equals to " + str(n_from_add)) # this will print a nice output
def subtraction():
try:
nu = int(input("enter number: "))
nu_for_sub = int(input("What do you want to take off " + str(nu) + " ? "))
except ValueError:
print("you must enter an integer!")
nu_from_sub = nu - nu_for_sub
print(str(nu) + " minus " + str(nu_for_sub) + " equals to " + str(nu_from_sub))
# this is the same as addition but it subtracts instead of adding
def division():
try:
num = int(input("enter number: "))
num_for_div = int(input("What do you want to divide " + str(num) + " off? "))
except ValueError:
print("you must enter an integer!")
num_from_div = num / num_for_div
print(str(num) + " divided by " + str(num_for_div) + " equals to " + str(num_from_div))
# same as others but with division this time
def multiplication():
try:
numb = int(input("enter number: "))
numb_for_multi = int(input("What do you want to multiply " + str(numb) + " on? "))
except ValueError:
print("you must enter an integer!")
numb_from_multi = numb * numb_for_multi
print(str(numb) + " multiplied by " + str(numb_for_multi) + " equals to " + str(numb_from_multi))
# its the same as others but with multiplication function
def choice(self):
x = self.addition()
self.x = x
return x
choice(self)
Hope it will help you.
Code modified:
class Variables:
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
return n + n_for_add
except ValueError:
# if the value is not an integer it will raise an error
pass
def choice(self):
x = self.addition()
self.x = x
return x
objectVariables = Variables()
print objectVariables.choice()
I hope this it may serve as its starting point:
def div(x, y):
return x / y
def add(x, y):
return x + y
def subs(x, y):
return x - y
def do(operation, x, y):
return operation(x, y)
print do(add, 4, 2)
print do(subs, 4, 2)
print do(div, 4, 2)

Graph results using canvas in tkinter

I have written my code and I want to graph the amount of times each dice is rolled. This isn't working how can I do it. I don't want to use any graphing packages.
import random
import time
name="JORDAN SUMMERS RANDOM NUMBER GENERATOR ASSIGNMENT"
by="## Created by Jordan Summers ##"
date="# 31.03.2015"
symbol="_"*50
bos=""*5
warning = "Please enter a number, i.e. 1. Not 'one'."
information=""" YOU WILL CHOOSE HOW MANY TIMES TO ROLL THE DICE,
ONCE ROLLED THE PROGRAM WILL PRINT THE NUMBERS, THEN IT WILL SORT THE NUMBERS
HIGHEST TO LOWEST. """
print("{:^80}\n{:^80}\n{:^80}\n{:^80}\n{:^80}\n{}".format(name,by,date,warning,symbol,bos,))
rolllist = []
total = 0
dice = int(input("How many times do you want to roll the dice? "))
if dice >50:
print("Please enter a lower number")
else:
for i in range(dice):
rolllist.append (random.randint(1,6))
print ("You rolled a " + str(rolllist[i])) #Here we are adding the results to the list
total = sum(rolllist)
print ("The total of the numbers " + str(total)) #This is calculating the total
rolllist.sort()
print ("numbers sorted " + str(rolllist)) #This is sorting the numbers in order of value
a = rolllist.count(1)
print ("The number 1 occured " + str(a) + " times." + " It's percentage is ") #Line 34 to line 51 are counting how many times a number occured.
percent_1 = ((int(rolllist.count(1))/(dice)))
print(percent_1*100)
b = rolllist.count(2)
print ("The number 2 occured " + str(b) + " times." + " It's percentage is ")
percent_2 = ((int(rolllist.count(2))/(dice)))
print(percent_2*100)
c = rolllist.count(3)
print ("The number 3 occured " + str(c) + " times." + " It's percentage is ")
percent_3 = ((int(rolllist.count(3))/(dice)))
print(percent_3*100)
d = rolllist.count(4)
print ("The number 4 occured " + str(d) + " times." + " It's percentage is ")
percent_4 = ((int(rolllist.count(4))/(dice)))
print(percent_4*100)
e = rolllist.count(5)
print ("The number 5 occured " + str(e) + " times." + " It's percentage is ")
percent_5 = ((int(rolllist.count(5))/(dice)))
print(percent_5*100)
f = rolllist.count(6)
print ("The number 6 occured " + str(f) + " times." + " It's percentage is")
percent_6 = ((int(rolllist.count(6))/(dice)))
print(percent_6*100)
from tkinter import *
root = Tk()
canvas = Canvas(root, width = 640, height = 360, bg = "red")
canvas.pack()
canvas.create_rectangle(1, 360, 50,(a), fill = "black")
canvas.create_rectangle(60,360, 100,(b), fill = "blue")
canvas.create_rectangle(110,360, 150,(c), fill = "yellow")
canvas.create_rectangle(160,360, 200,(d), fill = "white")
canvas.create_rectangle(210,360, 250,(e), fill = "orange")
canvas.create_rectangle(260,360, 300,(f), fill = "pink")
root.mainloop()
What do I do. I want this to graph, what I'm doing should work. I don't understand.
Note: always write clearly what is the problem. Here, I lost some time finding what it was.
So your first reectangle has y-coordinates 360 and a. And a is always small.
Try something like:
canvas = Canvas(root, width = 640, height = 100, bg = "red")
canvas.create_rectangle(1, 100, 50,100 - percent_1 *100, fill = "black")

Categories

Resources