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)
Related
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.
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)
I have the following code:
def five_numbers():
my_list = []
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
# Here I want to go back to five_numbers() and the number x (for example number 4)
Now I want to check if the input contains any letters. If it has, I want to print a message and then I want to go back to the number that the user was on earlier. I've tried to return five_numbers() but then the user will start from the beginning.
I appreciate all the help.
Add a keyword arg for num and default it to None:
def five_numbers(num=None):
my_list = []
if num is None:
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
else:
# do other stuff with num (4) here...
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
five_numbers(4)
You can use a while loop to keep asking the user for a valid input until the user enters one. You should also make the check function raise an exception instead so the caller can catch the exception and retry the input:
def five_numbers():
my_list = []
for i in range(1, 6):
while True:
user_nr = input("Number " + str(i) + ": ")
try:
check_if_number_is_1_to_25(user_nr)
break
except ValueError as e:
print(str(e))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
raise ValueError('Enter a number between 1 and 25.')
Don't use a for loop, use a while loop with the list length as its condition. Make the check function return a boolean and use it to decide whether to append to the list.
def five_numbers():
my_list = []
while len(my_list) < 5:
user_nr = input("Number {}: ".format(len(my_list)+1))
if check_if_number_is_1_to_25(user_nr):
my_list.append(user_nr)
else:
print("Enter a number between 1 and 25.")
return my_list
def check_if_number_is_1_to_25(number):
return number.isdigit() and (1 <= float(number) <= 25)
I have a problem with my condition. I would like the variable tabPoint to be between 10 and 100.
Here is my code:
def demand(nb):
tabName = [];
tabPoint = [];
for i in range(nb):
tabName.append(raw_input("Name of the jumper " + str(i+1) + " : "))
tabPoint.append(input("1st jump " + tabName [i] + " The number must be between 10 and 100: " ));
if int (tabPoint[i] < 5 ) and int (tabPoint[i] > 100):
tabPoint.append(input("The number must be between 10 and 100 " ));
return tabName, tabPoint;
name, point = demand(3)
print(name, point)
You have misplaced your parentheses. What you want as an int is tabPoint[i], not tabPoint[i] < 5.
So the correct form is
if int(tabPoint[i]) > 5 and int(tabPoint[i]) < 100:
tabPoint.append(input("The number must be between 10 and 100 " ))
You can also use the short version that accomplishes the same:
if 5 < int(tabPoint[i]) < 100:
tabPoint.append(input("The number must be between 10 and 100 "))
Try this:
def demand(nb):
tabName = []
tabPoint = []
for i in range(nb):
tabName.append(input("Name of the jumper "+str(i+1)+": "))
tabPoint.append(0)
# Until a valid entry is made, this prompt will occur
while tabPoint[i] < 10 or tabPoint[i] > 100:
tabPoint[i] = (int(
input("1st jump "+tabName[i]+" The number must be between 10 "
"and 100: ")))
return dict(zip(tabName, tabPoint)) # Returning a dictionary mapping name to point
Say you wanted to print each name and point after this, you could implement something like:
info = demand(3)
for name, point in info.items():
print(f"Name: {name} Point: {point}")
So I am trying to run a program on python3 that asks basic addition questions using random numbers. I have got the program running however, I wanted to know if there was a way I could count the occurrences of "Correct" and "Wrong" so I can give the person taking the quiz some feedback on how they did.
import random
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
else:
print ('Wrong.')
You could use a dict to store counts for each type, increment them when you come across each type, and then access it after to print the counts out.
Something like this:
import random
stats = {'correct': 0, 'wrong': 0}
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
stats['correct'] += 1
else:
print ('Wrong.')
stats['wrong'] += 1
print "results: {0} correct, {1} wrong".format(stats['correct'], stats['wrong'])
import operator
import random
def ask_float(prompt):
while True:
try: return float(input(prompt))
except: print("Invalid Input please enter a number")
def ask_question(*args):
a = random.randint(1,100)
b = random.randint(1,100)
op = random.choice("+-/*")
answ = {"+":operator.add,"-":operator.sub,"*":operator.mul,"/":operator.div}[op](a,b)
return abs(answ - ask_float("%s %s %s = ?"%(a,op,b)))<0.01
num_questions = 5
answers_correct = sum(map(ask_question,range(num_questions)))
print("You got %d/%d Correct!"%(answers_correct,num_questions))