I have the following code:
import math
q = input("Is there a square root in the function? (y,n) ")
if q == "y":
base = input("base? ")
x_value = input("x? ")
print (math.log(math.sqrt(base),x_value))
else:
base_2 = input("base? ")
x_value_2 = input("x? ")
print (math.log(base_2, x_value_2))
When I run the code, it says that the second value in math.log() must be a number. Shouldn't it work if I just use the variable I assigned to it?
input() returns a string. You should convert the user inputs to floating numbers with the float() constructor:
import math
q = input("Is there a square root in the function? (y,n) ")
if q == "y":
base = float(input("base? "))
x_value = float(input("x? "))
print (math.log(math.sqrt(base),x_value))
else:
base_2 = float(input("base? "))
x_value_2 = float(input("x? "))
print (math.log(base_2, x_value_2))
Related
I want this code to repeat from the top. Im trying to build a calculator app and when I say "Do you want to continue (y) or go back to home (n): " I want it so that if the user says "n" then it will start the code from the beggining. Here is the code I want to do this in.
# Importing stuff
import math
import random
import time
import numpy as np
def startup():
global ask
print("Welcome to this math python program")
ask = input(
"Do you wnat to solve 1, add, 2, subtract, 3, multiply, divide, or 5 other complex problems? (answer with 1, 2, 3, 4, or 5: "
)
startup()
# Some stuff to make it look better
print(" ")
print(" ")
def add():
print("Addition")
num1 = int(input("First number: "))
num2 = int(input("Second Number: "))
num = num1 + num2
print("The answer is " + str(num))
# Subtract
def subtract():
print("Subtraction")
num3 = int(input("First number: "))
num4 = int(input("Second Number: "))
num5 = num3 - num4
print("The answer is " + str(num5))
print(" ")
def multiply():
print("Multiplication")
num6 = int(input("First number: "))
num7 = int(input("Second Number: "))
num8 = num6 * num7
print("The answer is " + str(num8))
print(" ")
def divide():
print("Division")
num9 = int(input("First number: "))
num10 = int(input("Second Number: "))
num11 = num9 / num10
print("The answer is " + str(num11))
print(" ")
def squareRoot():
print("Square Root")
asksqrt = int(
input("What number would you like to find the square root of: "))
answer1 = math.sqrt(asksqrt)
print("The square root of " + str(asksqrt) + " is: " + str(answer1))
print(" ")
def cubeRoot():
print("Cube root")
num12 = int(input("What number do you want to find the cube root of: "))
cube_root = np.cbrt(num12)
print("Cube root of ", str(num12), " is ", str(cube_root))
print(" ")
def exponent():
print("Exponents")
num13 = int(input("First you are going to tell me the number: "))
num14 = int(input("Next you are going to tell me the exponent: "))
num15 = num13**num14
print(str(num13) + " to the power of " + str(num14) + " is " + str(num15))
print(" ")
# While loops
while ask == "1":
print(" ")
add()
ask4 = input("Do you want to continue (y) or go back to home (n): ")
while ask4 == "y":
add()
while ask == "2":
print(" ")
subtract()
ask5 = input("Do you want to continue (y) or go back to home (n): ")
while ask5 == "y":
add()
while ask == "3":
print(" ")
multiply()
ask6 = input("Do you want to continue? (y/n) ")
while ask6 == "y":
add()
while ask == "4":
print(" ")
divide()
ask7 = input("Do you want to continue (y) or go back to home (n): ")
while ask7 == "y":
add()
while ask == "5":
ask2 = input(
"Do you want to do a 1, square root equation, 2, cube root equation, or 3 an exponent equation? (1, 2, 3): "
)
print(" ")
while ask2 == "1":
print(" ")
squareRoot()
ask8 = input("Do you want to continue (y) or go back to home (n): ")
while ask8 == "y":
add()
while ask2 == "2":
print(" ")
cubeRoot()
ask9 = input("Do you want to continue (y) or go back to home (n): ")
while ask9 == "y":
add()
while ask2 == "3":
print(" ")
exponent()
ask10 = input("Do you want to continue (y) or go back to home (n): ")
while ask10 == "y":
add()
I'm a begginer so I dont know a lot. If you could tell me what I can do better that would be much appreciated.
In this case, it's good to take a step back and think of what your main entrypoint, desired exit scenario and loop should look like. In pseudo-code, you can think of it like this:
1. Introduce program
2. Ask what type of calculation should be conducted
3. Do calculation
4. Ask if anything else should be done
5. Exit
At points 2 and 4, your choices are either exit program or do a thing. If you want to 'do a thing' over and over, you need a way of going from 3 back into 2, or 4 back into 3. However, steps 2 and 4 are basically the same, aren't they. So let's write a new main loop:
EDIT: Decided to remove match/case example as it's an anti-pattern
if __name__ == "__main__": # Defines the entrypoint for your code
current_task = 'enter'
while current_task != 'exit':
current_task = ask_user_for_task() # The user will input a string, equivalent to your startup()
if current_task == 'add': # If its 'add', run add()
add()
elif current_task == 'subtract':
subtract()
else:
current_task = 'exit' # If its 'exit' or anything else not captured in a case, set current_task to 'exit'. This breaks the while loop
ask_user_for_task() will be an input() call where the user gives the name of the function they want to execute:
def ask_user_for_task():
return input("Type in a calculation: 'add', 'subtract', ...")
This answer is not perfect - what if you don't want to exit if the user accidentally types in 'integrate'. What happens if the user types in "Add", not 'add'? But hopefully this gives you a starting point.
What you want to do can be greatly simplified. The number you choose correlates to the index of the operation in funcs. Other than that, the program is so simple that each part is commented.
Using this method eliminates the need for excessive conditions. The only real condition is if it is a 2 argument operation or a 1 argument operation. This is also very easily extended with more operations.
import operator, math, numpy as np
from os import system, name
#SETUP
#function to clear the console
clear = lambda: system(('cls','clear')[name=='posix'])
"""
this is the index in `funcs` where we switch from 2 arg operations to 1 arg operations
more operations can be added to `funcs`
simply changing this number accordingly will fix all conditions
"""
I = 6
"""
database of math operations - there is no "0" choice so we just put None in the 0 index.
this tuple should always be ordered as:
2 argument operations, followed by
1 argument operations, followed by
exit
"""
funcs = (None, operator.add, operator.sub, operator.mul, operator.truediv, operator.pow, math.sqrt, np.cbrt, exit)
#operation ranges
twoarg = range(1,I)
onearg = range(I,len(funcs))
#choice comparison
choices = [f'{i}' for i in range (1,len(funcs)+1)]
#this is the only other thing that needs to be adjusted if more operations are added
menu = """
choose an operation:
1:add
2:subtract
3:multiply
4:divide
5:exponent
6:square root
7:cube root
8:quit
>> """
#IMPLEMENT
while 1:
clear()
print("Supa' Maffs")
#keep asking the same question until a valid choice is picked
while not (f := input(menu)) in choices: pass
f = int(f)
#vertical space
print("")
if f in twoarg: x = (int(input("1st number: ")), int(input("2nd number: ")))
elif f in onearg: x = (int(input("number: ")), )
else : funcs[f]() #exit
#unpack args into operation and print results
print(f'answer: {funcs[f](*x)}\n')
input('Press enter to continue')
if you want to, you can see the code below:
while(input("want to continue (y/n)?") == 'y'):
operation = input("operation: ")
num_1 = float(input("first num: "))
num_2 = float(input("second num: "))
match operation:
case "+":
print(num_1 + num_2)
case "-":
print(num_1 - num_2)
case "*":
print(num_1 * num_2)
case "/":
print(num_1 / num_2)
case other:
pass
make sure you have the version 3.10 or later of python
I wrote a program that draws a convex regular polygon in turtle (given no. of sides and length). I also wanted it to check for invalid inputs, such that it would immediately ask if the user would like to try a different one. Is there a way to check both input's validity in less code, while also accounting for ValueError?
Also, a Terminator error occurs after every successful run. What might be causing it, and is there even a way to fix it when using this import command?
from turtle import *
def inp():
while True:
try:
n = int(input("Enter the number of sides of the polygon: "))
except ValueError:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
continue
else:
print("Goodbye!")
break
if n >= 3:
pass
else:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
inp()
else:
print("Goodbye!")
break
try:
l = float(input("Enter the length of the side in pixels: "))
except ValueError:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
continue
else:
print("Goodbye!")
break
if l > 0:
for i in range(1, n + 1):
forward(l)
left(360/n)
exitonclick()
break
else:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
inp()
else:
print("Goodbye!")
break
inp()
For efficient parameter inputs, here are some steps:
Start with the value as something invalid
Using a while loop, ask the user for valid input
If valid input, exit the loop
In you're code, both parameters have the the same validation check, so you can use a function to check both.
Try this code:
from turtle import *
def validnum(nm):
return str(nm).isdigit() and int(nm) > 0 # integer and greater than zero
def inp():
n = l = '' # both invalid
while not validnum(n): # loop first entry until valid
n = input("Enter the number of sides of the polygon or 'q' to quit: ")
if n == 'q':
print("Goodbye!")
exit()
if not validnum(n):
print("Invalid entry")
while not validnum(l): # loop second entry until valid
l = input("Enter the length of the side in pixels or 'q' to quit: ")
if l == 'q':
print("Goodbye!")
exit()
if not validnum(l):
print("Invalid entry")
n, l = int(n), int(l) # convert entries to integers
for i in range(1, n + 1):
forward(l)
left(360/n)
exitonclick()
inp()
Since both parameters have the same validation and only differ in the message prompt, you can make your code even more compact by putting the prompts in a list.
from turtle import *
def validnum(nm):
return str(nm).isdigit() and int(nm) > 0 # integer and greater than zero
def inp():
lstinp = ['',''] # both invalid
lstmsg = ['Enter the number of sides of the polygon', 'Enter the length of the side in pixels'] # both msgs
for i in range(len(lstinp)): # each input value
while not validnum(lstinp[i]): # loop until valid entry
lstinp[i] = input(lstmsg[i] + " or 'q' to quit: ") # msg
if lstinp[i] == 'q':
print("Goodbye!")
exit()
if not validnum(lstinp[i]):
print("Invalid entry")
n, l = int(lstinp[0]), int(lstinp[1]) # convert entries to integers
for i in range(1, n + 1):
forward(l)
left(360/n)
exitonclick()
inp()
I did not receive any errors when running the code.
There is no error but there is a problem that process is not defined, why?
And how can it be defined to make the program work?
I mean how can I use class process outside the class?
class Process:
def convert1(self,typedkm):
meter = typedkm*1000
return meter
def convert2(self,typedkm):
kilometer = typedm/1000
return kilometer
def menu():
ask = None
while ask != 'q':
print('KM TO M Convertor Menu')
print('a) KM To M Convertor')
print('b) M To KM Convertor')
print('c) Both')
print('q) Quit')
print("\n")
ask = input("Action: ")
if ask == 'a':
try:
typedkm = float(input("Please Enter Kilometers: "))
self.Process.convert1(typedkm)
except:
print("\n")
print("Please Enter Right Digits")
print("\n")
elif ask == 'b':
try:
typedm = float(input("Please Enter Meters: "))
self.Process.convert2(typedm)
except:
print("\n")
print("Please Enter Right Digits")
print("\n")
menu()
Python reads function input() as string.
Before passing it to my function for division, variables are typecasted into int using int().
If one variable is non-int (eg "a") then how to catch it?
def divideNums(x,y):
try:
divResult = x/y
except ValueError:
print ("Please provide only Integers...")
print (str(x) + " divided by " + str(y) + " equals " + str(divResult))
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
divideNums (int(firstVal), int(secondVal))
if __name__ == "__main__":
main()
How to handle typecast of firstVal / secondVal ?
You can use isdigit function to check if the input values are integer or not
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
if firstVal.isdigit() and secondVal.isdigit():
divideNums (int(firstVal), int(secondVal))
else:
print ("Please provide only Integers...")
You are right about using a try/except ValueError block, but in the wrong
place. The try block needs to be around where the variables are converted to
integers. Eg.
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
try:
firstVal = int(firstVal)
secondVal = int(secondVal)
except ValueError:
# print the error message and return early
print("Please provide only Integers...")
return
divideNums (firstVal, secondVal)
I'm a newbie in Python3 coding and I have a problem here.
In line 14, I intended to end this program by printing "Thank you! Goodbye" at the part where you answer "n" to "try again?". However, it turned out that I would start all over again even if I've inserted "break" under it. Now, the only solution I can come up is to end the whole program with sys.exit(0), but I don't consider it an ideal solution since it just closes the whole program down.
import sys
while True:
x=int(input("Enter the coins you expected="))
f=int(input("Enter first coin="))
while f!=1 and f!=5 and f!=10 and f!=25:
print("invalid number")
f=int(input("Enter first coin="))
if x>f:
while x>f:
n=input("Enter next coin=")
if not n:
print("Sorry-you only entered",f,"cents")
again=input("Try again (y/n)?=")
if again=="y":
True
elif again=="n":
print("Thank you, goodbye!")
sys.exit(0)
break
while int(n)!=1 and int(n)!=5 and int(n)!=10 and int(n)!=25:
print("invalid number")
n=input("Enter next coin=")
f=f+int(n)
Replace your whole code with this:
import sys
Stay = True
while Stay:
x = int(input("Enter the coins you expected = "))
f = int(input("Enter first coin = "))
while f != 1 and f != 5 and f != 10 and f != 25:
f = int(input("Invalid number entered./nEnter first coin = "))
while x > f and Stay:
n = input("Enter next coin = ")
if not n:
print("Sorry, you only entered " + str(f) + " cents")
again = input("Try again (y/n)?=")
if again == "n":
print("Thank you, goodbye!")
Stay = False
if Stay:
n = int(n)
while n != 1 and n != 5 and n != 10 and n != 25:
print("Invalid number entered.")
n = int(input("Enter next coin = "))
f += n
I made your code more readable and fixed your problem by using a Boolean flag (Stay). This basically means that the program runs while Stay is True, and Stay becomes False when the user enters 'n'.