Python Calculator: Several options, changing the number - python

Hello I am new to python and I am trying to do an assignment but I couldn't get the needed output I am supposed to
get. Can any one suggest me what I am missing? Thank you!
Assignment:
The last exercise in this chapter continues with the exercise from the last chapter, the calculator. In this exercise, expand the existing code by implementing the following new features: (A) Calculator does not automatically quit when the result is given, allowing user to do new calculations. The user has to select "6" in the menu to exit the program. (B) The calculator shows the selected numbers in the main menu by printing "Current numbers:" and the user-given input. By selecting "5" in the calculator menu, the user can change the given numbers.
When implemented correctly, the program prints out following:
Again, implement the program within one large while True-segment, which is terminated with break if the user selects the option "6".
Example output
Calculator
Give the first number: 100
Give the second number: 25
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 100 25
Please select something (1-6): 5
Give the first number: 10
Give the second number: 30
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 10 30
Please select something (1-6): 1
The result is: 40
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 10 30
Please select something (1-6): 6
Thank you!
MY code:
print("Calculator")
while True:
selrction={1,2,3,4,5,6,}
value1 = int(input("Give the first number: "))
value2 = int(input("Give the second number: "))
print("(1) +\n(2) -\n(3) *\n(4) /\n(5)Change numbers\n(6)Quit")
print("Current numbers: ",value1,value2)
selection=int(input("Please select something (1-6): "))
if selection==1:
print("The result is: ",(value1+value2))
elif selection==2:
print("The result is: ",(value1-value2))
elif selection==3:
print("The result is: ", (value1*value2))
elif selection==4:
print("The result is: ",(value1/value2))
elif selection==6:
print("Thank you!")
break
elif selection==5:
print("Change numbers")
continue
else:
print("Selection was not correct.")
selection+=1
my output
Calculator
Give the first number: 100
Give the second number: 25
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 100 25
Please select something (1-6): 5
Change numbers
Give the first number: 10
Give the second number: 30
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 10 30
Please select something (1-6): 1
The result is: 40
Give the first number: 6
Give the second number:

You need to use a flag (e.g. promptForNumbers) to determine whether to prompt for the values again in the loop. Set the flag to True at the very start before the loop, and only execute the value capture of inputs value1 and value2 if the flag is True. Once the numbers are captured, set the flag to False. Then, only set the flag to True again when option 5 is selected (change numbers).
Other points of note:
The continue statement is redundant, too, as there's nothing that follows the if/elsif/elsif/../else statement.
selrction={1,2,3,4,5,6,} statement is redundant (and misspelled), as next assignment to selection is another assignment, and there's no use in-between.
selection+=1 is also redundant, as it's not used.
casting input to integer int(input(value)), rather than float float(input(value)), will limit the accuracy of the calculator
changed indentation to be consistent with expected Python format
there's no error handling for division-by-zero processing (so if 0 is entered as the second number, then division / selected, it'll exit with an exception)
So here's the code with changes as described above:
print("Calculator")
# Flag to indicate whether user should be prompted for input numbers
promptForNumbers = True
while True:
if promptForNumbers:
value1 = float(input("Give the first number: "))
value2 = float(input("Give the second number: "))
# Set prompt flag false to prevent re-prompting for numbers upon next loop
promptForNumbers = False
print("(1) +\n(2) -\n(3) *\n(4) /\n(5)Change numbers\n(6)Quit")
print "Current numbers: %s, %s" % (value1, value2)
selection = int(input("Please select something (1-6): "))
if selection == 1:
print("The result is: %s" % (value1 + value2))
elif selection == 2:
print("The result is: %s" % (value1-value2))
elif selection==3:
print("The result is: %s" % (value1*value2))
elif selection==4:
print("The result is: %s" % (value1/value2))
elif selection==6:
print("Thank you!")
break
elif selection==5:
# Set prompt flag so that numbers will be requested upon next loop
promptForNumbers = True
else:
print("Selection was not correct.")

Related

Keep asking for numbers and find the average when user enters -1

number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)

Fixing While Loops Python

We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')

Do-while in Python 3x

Evening Stack Overflow. Im a beginner in Python, which is why i decided to come on here for some help. Specifically, i'm having trouble understanding "do-while loop".
Here is the assignment i where given:
[Design the logic for a program that allows the user to enter a number. The program will display the sum of every number from 1 through the entered number. The program will allow the user to continuously enter numbers until the user enters 0.]
Here is my code without the "Do-while loop":
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display the total \ sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
print ('\nThank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
Works great. Essentially do what i want it to do.
Now, from the assignment......it states:
The program will allow the user to continuously enter numbers until the user enters 0.
So here is my code/attempt for that:
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display \
the total sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
def equation_run(EQ):
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
zero = 0
while zero < user_number:
print (equation_run)
elif zero == user_number:
print ('Thank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
When running this code, i get a syntax error. It highlights the elif part. Ive tried trial-and-error, but cant seem to get it to work. Please help.
Any comments/suggestion would be greatly appreciated. Thank you in advance and good day.
elif comes after an if, not a while. Replace it with a simple if:
while zero < user_number:
...
if zero == user_number:
...
something like:
while True:
number = int(input("Enter a number: "))
if number == 0:
break
print(0.5*number*(number+1))
should work

Collatz sequence ends at 4

I am writing a Collatz sequence program using the practice projects from chapter 3 of Automate the boring stuff with python.
The program outline is:
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return
this value. If number is odd, then collatz() should print and return
3 * number + 1.
Then write a program that lets the user type in an integer and that
keeps calling collatz() on that number until the function returns the
value 1.
My code runs however it stops on 4 rather than 1. For every number I have tried so far the output goes past 1 back to 4.
example output:
6,3,10,5,16,8,4,2,1,4
I am using python 3.4.2
def collatz(number):
if number % 2 == 0:
number = number //2
print(number)
return number
elif number % 2 == 1:
number = 3 * number + 1
print(number)
return number
print ("pick a number:")
while True:
try:
number = int(input())
while number != 1:
number = collatz(number)
collatz(number)
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
The problem is that you call collatz() once more after the loop finishes with 1. Just remove that line, and it works fine.
Also if you move the "pick a number" to the input function, you can avoid the new line after the question and are asked again every time, if you input an invalid value.
Additionally you should also check if the number is greater than or equal to 1, to avoid endless loops. The code to do all that would look like that:
while True:
try:
number = int(input("pick a number: "))
if number < 1:
print("Error: Please enter a integer greater than or equal to 1 ")
continue
while number != 1:
number = collatz(number)
# removed the additional call to collatz
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
def collatz(number):
number = number // 2 if number % 2 == 0 else 3 * number + 1
print(number)
return number
number = int(input("Pick a Number\n"))
while number != 1:
number = collatz(number)
print("Magic! You are down to 1.")

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Categories