how to make a discord bot calculator - python

so i made some code for a discord bot calculator. it should respond to a command for example calculate 2+2. but well it doesnt work. (im a begginer so the code is probably trash)
if "calculate" in message.content or "Calculate" in message.content:
i = message.content.split("alculate ",1)[1]
number = 0
letter = 'd'
for ii in i:
try:
number == ii
except:
try:
if letter == "*":
number*=float(ii)
print
elif letter == "-":
number -= float(ii)
elif letter == "+":
number += float(ii)
elif letter == "/":
number/=float(ii)
if int(ii) != ii:
ii = letter
except:
try:
if ii == "*":
ii == letter
elif ii == "-":
ii == letter
elif ii == "+":
ii == letter
elif ii == "/":
ii == letter
except:
break
await message.channel.send(number)

Related

The result is not what I expected, python console problem

new to coding, when enter an equation of 1 * 5, I get "You are ...lazy". But I need to get "You are ...very lazy". Can you help me finding the problem?
Expected:
You are ... lazy ... very lazy
5.0
Do you want to store the result? (y / n):
Found:
You are ... lazy
5.0
Do you want to store the result? (y / n):
msg_0 = "Enter an equation"
msg_1 = "Do you even know what numbers are? Stay focused!"
msg_2 = "Yes ... an interesting math operation. You've slept through all classes, haven't you?"
msg_3 = "Yeah... division by zero. Smart move..."
msg_4 = "Do you want to store the result? (y / n):"
msg_5 = "Do you want to continue calculations? (y / n):"
msg_6 = " ... lazy"
msg_7 = " ... very lazy"
msg_8 = " ... very, very lazy"
msg_9 = "You are"
memory = 0
def is_one_digit(v):
v = float(v)
if -10 < v < 10 and v.is_integer():
return True
else:
return False
def check(v1, v2, v3):
msg = ""
if is_one_digit(v1) and is_one_digit(v2):
msg = msg + msg_6
if (v1 == 1 or v2 == 1) and v3 == "*":
msg = msg + msg_7
if (v1 == 0 or v2 == 0) and (v3 == "*" or v3 == "+" or v3 == "-"):
msg = msg + msg_8
if msg != "":
msg = msg_9 + msg
print(msg)
while True:
calc = input(msg_0)
try:
x = calc.split()[0]
oper = calc.split()[1]
y = calc.split()[2]
if x == "M":
x = memory
if y == "M":
y = memory
float(x)
float(y)
if oper in ["+", "-", "*", "/"]:
check(x, y, oper)
if oper == "+":
result = float(x) + float(y)
print(result)
elif oper == "-":
result = float(x) - float(y)
print(result)
elif oper == "*":
result = float(x) * float(y)
print(result)
elif oper == "/":
if float(y) != 0:
result = float(x) / float(y)
print(result)
else:
print(msg_3)
continue
user_input = input(msg_4)
if user_input == "y":
memory = result
user_i = input(msg_5)
if user_i == "y":
continue
elif user_i == "n":
break
else:
user_i = input(msg_5)
elif user_input == "n":
user_i = input(msg_5)
if user_i == "y":
continue
elif user_i == "n":
break
else:
user_i = input(msg_5)
else:
user_input = input(msg_5)
else:
print(msg_2)
except ValueError:
print(msg_1)
continue
You call float(x) and float(y), but this is not saved anywhere, so v1 and v2 will be '1' and '5', instead of 1 and 5.
If you set
x = float(x)
y = float(y)
, it should work.

Doesn't store entered value when runs second time

