removes the writing "none" in the python calculator - python

I just created a simple calculator program using python language, but there is a little problem here, when I end the program by inputting number 1, there is always the text none.
The question is how do I get rid of the text none in the program that I created? Because to be honest it is very annoying and will damage the image of the program that I created.
def pilihan():
i = 0
while i == 0:
print('\n\tWelcome to the Simple Calculator Program')
print("\nPlease Select Existing Operations", "\n1. subtraction", "\n2. increase", "\n3. division", "\n4. multiplication")
pilihan2 = int(input('Enter your choice (1/2/3/4): '))
if pilihan2 == 1:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "-", angka2, "=", angka1 - angka2)
elif pilihan2 == 2:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "+", angka2, "=", angka1 + angka2)
elif pilihan2 == 3:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, ":", angka2, "=", angka1 / angka2)
elif pilihan2 == 4:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "x", angka2, "=", angka1 * angka2)
else:
print('Error option, please try again')
continue
print('Program finished, want to restart?')
y = 0
while y == 0:
ulang = int(input('Type 0 for YES and 1 for NO = '))
if ulang == 0:
y += 1
break
elif ulang == 1:
y += 2
break
else:
print('\nThe command you entered is an error, please try again')
continue
if y == 1:
continue
else:
break
print(pilihan())

Change the print(pilihan()) to pilihan(), the return value of pilihan() is None :)

Related

How do I count the number of times an else statement is performed and executed in my program

This program is supposed to do basic calculations by asking the user what type of calculation it wants to perform, then it collects two numbers via the user input and finally performs the calculation by spitting it out before asking you to close it. In the else statement I have here, if the user doesn't input what I want them to, it'll tell them to read more carefully and then it restarts the program. What I want to do is make it so that if the else statement has been executed 3 or 4 times, it will print "I give up" and then it asks the user to type anything to exit the program. I'm a beginner too!
while True:
Pick = input("add, sub, multiply, or divide? :")
# Pick the calculation and then actually do it
if Pick == "add":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
if num_one == 9 and num_two == 10:
print("Twenty one? You stupid.")
Exit = input("Type literally anything to exit ")
break
print("The sum is : ", num_one + num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "sub":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The result is : ", num_one - num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "multiply":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The product is : ", num_one * num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "divide":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The quoitient is : ", num_one / num_two)
Exit = input("Type literally anything to exit ")
break
else:
print("Read and type exactly what it says in the beginning.")
continue
You can simply count how often your loop runs, so before the the loop you would have to add a loop counter, which you increase whenever the last else is called. Within the last else you then simply have to check how high the counter is. See for example:
loop_counter = 0
while True:
...
else:
if loop_counter >= 4:
print("Okay, I give up!")
Exit = input("Type literally anything to exit ")
break
else:
loop_counter = loop_counter +1
print("Read and type exactly what it says in the beginning.")
continue
Hope this helps you
i = 0
while True:
Pick = input("add, sub, multiply, or divide? :")
print("NUMBER OF ELSE : "+str(i))
# Pick the calculation and then actually do it
if Pick == "add":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
if num_one == 9 and num_two == 10:
print("Twenty one? You stupid.")
Exit = input("Type literally anything to exit ")
break
print("The sum is : ", num_one + num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "sub":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The result is : ", num_one - num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "multiply":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The product is : ", num_one * num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "divide":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The quoitient is : ", num_one / num_two)
Exit = input("Type literally anything to exit ")
break
else:
i = i + 1
print("Read and type exactly what it says in the beginning.")
continue
The i variable will count the number of else executed
The rest is your job to do :))
I have removed some code duplication in your code, let me know if you have any questions about what I have done :)
while True:
user_input = input("add, sub, multiply, or divide? :")
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
# Pick the calculation and then actually do it
if user_input == "add":
if num_one == 9 and num_two == 10:
print("Twenty one? You stupid.")
break
print(f"The sum is : {num_one + num_two}")
break
elif user_input == "sub":
print(f"The result is : {num_one - num_two}")
break
elif user_input == "multiply":
print(f"The product is : {num_one * num_two}")
break
elif user_input == "divide":
print(f"The quoitient is : {num_one / num_two}")
break
else:
print("Read and type exactly what it says in the beginning.")
continue
Exit = input("Type literally anything to exit ")
As for the counting, you can set a counter variable before the if statement to 0, and in each elif/else statement, it can be incremented by 1.
So it would look like this:
counter = 0
# in elif/else
counter += 1

