Here is my code as show below:
menu= "Welcome to the menu\n" \
+ "Please select an option below:\n" \
+ ( "0 - Enter a number\n" + "1 - Display current number\n" + \
"2 - Divisibility checking\n" + "3 - Perfect checking\n" + \
"4 - Triangular checking\n" + "5 - Quit\n" )
x == ("")
while option!=5: # <<< Q2
print(menu)
option= int(input("Enter option: "))
if option==0:
x= int(input("What is your number?: "))
while x <=0:
x= int(input("Must be positive, please! What is your number?: ")
elif option==1: # <<< Q1
print("The current number is", x)
elif (x == ""):
print("No number yet - Please input a number and try again.")
x= int(input("What is your number?: "))
Q1:
I was wondering why I kept getting an error message for line 14 of my code, for the second elif statement.
Q2:
I was also wondering how, for my first while statement, I might define "option" for option!=5 and then print the menu if I had not prompted the user to enter an option yet.
Any help on these two cases would really be appreciated.
Thank you.
concerning your second elif-statement, I think you got the nesting wrong.
You have one outer decision tree, where you go through the available option, the tree is:
if option == 0 --> do a
elif option == 1 --> do b
elif option == 2 --> do c and so on
You don't need in inner elif, because it is NOT an else statement to the chosen option. You are just starting a new decision tree (You try to find if x is already assigned and if not ask for a number, otherwise show the number). Therefore the correct code should be:
elif option == 1:
if x == "":
print("No number yet - Please input a number and try again.")
x= int(input("What is your number?: "))
else:
print("The current number is", x)
elif option == 2
--> Handling of option 2
This should work. I took the freedom to put the if-statement first, otherwise you would get the output
"The current number is "
"No number yet - Please input a number and try again."...
I think this is pretty much what Ignacio meant, when he asked, if you knew what the elif belongs to.
Related
here is my code, it does run but the output is not the way it should be
formula = input("Enter a formula: ")
parenthesis = (formula.count("(,)"))
if parenthesis >= 1 :
print ("You have enteread a complete formula.")
else:
print ("You have incomplete set of parenthesis")
Maybe I'm oversimplifying in my head, but here is a simple way of doing it:
formula = input("Enter a formula: ")
open_brackets = formula.count("(")
close_brackets = formula.count(")")
if open_brackets == close_brackets:
print("You have entered a complete formula.")
else:
print("You have incomplete set of parenthesis")
I'm really new to python. i'am trying to get this working.
import math
number, times = eval(input('Hello please enter the value and number of times to improve the guess followed by comma:'))
guess=number/2
sq_math= math.sqrt(number)
if times>1:
for i in range(2,times+1):
guess=(guess+times/guess)/2
if round(guess,1) == round(sq_math,1):
break
else:
pass
print('Newtons method guessed {0}, square root was {1}'.format(guess, sq_math))
So what he best way? Thank you guys!
You want to do the boolean not-equal comparison round(guess,1) != round(sq_math,1) in a separate if clause, just as you have done for the equality comparison ==:
if times>1:
# break this next line up in to two lines, `for` and `if`
# for i in range(2,times+1) and round(guess,1) != round(sq_math,1):
for i in range(2,times+1): # for check
if round(guess,1) != round(sq_math,1): # if check
guess=(guess+times/guess)/2
if round(guess,1) == round(sq_math,1):
break
times-=1 #decrement times until we reach 0
Demo:
Hello please enter the value and number of times to improve the guess followed by comma:9,56
Newtons method guessed 3.0043528214, square root was 3.0
I believe the primary problem is this formula is incorrect:
guess = (guess + times / guess) / 2
it should be:
guess = (guess + number / guess) / 2
I don't see any problem with your if statement nor your for loop. A complete solution:
import math
number = int(input('Please enter the value: '))
times = int(input('Please enter the number of times to improve the guess: '))
answer = math.sqrt(number)
guess = number / 2
if times > 1:
for _ in range(times - 1):
guess = (guess + number / guess) / 2
if round(guess, 1) == round(answer, 1):
break
print("Newton's method guessed {0}; square root was {1}".format(guess, answer))
USAGE
% python3 test.py
Please enter the value: 169
Please enter the number of times to improve the guess: 6
Newton's method guessed 13.001272448567825; square root was 13.0
%
Though I believe I'm really implementing the Babylonian method for finding square roots.
I'm new to Python. When I run this code, the last part where the results should be calculated is not shown on shell. Can someone tell me how should I fix this? The last part seems a little bit awkward, but I have no idea how to convert str into operations.
# Set variables
opList = ["plus", "minus", "times", "divided-by", "equals"]
# Instrution
print("Intructions: Please enter + as plus, - as minus, * as times and / as divided-by.")
# Read user's equation as a string
equation = input("\nPlease, enter your equation by following the syntax expressed above: ")
# Echo to the screen what the user has entered
print('The equation you entered is "%s".' %equation)
# Parse the equation into a list
theParts = equation.split() # default is whitespace
# print("Here is a list containing the operands and operator of the equation: ", theParts) # For debugging purposes
if len(theParts) == 0 :
print("\nHave you simply pressed the Enter key? Please, enter an equation next time! :)")
elif len(theParts) == 1 :
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 2 :
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 3 :
print("\nThe equation entered by the user is %s %s %s." %(theParts[0], theParts[1], theParts[2]))
if theParts[1] is str("plus"):
theAnswer == theParts[0] + theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts[1] is str("minus"):
theAnswer == theParts[0] - theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts[1] is str("times"):
theAnswer == theParts[0] * theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts [1] is str("divided-by"):
theAnswer == theParts[0] / theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
print("\nBye!")
Assuming you're using Python 2.x, the main issue that's getting you hung up is that you're using input instead of raw_input. input will evaluate your equation and use the evaluation in your program, whereas raw_input will get exactly what the user types as a string. For example:
input
# what the user types
3 + 7
# what the program gets as an integer
10
raw_input
# what the user types
3 + 7
# what the program gets as a string
"3 + 7"
No matter what version of Python you're using, you'll have to fix the following:
Indentation
You'll need to indent the code for your case where theParts has three integers so it executes only then. Otherwise it will execute no matter what and give you an array out of bounds error or the you'll get an indentation formatting error.
Testing string equality
Rather than use is str("[string]") simply use ==. Don't try to over-complicate things.
Strings vs. Numbers
In order to do math, you'll have to convert your strings to numbers. You can do that using something like int("5") which is equal to 5 (integer).
Example Code
# case 3
elif len(theParts) == 3:
# do stuff
if "plus" == theParts[1]:
theAnswer = int(theParts[0]) + int(theParts[2])
Assuming you are using a modern Python, input is actually the correct function to use (there is no raw_input in 3.x, and input is always a string). But, as mentioned, there are other problems.
Here's a version with some corrections.
# Instruction
# I changed the instructions to make them more precise and get rid of the unneccesarily awkward operators
print("Instructions: Please enter a simple equation of the form 'integer [operator] integer', where [operator] is '+', '-', '*' or '/'.")
print("Instructions: Make sure to put spaces between each element.")
# Read user's equation as a string
equation = input("\nPlease, enter your equation by following the syntax expressed above: ")
# Echo to the screen what the user has entered
print('The equation you entered is "%s".' % equation)
# Parse the equation into a list
theParts = equation.split() # default is whitespace
# print("Here is a list containing the operands and operator of the equation: ", theParts) # For debugging purposes
if len(theParts) == 0 :
print("\nHave you simply pressed the Enter key? Please, enter an equation next time! :)")
# Since the two conditions warranted the same response, I just condensed them.
elif len(theParts) == 1 or len(theParts) == 2:
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 3 :
#print("\nThe equation entered by the user is %s %s %s." % (theParts[0], theParts[1], theParts[2]))
# I set the answer before the conditions to a float, so division can result in more meaningful answers
theAnswer = 0.0
# I cast the input strings to integers
p1 = int(theParts[0])
p2 = int(theParts[2])
if theParts[1] is str("+"):
theAnswer = p1 + p2
elif theParts[1] is str("-"):
theAnswer = p1 - p2
elif theParts[1] is str("*"):
theAnswer = p1 * p2
elif theParts [1] is str("/"):
theAnswer = p1 / p2
print('The anwser of the input equation is "{}".'.format(theAnswer))
print("\nBye!")
If you wanted division to have a more school book response, with a quotient and remainder, then instead of p1 / p2, you should use divmod(p1, p2) and parse out the two parts in your printed response.
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.")
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.)