This question already has answers here:
mapping functions in dict
(3 answers)
Python Argument Binders
(7 answers)
Closed 1 year ago.
Below is my Code:
def addition(values):
total = 0
for i in values:
total = total + i
return total
def substract(values):
total = values[0]
print(total)
for i in range(1,len(values)):
total = total - values[i]
print(total)
return total
print("Welcome to this code")
print("This code is a simple calculator")
print("--------------------------------")
print("Please select any one")
print("1) Addition\n2) Substraction\n3) Multiplication\n4) Division\n5) Modulation")
choice = -1
while choice < 1 or choice > 5:
try:
choice = int(input("Enter your choice: "))
if choice < 1 or choice > 5:
print("Please enter value between 1 to 5")
except:
print("Enter valid input!")
option = ["Addition", "Substraction", "Multiplication", "Division", "Modulation"]
optionalias = ["add", "subtract", "multiply", "divide", "modulate"]
#print(choice)
#print("You selected " + option[choice-1])
while True:
values = list(map(float, input("Enter values to " + optionalias[choice - 1] + " separated by comma ',': ").split(',')))
if len(values) < 2:
print("Enter atleast 2 values to perform ", option[choice - 1])
continue
if (choice == 4 or choice == 5):
if len(values) > 2:
print("Please enter exactly 2 values for Division/Modulation")
continue
if values[1] == 0:
print("Divisor cannot be Zero (0) !! Please Try again!")
continue
break
operation = {
1: addition(values),
2: substract(values)
}
total = operation.get(choice)
print("Your total is ", str(total))
Please see the result below
result
I selected choice as 1, thus my code should only execute the addition function. But this code is executing even the substraction function as given above in my result. Can someone explain if I am missing something?
operation = {
1: addition(values),
2: substract(values)
}
is defining a dict where the values are the result of calling addition and substract (note: the correct spelling is subtract, no second s). You need to make the values functions to call, not the result of called functions, e.g.:
operation = {
1: addition, # No call parentheses, so it stores the function itself
2: substract
}
total = operation[choice](values) # Look up the function to call and call it
Related
It has been a week since I started to self-study python and I tried making a program that adds or multiplies all natural numbers and the problem is I want to only show the final result of all the sum or product of all natural numbers. How do I do it?
repeat = 'y'
a=0
while repeat.lower() == 'y':
result = 0
choice = 0
i=0
product = 1
num = int(input("Enter the value of n: "))
if num < 1 or num > 100 :
print('must be from 1-100 only')
repeat = input("\nDo you want to try again?Y/N\n>>> ")
continue
print('1. Sum of all natural numbers')
print('2. Product of all numbers')
choice = int(input("Enter choice: "))
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('\nthank you')
break
The program prints you all the numbers because the print statement is in a while loop, so it gets executed with each run of the loop. Just move the print function out of the while.
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
You have two problems. First, your print statements that print the results need to be un-indented by one step, so they are not PART of loop, but execute AFTER the loop. Second, you need to initialize product = 1 after the if choice == 2:. As a side note, you don't need that final while loop. After you have exited the loop, just print('Thanks') and leave it at that.
So the end of the code is:
if choice == 1:
while num > 0 :
result += num
num -= 1
print(' ',result)
if choice == 2:
product = 1
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
print('thank you\n')
I presume you'll learn pretty quickly how to do those with a for loop instead of a while loop.
print("\tWELCOME TO DRY_RUN CLASS ASSAIGNTMENT!\t")
userList = []
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input(print("Enter number",number )))
number = number + 1
userList.append(variable)
else:
print("Number should not be less than or equal to '0'!")
def maxAll():
maxofall = 0
for element in userList:
if element > maxofall:
maxofall = element
print("The maximum number is:", element)
while True:
mainSystem()
askUser = int(input("What do you want to do with the numbers?\n1.Max All\n2.Average\n3.Quit\nYour answer: "))
if askUser == 1:
maxAll()
this is the code i am using right now...
what do i need to fix i am getting an error like this wheni am executing line no. 9
:-
Enter Number whatever the number is
Noneinput starts here
???
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input("Enter number {} : ".format(number) ))
number = number + 1
userList.append(variable)
else:
print("Number should not be less than or equal to '0'!")
Change your function to this.
print() is a function. Which returns nothing (None) in your case.
input() function thinks this None object is worth displaying on console.
Hence None appears on screen before taking any input.
There are a couple of problems:
1)You have a misplaced print() inside input() in your mainSystem() function
2)You probably want to use f-strings to print the right number instead of the string literal 'number'
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input(f"Enter number {number} : "))
number = number + 1
userList.append(variable)
Write a function called random_equation that takes as input a single parameter, the number of operators to generate in the random equation, and returns a string representing a random math equation involving the numbers 1-10 and operators +, -, *.
def random_equation(num):
result = ""
for i in range (num):
number = random.randint(1, 10)
if number == 1:
num_gen = (" 1 ")
elif number == 2:
num_gen = (" 2 ")
elif number == 3:
num_gen = (" 3 ")
elif number == 4:
num_gen = (" 4 ")
elif number == 5:
num_gen = (" 5 ")
elif number == 6:
num_gen = (" 6 ")
elif number == 7:
num_gen = (" 7 ")
elif number == 8:
num_gen = (" 8 ")
elif number == 9:
num_gen = (" 9 ")
else:
num_gen = (" 10 ")
operator = random.randint(1,4)
if operator == 1:
op_gen = (" + ")
elif operator == 2:
op_gen = (" - ")
else:
op_gen = (" * ")
math = result + num_gen + op_gen
I don't really know where to put the [i] to get it to repeat the loop since number is an integer and num_gen is the result
There are several issues here.
Your math gets replaced every time (e.g. "" + " 2 " + " - "), thus you never get to build longer sequences. You want to make result longer in each iteration: result = result + num_gen + op_gen, instead of always creating a new math with an empty result.
You never return anything. You will want to return result when the loop is finished.
You are now generating num numbers and num operators; that will produce equations like 1 + 3 *, which are a bit unbalanced. You will want to put only num - 1 pairs, and then one more number.
There are easier ways to make a string out of a number; str(num) will do what you do in twenty lines, just without the spaces.
With operator from 1 to 4, you will be generating as many * as you do + and - combined. Intentional?
import random
question = str(random.randint(-10,100)) + random.choice(op) + str(random.randint(-10,100)) + random.choice(op) + str(random.randint(-10,100))
q_formatted = question.replace('÷','/').replace('×', '*')
answer = eval(q_formatted)
print(answer)
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I am writing the code for a calculator using python.
loop = 1
while loop == 1: #loop calculator while loop is TRUE
print ("""Options:
Addition 1)
Subtraction 2)
Multiplication 3)
Division 4)
Quit 5)
Reset Sum 6) """) #display calculator's options
(' ') #spacer
choice = input("option: ") #get user input for calculator options
#----------------------------------------------------------------------------Addition
if choice == 1: #check if user wants to add
print (' ') #spacer
print ('Addition Loaded!') #tell the user they are adding
print (' ') #spacer
add1 = int(input('Base Number')) #get value for add1
sum = int(input('Number ta add')) #get value for sum
sum = add1 + sum #make sum equal the sum of add1 and sum
print (str(sum)) #print sum
addloop = 1 #set addloop to TRUE
while addloop == 1: #continue addition while addloop = TRUE
add1 = int(input('Additional number to add')) #get value for add1
if add1 == 0: #check if add1 equals zero
print (' ') #spacer
sum = add1 + sum #make sum equal the sum of add1 and sum
if add1 != 0: #check if add1 is not equal to 0
print (str(sum)) #print sum
if add1 == 0: #check if add1 is equal to 0
print ('Total: ',) #print prefix
print (str(sum)) #print sum
addloop = 0 #set addloop to FALSE
Below the addition section listed here, there is other sections for subtraction, multiplication, etc that use ELIF instead of IF (as they should be?). The problem is, when the user picks an option for the calculator (addition, subtraction...), it instead loops back to the while loop, without it going through any of the IF or ELIF statements. Do IF statements not work inside a WHILE loop?
Here's your problem:
choice = input("option: ")
Under Python 3, this puts a string into choice. You need an integer:
choice = int(input("option: "))
This will raise a ValueError if the user types something which is not an integer. You can catch that with a try/except ValueError block, or you can leave the choice line as it appears in the question and change all your comparisons to look like this:
if choice == "1": # compare to a string instead of an integer
i have no idea why this is broken. Also dont tell me to use python's built in function because this is designed for some practice not to actually be used. It is binary to decimal that is broken. It has a index error with the variable 'index'
print('Please choose from the list below:')
print('')
print('1) Convert from decimal/denary to binary; ')
print('2) Covert from binary to denary/decimal; ') #Main Menu
print('3) Infomation and settings (coming soon);')
print('4) Exit. ')
print('')
menu_choice = str(input('Enter your choice here: ')) #User inputs choice here
if menu_choice == '1':
dec_binary()
elif menu_choice == '2':
binary_dec()
elif menu_choice == '3':
print('By Callum Suttle')
else:
return 'Thank You'
def dec_binary(): #Module 1: decimal to binary
dec = int(input('Enter a number in decimal up to 255: ')) #Checks The number is an ok size, could be made bigger
while dec > 255:
dec = int(input('Enter a number up to 255, no more: '))
power = int(7) #change 7 to make bigger by 1 digit
convert = []
while power > -1: #until power goes below zero
if dec - pow(2, power) >= 0: #if entered number subtract 2 to the power of var-pow returns posotive number
convert.append(1)
power -=1 # add a 1
dec = dec - pow(2, power) >= 0
else:
convert.append(0)#if not add a zero
power -=1
print('')
print(convert) # print completed number
print('')
binary_decimal_converter() #back to main menu
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) != 7: #checks for correct length
l_bi = str(input('Enter a number in binary up to 7 digits, you may add zeros before: '))
power = 7 #size can be increased by using this
index = 0
while index > 6: #until every power has been checked (in reverse order)
if l_bi[index] == '1': #if the digit is equal to 1
anwser += pow(2, power) #add that amount
power -= 1 #take the power to check next #why is this broken
index += 1 # add another index to check previous
else:
power -= 1 #as above
index += 1 #/\
print('')
print(anwser) #prints result
print('')
binary_decimal_converter() #main menu
this doesn't seem right
index = 0
while index > 6: #until every power has been checked (in reverse order)
...
you never enter this loop, do you?
a better loop would be something like
for i, bit in enumerate(l_bi):
answer += int(bit) * pow(2, 7-i)
also, since you're just practicing, you should find a better way to jump from menu to functions and back. you're doing recursive calls, which is a waste of stack, i.e. your functions actually never finish but just call more and more functions.
Some fixes:
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) > 7: # LOOP UNTIL LENGTH IS LESS THAN 7
l_bi = str(input('Enter... : '))
power = len(l_bi) - 1 # directly set the power based on length
index = 0
while index < len(l_bi): # CORRECT LOOP CONDITION