Python: How can this code be made better? - python

WAP to create math application using function concept add minimum 20-25 functionalities different function for each functionalities and user input for selection of any function based on the functionality ask user for the input.
import math
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def floor(x , y):
return x // y
def exponent(x, y):
return x ** y
def remainder(x, y):
return x % y
def square(x, y):
a = x ** 0.5
b = y ** 0.5
return a,b
def swap(x, y):
temp = x
x = y
y = temp
return int(x), int(y)
def factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
def lcm(x, y):
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
def hcf(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
def odd_even(x):
if (x % 2) == 0:
print("{0} is Even".format(x))
else:
print("{0} is Odd".format(x))
def factorial(x):
return math.factorial(x)
def absolute(x):
return math.fabs(x)
def power(x, y):
return math.pow(x, y)
def sin(x):
return math.sin(x)
def cos(x):
return math.cos(x)
def tan(x):
return math.tan(x)
def radian(x):
return math.radians(x)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Floor")
print("6.Exponent")
print("7.Remainder")
print("8.Square")
print("9.Swap")
print("10.Factors")
print("11.LCM")
print("12.HCF")
print("13.Odd or Even")
print("14.Factorial")
print("15.Absolute")
print("16.Power")
print("17.Sin")
print("18.Cos")
print("19.Tan")
print("20.Radian")
choice = input("Enter choice(1-20): ")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
print("Floor:", floor(num1,num2))
elif choice == '6':
print(num1,"** ",num2,"=", exponent(num1,num2))
elif choice == '7':
print(num1," % ",num2,"=", remainder(num1,num2))
elif choice == '8':
print("Square:", square(num1,num2))
elif choice == '9':
print("Swap:", swap(num1,num2))
elif choice == '10':
print(factors(num1))
elif choice == '11':
print("LCM is:", lcm(num1,num2))
elif choice == '12':
print("HCF is:", hcf(num1,num2))
elif choice == '13':
print(odd_even(num1))
elif choice == '14':
print("Factorial is:", factorial(num1))
elif choice == '15':
print("Absolute value is:", absoulute(num1))
elif choice == '16':
print("Power:", power(num1, num2))
elif choice == '17':
print("Sin:", sin(num1))
elif choice == '18':
print("Cos:", cos(num1))
elif choice == '19':
print("Tan:", tan(num1))
elif choice == '20':
print("Radian:", radian(num1))
else:
print("Invalid input")

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.

Giving one hint for each of the tries (guessing number game)

I am making a game which requires the user to enter a number. They get four tries, and if they get the number wrong, they get a hint.
How can I try to give only one hint for each of the four tries the user has to get the number right? For example, after the user gets the first try wrong, I would like the program to display the even_or_odd hint.
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
for x in range(1, 5):
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {x}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number and x == 1: #hint after first attempt
print('You win!')
break
else:
print('Incorrect!')
hint.even_or_odd()
if user_input == new_number and x == 2: #hint after second attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple3to5()
if user_input == new_number and x == 3: #hint after third attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple6to10()
if x == 4:
print('You are out of attempts!')
print(f'The number was {new_number}')
break
You should make one if statement that checks for the correct answer. In the else statement you can use if - elif statements to check for the attempt number.
if user_input == new_number:
print('You win!')
break
else:
print('Incorrect!')
if x == 1:
hint.even_or_odd()
elif x == 2:
hint.multiple3to5()
elif x == 3:
hint.multiple6to10()
else:
print('You are out of attempts!')
print(f'The number was {new_number}')
The reason you see multiple hints on attempt is that for multiple if statements their condition is not true, so their 'else' block is run
Here is a neat trick:
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
self.choices = {
1: self.even_or_odd,
2: self.multiple3to5,
3: self.multiple6to10
}
def run(self,key):
action = self.choices.get(key)
action()
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
else:
print("Well, Not a multple of 3 or 5")
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
else:
print("Well, Not a multple of 6 or 10")
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
print(new_number)
i = 3
win = False
while i >= 1 :
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {i}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number:
print('You win!, Number is: {new_number}')
win = True
break
hint.run(i)
i -= 1
if not win:
print("You lost!")
print(f"Number is {new_number}")

i am not able to calculate my answer and always gives answer err

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..

Python 3 - Why wont my simple program do anything with the input?

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!")

Calculator Loop in Python

Need to add a loop to my calculator by giving the user an option to restart the calculator by putting the code in a while loop with the condition that the input from user should be, 'y' or 'Y'.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Just add somethings to Alex's post
cont = "y"
while cont.lower() == "y":
print("Select operation\n1.Add\n2.Subtract\n3.Multiply\n4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
cont = input("Continue?y/n:")
if cont == "n":
break
Don't really see what the problem is, you can just use another input statement and check the value in the while loop condition...
cont = "y"
while cont == "y" or cont == "Y":
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
cont = raw_input("Continue?y/n:")
you can simply modify your code like this
def continue():
resp = input("Continue ? Y/N ")
if resp == "n" or resp == "N":
return False
return True
while True:
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
if not continue() :
break
you can change the continue function as you like
Here's a while loop example :
Changed
again = "y"
while again:
# ...
#enter your code here
# ...
a = input("do you want to do again (y/Y): ")
if a not in ("y","Y"):
a=""
enter code here
while True:
b = int(input('first num: '))
c = input('operator: ')
d = int(input('second num: '))
if c == '+':
print(b + d)
elif c == '-':
print(b - d)
elif c == '*':
print(b * d)
elif c == '/':
print(b / d)
q = input('do you want to continue?: ')
if q == 'y':
continue
else:
break
Here's another while loop example
menu ="""
0. chose 0 to quit
1. chose 1 to add
2. chose 2 to sub
3. chose 3 to multi
4. chose 4 to div
"""
chose= None
while(chose != 0):
print(menu)
num1 =int(input('first num is: '))
num2 =int(input('second num is: '))
chose= int(input("plz enter your chose: "))
if(chose == 1):
print(num1, " + ",num2," = ",num1+num2)
elif(chose == 2):
print(num1, " - ",num2," = ",num1+num2)
elif(chose == 3):
print(num1, " * ",num2," = ",num1+num2)
elif(chose == 4):
if(num2 == 0):
print("You can not divide by zero")
else:
print(num1, " / ",num2," = ",num1+num2)
else:
print('plz enter a correct option')

Categories