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.
Related
I try to make a calculator but when i run it it just show 0. Why my the result variable doesn't change?
MathSlice = list("1 + 2")
i = 0
Number1 = []
Operation = ""
Number2 = []
Result = 0
while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"):
Number1.append(MathSlice[i])
i += 1
Number1 = ''.join(Number1)
Operation = MathSlice[i]
while not i > len(MathSlice):
Number2.append(MathSlice[i - 1])
i += 1
Number2.pop(1)
Number2 = ''.join(Number2)
if Operation == "+":
Result = int(Number1) + int(Number2)
elif Operation == "-":
Result = int(Number1) - int(Number2)
elif Operation == "*":
Result = int(Number1) * int(Number2)
elif Operation == "/":
Result = int(Number1) / int(Number2)
print(Result)
I expect it to printing 3 but the variable result doesn't change and printing 0.
Changes made: while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"): to while not MathSlice[i] in ("+", "-", "*", "/"):
Code:
MathSlice = list("1 + 2")
#print(MathSlice)
i = 0
Number1 = []
Operation = ""
Number2 = []
Result = 0
while not MathSlice[i] in ("+", "-", "*", "/"):
Number1.append(MathSlice[i])
i += 1
Number1 = ''.join(Number1)
Operation = MathSlice[i]
while not i > len(MathSlice):
Number2.append(MathSlice[i - 1])
i += 1
Number2.pop(1)
Number2 = ''.join(Number2)
if Operation == "+":
Result = int(Number1) + int(Number2)
elif Operation == "-":
Result = int(Number1) - int(Number2)
elif Operation == "*":
Result = int(Number1) * int(Number2)
elif Operation == "/":
Result = int(Number1) / int(Number2)
print(Result) #3
what you have done is assume that or statements only act on the second part of the evaluation, however they act on both. Basically this means you are saying is str(MathSlice[i]) == "+" or "-" == True etc. This then instantly cancels the while not loop as strings with characters evaluate as true in python.
The simple fix is to change your while loop from this:
while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"):
to this
while not str(MathSlice[i]) == "+" or str(MathSlice[i]) == "-" or str(MathSlice[i]) == "/" or str(MathSlice[i]) == "*":
which is unfortunately a little bit uglier but it fixes your problem :)
def add(x, y):
return x + y
def sub(x, y):
return x - y
def multiply(x, y ):
return x * y
def div(x, y):
return x / y
print("Select Operation:")
print("1.add")
print("2.sub")
print("3.multiply")
print("4.div")
choice = input("enter your operation number: ")
a = int(input("enter the first number:"))
b = int(input("enter the second number: "))
if choice == 1:
print(a,"+",b,"=", add(a,b))
elif choice == 2:
print(a,"-",b,"=", sub(a,b))
elif choice == 3:
print(a,"*",b,"=", multiply(a,b))
elif choice == 4:
print(a,"/",b,"=", div(a,b))
else:
print("err")
Pay attention, when inputing something, it's a string.
So, when doing: choice == 1, it tries to do: '1' == 1, which is false
Do:
if choice == '1':
print(a,"+",b,"=", add(a,b))
elif choice == '2':
print(a,"-",b,"=", sub(a,b))
elif choice == '3':
print(a,"*",b,"=", multiply(a,b))
elif choice == '4':
# complete..
i just started learning Python 3. So i learned some basics and tried writing something on my own. Its a little calc, but after the user does its inputs nothing happens, it justs ends. Sorry if this is a very stupid Question. Thanks in advance
print("Welcome")
n1 = float(input("Please insert a number"))
o1 = input("Please insert the operator(+,-,*,/)")
n2 = float(input("Please insert another number"))
def mult(x, y):
z = x * y
return z
def addi(x, y):
z = x + y
return z
def subi(x, y):
z = x - y
return z
def divi(x, y):
if x == 0 or y == 0:
print("Cant divide 0")
elif x == 0 and y == 0:
print("Cant divide 0")
else:
z = x / y
return z
if o1 == "+":
addi(n1, n2)
elif o1 == "-":
subi(n1, n2)
elif o1 == "*":
mult(n1, n2)
elif o1 == "/":
divi(n1, n2)
else:
print("Wrong Operator!")
EDIT: Thanks to all of you, I fixed it and it works. Thanks again.
You're doing the calculations, but not outputting them :
if o1 == "+":
print(addi(n1, n2))
elif o1 == "-":
print(subi(n1, n2))
elif o1 == "*":
print(mult(n1, n2))
elif o1 == "/":
print(divi(n1, n2))
else:
print("Wrong Operator!")
NOTE:
There is a mistake in your divi function, use this instead :
def divi(x, y):
if y == 0:
print("Cant divide by 0")
else:
z = x / y
return z
+ You can just return the result without storing it in a variable :
def mult(x, y):
return x * y
def addi(x, y):
return x + y
def subi(x, y):
return x - y
def divi(x, y):
if y == 0:
print("Cant divide by 0")
else:
return x / y
It works perfectly may be you just want to print the result
Add print
print("Welcome")
n1 = float(input("Please insert a number"))
o1 = input("Please insert the operator(+,-,*,/)")
n2 = float(input("Please insert another number"))
def mult(x, y):
z = x * y
return z
def addi(x, y):
z = x + y
return z
def subi(x, y):
z = x - y
return z
def divi(x, y):
if x == 0 or y == 0:
print("Cant divide 0")
elif x == 0 and y == 0:
print("Cant divide 0")
else:
z = x / y
return z
if o1 == "+":
print(addi(n1, n2))
elif o1 == "-":
print(subi(n1, n2))
elif o1 == "*":
print(mult(n1, n2))
elif o1 == "/":
print(divi(n1, n2))
else:
print("Wrong Operator!")
Output
Welcome
Please insert a number34
Please insert the operator(+,-,*,/)+
Please insert another number23
57.0
You calculates operation results, but use it anyway - so it not changes program state (e.g. not writing in standart output).
See next:
if o1 == "+":
addi(n1, n2) # addi return value not used
elif o1 == "-":
subi(n1, n2) # subi return value not used
elif o1 == "*":
mult(n1, n2) # mult return value not used
elif o1 == "/":
divi(n1, n2) # divi return value not used
else:
print("Wrong Operator!")
As you can see - return values not used.
Let's see functions
def mult(x, y):
z = x * y
return z
def addi(x, y):
z = x + y
return z
def subi(x, y):
z = x - y
return z
def divi(x, y):
if x == 0 or y == 0:
print("Cant divide 0")
elif x == 0 and y == 0:
print("Cant divide 0")
else:
z = x / y
return z
It's just return values, but not output it anyway.
So you need to print return values. E.g. -
if o1 == "+":
print(addi(n1, n2))
elif o1 == "-":
print(subi(n1, n2))
elif o1 == "*":
print(mult(n1, n2))
elif o1 == "/":
print(divi(n1, n2))
else:
print("Wrong Operator!")
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)
i need x to be an integer so my next part of code works, but as soon as i remove quotation marks around 0,1 or 2 where it says "making input readable for computer" i get this error message.
from random import randint
# Input
print("Rock: R Paper: P Scissors: S")
x = input("Please pick your choice: ")
y = randint(0,2)
#Making input readable for computer
if x.lower() == "r":
x = 0;
if x.lower() == "p":
x = "1";
if x.lower() == "s":
x = "2";
print("value entered ", x, "value generated ", y)
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 0 and y == 1:
print("Computer wins!")
if x == 0 and y == 2:
print("You won!")
if x == 1 and y == 0:
print("You won!")
if x == 1 and y == 2:
print("Computer wins!")
if x == 2 and y == 0:
print("Computer wins!")
if x == 2 and y == 1:
print("You won!")
You should be using elif here:
if x.lower() == "r":
x = 0
elif x.lower() == "p":
x = 1
elif x.lower() == "s":
x = 2
Otherwise, all three conditions are evaluated with every run. Meaning, if the first passes, then x will be an integer for the second.
Also, you should write your code like this:
x = x.lower() # Put this up here
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
That way, you don't call str.lower multiple times.
Lastly, Python does not use semicolons.
You are calling x.lower() after you assign x to an integer.
Also, you should probably not use the same variable for the integer and the input string.
With a couple of dictionaries this code will be short and concise:
x_conversion = {'r':0, 'p':1, 's': 2}
x = x_conversion[x.lower()]
or list(in this particular case)
x_conversion=['r', 'p', 's]
x = x_conversion.index(x.lower())
And for winner
winner_choice = {(0,1): 'Computer', (1, 2): 'You', ...}
winner = winner_choice[(x, y)]
Don't forget try/except and you'll have your results in much shorter and more readable code
iCodez answer is the one, but you should just use the strings, like the following, if you are not using the number conversion to factor your print statement, not both.
Edit: Had to change what y was, oops
x = raw_input("Please pick your choice: ").lower()
y = choice(['r','p','s'])
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 'r' and y == 'p':
print("Computer wins!")
elif x == 'r' and y == 's':
print("You won!")
elif x == 'p' and y == 'r':
print("You won!")
elif x == 'p' and y == 's':
print("Computer wins!")
elif x == 's' and y == 'r':
print("Computer wins!")
elif x == 's' and y == 'p':
print("You won!")
Now if you want to go with the convertion to integer then you could just use this:
y = randint(0,2)
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
print ['tie', 'you win', 'they win'][x-y]
And semicolons are not needed in Python, but you can still use them if it makes you comfortable.
Edit: Just for fun.
import random
pick = ['r', 'p', 's']
x = ""
while x not in pick:
x = str(raw_input("r, p, or s? ")).lower()
print ['tie', 'y win', 'y win', 'x win', 'x win'][ord(x)-ord(random.choice(pick))]
Use raw_input() instead of input.
Also this should be:
if x.lower() == "r":
x = "0"