I made a rock, paper, scissors game.
It works fine, as I wanted to, but it doesn't store entered value when runs second time, how do I fix that.
See the while loop below where the program goes again if the user enters y.
import random
tools =["Rock","Scissors","Paper"]
r = "".join(tools[0])
s = "".join(tools[1])
p = "".join(tools[-1])
def computer_predicion():
computer_pred = random.choice(tools)
return computer_pred
computer = computer_predicion()
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
if my_predicion == "R" or my_predicion == "r":
my_predicion = r
return my_predicion
elif my_predicion == "S" or my_predicion == "s":
my_predicion = s
return my_predicion
elif my_predicion == "P" or my_predicion == "p":
my_predicion = p
return my_predicion
else:
print("Debils ir?")
human=my_predicion()
def game():
message_win = ("You won!")
message_lose = ("You lost!")
message = "Computer:%s\nUser:%s"%(computer, human)
if computer == r and human == r :
print(message+"\nIt's draw")
elif computer == p and human == p:
print(message + "\nIt's draw")
elif computer == s and human == s:
print(message + "\nIt's draw")
elif computer == r and human == p:
print(message+'\n'+message_win)
elif computer == p and human == r:
print(message+'\n'+message_lose)
elif computer == r and human == s:
print(message+'\n'+message_lose)
elif computer == s and human == r:
print(message+'\n'+message_win)
elif computer == p and human == s:
print(message+'\n'+message_win)
elif computer == s and human == p:
print(message+'\n'+message_lose)
else:
pass
c = True
while c: //Here code runs second time if user inputs Y or y.
game()
h = input("Continue?(Y/N):")
if h == "Y" or h == "y":
my_predicion()
computer_predicion()
pass
elif h == "N" or h == "n":
c = False
else:
print("Wrong symbol!")
The value is not being stored in the second loop because
computer = computer_predicion()
human = my_predicion()
are displayed outside of the while loop
Here is your working code, I migrated the two variable assignment inside the while loop
import random
tools =["Rock","Scissors","Paper"]
r="".join(tools[0])
s="".join(tools[1])
p="".join(tools[-1])
def computer_predicion():
computer_pred = random.choice(tools)
return computer_pred
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
if my_predicion=="R" or my_predicion =="r":
my_predicion = r
return my_predicion
elif my_predicion=="S" or my_predicion =="s":
my_predicion = s
return my_predicion
elif my_predicion=="P" or my_predicion =="p":
my_predicion = p
return my_predicion
else:
print("Debils ir?")
def game():
message_win = ("You won!")
message_lose = ("You lost!")
message = "Computer:%s\nUser:%s"%(computer,human)
if computer ==r and human==r :
print(message+"\nIt's draw")
elif computer == p and human == p:
print(message + "\nIt's draw")
elif computer == s and human == s:
print(message + "\nIt's draw")
elif computer == r and human==p:
print(message+'\n'+message_win)
elif computer == p and human==r:
print(message+'\n'+message_lose)
elif computer == r and human==s:
print(message+'\n'+message_lose)
elif computer == s and human==r:
print(message+'\n'+message_win)
elif computer == p and human == s:
print(message+'\n'+message_win)
elif computer == s and human==p:
print(message+'\n'+message_lose)
else:
pass
c=True
while c : #Here code runs second time if user inputs Y or y.
computer = computer_predicion()
human = my_predicion()
game()
h = input("Continue?(Y/N):")
if h=="Y" or h=="y":
pass
elif h=="N" or h=="n":
c=False
else:
print("Wrong symbol!")

Using if statements

I am attempting to make a simple Python code that replaces numbers with roman numerals. In order to do this, I need to get the position of each number to replace it with the roman numeral equivalent. However, my code doesn't seem to work.
number = range(1,21)
number = list(number)
number = str(number)
for i in number:
for x in i:
if i.index(x) == 0:
if x == "1":
x.replace(x, "X")
elif x == "2":
x.replace(x, "XX")
else:
if x == 1:
x.replace(x, "I")
elif x == 2:
x.replace(x, "II")
elif x == 3:
x.replace(x, "III")
elif x == 4:
x.replace(x, "IV")
elif x == "5":
x.replace(x, "V")
elif x == "6":
x.replace(x, "VI")
elif x == "7":
x.replace(x, "VII")
elif x == "8":
x.replace(x, "VIII")
elif x == "9":
x.replace(x, "IX")
else:
x.replace(x, "")
print number
I suspect that it has to do with the way that my if statements work, but I'm not sure. Any advice would be appreciated.
A long sequence of if and elif clauses is usually a sign that one should be using one or more dicts.
numstrings = [str(i) for i in range(1, 100)]
d0 = {'0':'', '1':'I', '2':'II', '3':'III', '4':'IV',
'5':'V', '6':'VI', '7':'VII', '8':'VIII', '9':'IX'}
d10 = {'0':'', '1':'X', '2':'XX', '3':'XXX', '4':'XL',
'5':'L', '6':'LX', '7':'LXXX', '8':'LXXX', '9':'XC'}
for s in numstrings:
if len(s) == 1:
r = d0[s]
elif len(s) == 2:
r = d10[s[0]] + d0[s[1]]
else:
r = '??'
print(r)

Variable not being assigned value when returned from subprogram? Python 3?

I am trying to return a value from my subprogram, but when trying to use the variable in the main program, it comes up with an error saying it has not been assigned a value.
correct = 0
def subprogram():
correct2 = 0
loop = 0
while loop == 0:
loop2 = 0
memberID = input("Please enter your member ID: ")
if memberID == "1495":
print("Login successful!")
loop = 1
correct2 = 1
else:
print("Login unsuccessful.")
while loop2 == 0:
decision = input("<T>ry Again or <E>xit to Menu? ")
if decision == "t" or decision == "T":
print("Ok, restarting.")
print("")
loop2 = 1
elif decision == "e" or decision == "E":
print("Ok, exiting to main menu.")
print("")
loop2 = 1
loop = 1
correct2 = 0
else:
print("-----------------------------------------------------")
print("Sorry, this is not a valid answer. Please try again.")
print("-----------------------------------------------------")
continue
return correct2
#main
while correct == 0:
print ("Are you a member?")
member = input("<Y>es or <N>o? ")
if member == "y":
correct = subprogram()
if correct2 == 0:
correct = 0
elif correct2 == 1:
correct = 1
elif member == "Y":
correct = subprogram()
if correct2 == 0:
correct = 0
elif correct2 == 1:
correct = 1
elif member == "n" or member == "N":
print("Ok, not a problem! Welcome!")
correct = 1
else:
print("-----------------------------------------------------")
print("Sorry, this is not a valid answer. Please try again.")
print("-----------------------------------------------------")
correctVIP = 0
print("END")
How would I fix this error? Thankyou.
In your main while loop you don't define the correct2 variable so it throws an error when you try to do:
if correct2 == 0:
You assign the result of subprogram to correct:
correct = subprogram()
where you probably mean to do:
correct2 = subprogram()