Making a Calculator which take input from user until user enter 0 but not working correctly

I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))

Python array loop not looping/validator issues

I'm not exactly sure what I did, but when testing my code it either crashes immediately or gets stuck in a loop. If the first input is a value error (string) and the next is a number it loops as long as the pattern is kept. But if first user entry is int then program crashes. Please any help would be appreciated.
def main():
courseArray = []
keepGoing = "y"
while keepGoing == "y":
courseArray = getValidateCourseScore()
total = getTotal(courseArray)
average = total/len(courseArray)
print('The lowest score is: ', min(courseArray))
print('The highest score is: ', max(courseArray))
print('the average is: ', average)
keepGoing = validateRunAgain(input(input("Do you want to run this program again? (Y/n)")))
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray)
except ValueError:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
counter += 1
return courseArray
def valScore(courseArray):
score = int(courseArray)
if score < 0:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
elif score > 100:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
else:
return courseArray
def validateRunAgain(userInput):
if userInput == "n" or userInput == "N":
print("Thanks for using my program")
return "n"
elif userInput == "y" or userInput == "Y":
return "y"
else:
print("Please enter y or n")
validateRunAgain(input("Do you want to run this program again? (Y/n)"))
return getValidateCourseScore()
def getTotal(valueList):
total = 0
for num in valueList:
total += num
return total
main()
There are too many inputs from the user, so I have cut down on them and changed it.
Here are the sections of your code which I have changed :
Here valScore() I presume validates the input score so, I also gave the index of element to be validated. If it is not valid we remove it from the array and raise ValueError, since it raises error our counter is not updated.
keepGoing = validateRunAgain()
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray, counter - 1)
counter += 1
except ValueError:
print("Please enter a valid score between 0-100")
continue
return courseArray
def valScore(courseArray, counter):
score = courseArray[counter]
if score < 0 or score > 100:
courseArray.pop()
raise ValueError
def validateRunAgain():
while True:
userInput = input("Do you want to run this program again? (Y/n)")
if userInput == 'y' or userInput == 'Y':
return 'y'
elif userInput == 'n' or userInput == 'N':
print('thank you for using my program')
return 'n'
else:
print('Enter Y or N')

Trying to create a confirmation for my code so that it will allow user to change answer

I wanted to add a confirmation for my code so that the user will be able to change their input. I haven't yet added the loop for the question but for some reason when I run this it fails to run def calc() and therefore the calculations I created cannot continue. Help!!
n=0
x=0
while True:
numbers = input("Please enter a, b,c, or, d to select a equation")
if numbers == "a":
n =3
x = 2
break
elif numbers =="b":
n = 4
x = 5
break
elif numbers == "c":
n=5
x=6
break
elif numbers == "d":
n=6
x=7
break
else:
print("Please enter a,b,c, or d")
w = float(input("Please enter weight"))
choice = input("Is this your answer?")
if choice == "yes":
def calc():
if n > w :
weight = (x - w)
weight2 = weight/n
print(weight)
elif w < x:
weight = (w - x)
weight2 = weight/n
print(weight)
calc()
elif choice =="no":
print ("Lets change it")
else:
print("Please respond with 'yes' or 'no'")

Python Prime Numbers Loop

When running this code, I keep having an error. I would like to know what is wrong. The code has to be able to read words and integers and repeat the prompt(Please enter an integer >= 2: ') until it is greater or equal to 2. Thanks in advance.
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not(prime_num.isdigit() and int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
You need to enter the function. This is typically done in python with:
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not(prime_num.isdigit() and int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
if __name__ == "__main__":
prime_number()
Just some advice in general. I would separate the input logic from the prime number calculation logic.
As mentioned by #rpattiso, you are not invoking the method and
You while condition is buggy
This should work:
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not (prime_num.isdigit() and not int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
prime_number()

Categories

Resources