Naughts and crosses in python: scoring not working

I realise that many other people have tried and failed to make naughts and crosses (by looking at the suggested question) but I'm assuming they don't have the same problem as me.
Here is my code:
import random, time, sys
raw3 = ["-", "-", "-"]
raw2 = ["-", "-", "-"]
raw1 = ["-", "-", "-"]
def draw():
str3 = ""
str2 = ""
str1 = ""
for i in raw3:
str3 = (str3 + i + " ")
for i in raw2:
str2 = (str2 + i + " ")
for i in raw1:
str1 = (str1 + i + " ")
str_board = str3+str("\n"*2)+str(str2)+str("\n"*2)+str(str1)
print(str_board)
def playerX_turn():
c_choice_in = input("Type the coordinates in the format y/x\n(e.g. 2/1)")
c_choice_list = list(c_choice_in)
c_choice_x = int(c_choice_list[0]); c_choice_y = int(c_choice_list[2])
print(c_choice_x, c_choice_y)
if c_choice_x == 3 and raw3[c_choice_y - 1] == "-":
raw3[c_choice_y - 1] = "X"
elif c_choice_x == 2 and raw2[c_choice_y - 1] == "-":
raw2[c_choice_y - 1] = "X"
elif c_choice_x == 1 and raw1[c_choice_y - 1] == "-":
raw1[c_choice_y - 1] = "X"
def playerO_turn():
c_choice_in = input("Type the coordinates in the format y/x\n(e.g. 2/1)")
c_choice_list = list(c_choice_in)
c_choice_x = int(c_choice_list[0]); c_choice_y = int(c_choice_list[2])
print(c_choice_x, c_choice_y)
if c_choice_x == 3 and raw3[c_choice_y - 1] == "-":
raw3[c_choice_y - 1] = "O"
elif c_choice_x == 2 and raw2[c_choice_y - 1] == "-":
raw2[c_choice_y - 1] = "O"
elif c_choice_x == 1 and raw1[c_choice_y - 1] == "-":
raw1[c_choice_y - 1] = "O"
def check4win():
winner = None
if winner == None or winner == False and raw3[0] == "X" or raw3[2] == "X" and raw2[1] == "X" and raw1[0] == "X" or raw1[2] == "X":
winner = "playerX"
column_checker = 0
for i in range(0,3):
if winner == None or winner == False and raw3[column_checker] == "X" and raw2[column_checker] == "X" and raw1[column_checker] == "X":
winner = "playerX"
else:
column_checker += 1
if winner == None or winner == False:
if raw3[0] == "X" and raw3[1] == "X" and raw3[2] == "X":
winner = "playerX"
elif raw2[0] == "X" and raw2[1] == "X" and raw2[2] == "X":
winner = "playerX"
elif raw1[0] == "X" and raw1[1] == "X" and raw1[2] == "X":
winner = "playerX"
### ### ### ###
if winner == None or winner == False and raw3[0] == "Y" or raw3[2] == "Y" and raw2[1] == "Y" and raw1[0] == "Y" or raw1[2] == "Y":
winner = "playerY"
column_checker = 0
for i in range(0,3):
if winner == None or winner == False and raw3[column_checker] == "Y" and raw2[column_checker] == "Y" and raw1[column_checker] == "Y":
winner = "playerY"
else:
column_checker += 1
if winner == None or winner == False:
if raw3[0] == "Y" and raw3[1] == "Y" and raw3[2] == "Y":
winner = "playerY"
elif raw2[0] == "Y" and raw2[1] == "Y" and raw2[2] == "Y":
winner = "playerY"
elif raw1[0] == "Y" and raw1[1] == "Y" and raw1[2] == "Y":
winner = "playerY"
### ### ### ###
if winner != None or winner != False:
if winner == "playerX":
print("X won the game!\n(Sorry, O!)")
elif winner == "playerY":
print("Y won the game!\n(Bad luck, X!)")
sys.exit()
def main():
game_over = False
while game_over == False:
playerX_turn()
draw()
check4win()
playerO_turn()
draw()
check4win()
main()
So my first problem is that this is an example of output from it:
>>>
Type the coordinates in the format y/x
(e.g. 2/1)1,1
1 1
- - -
- - -
X - -
X won the game!
(Sorry, O!)
>>>
Which clearly is not correct...
It's probably a stupid mistake somewhere but I'm too lazy to go looking through it properly, but I've had a brief look through the check4win() function, but to no avail.
Another (less important) thing is that I have a feeling this code could be made neater... Maybe something with main()?

Categories