I'm writing this program that is basically a limited calculator. I'm trying to make it so that if the user enters let's say "Power" instead of the number 1 for the desired mode, it prints out "Invalid selection". The same goes if they attempt to write "Quadratics" instead of 2 and so on for the rest.
#CALCULATOR
print("MY CALCULATOR")
print("1. Powers")
print("2. Quadratics")
print("3. Percents")
print("4. Basic Ops")
choice = int(input("Please enter your desired mode: "))
if choice == 1:
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
power = base**exponent
if choice == 2:
print("Please enter the values for A/B/C: ")
a = int(input("A: "))
b = int(input("B: "))
c = int(input("C: "))
I tried doing:
if choice not == 1:
print("Invalid Selection")
and
if choice not 1:
print("Invalid Selection")
but they don't seem to work. If you could please tell me what I am doing wrong. Thank you.
not is not a function. It is an operator.
The correct usage is to put it before an expression:
if not (choice == 1):
However in this case, it's much better to use != (not equal) instead:
if choice != 1:
Related
i tried everything shoould i add something in between or what i used to work with c++
so i dont know what to do
print("1 add")
print("2 sub")
print("3 mult")
print("4 div")
start = int(input("please choose what u want: "))
if start == "1":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose + chose))
if start == "2":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
If I understood correctly, you have an indentation problem, as well as condition one.
Every input from the console is treated as a string.
You converted that input to int and then checked against the string, it isn't equal.
The right one would be:
start = input("please choose what u want: ")
if start == "1":
or
start = int(input("please choose what u want: "))
if start == 1:
Also, make sure to indent the code:
if start == "2":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
You should write your code inside the if statement like this:
start = int(input("please choose what u want: "))
if start == 1:
print("enter your first number")
choose = float(input("please enter
your first number: "))
chose = float(input("please enter
your second number: "))
print("your answer is ", (
choose+chose))
if start == 2:
print("enter your first number")
choose = float(input("please enter
your first number: "))
chose = float(input("please enter
your second number: "))
print("your answer is ", (choose -
chose))
Try:
print("1 add")
print("2 sub")
print("3 mult")
print("4 div")
start = int(input("please choose what u want: "))
if start == 1:
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose + chose))
elif start == 2:
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
The data you get from the user is integer, but the type you are querying is string. Your code is not working due to data type mismatch. I have specified the correct code above.
I am making a python calculator program that asks a user after completing one calculation whether they want to continue or not. If the user says Yes the loop should run or else it should stop. I am Facing a problem where a user says yes or no the loop still executes anyhow. Why is it so ???
print("This is a Calculator In Python. !!!")
print("I Can Do Addition, Subtraction, Multiplication and Division.!!")
def addition():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number. !!"))
result = num1 + num2
return result
def subtraction():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number.!!"))
result = num1 - num2
return result
def multiplication():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 * num2
return result
def division():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 / num2
return result
print("""1. a for Addition
2. s for subtraction
3. m for multiplication
4. d for Division""")
select = "Yes"
while select:
choice = str(input("You Choose The Operation."))
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select=str(input('Continue Yes or No '))
print("Thank you..!")
You've defined your loop as while select, which means as long as select is considered to not be None, it will continue looping
In your loop, you assign the user input to select, which means as long as the user inputs anything, it will always keep looping.
To fix this, you should have the while loop check if select is "yes":
while select.lower().strip() == "yes":
choice = input("You Choose The Operation. ")
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select = input("Continue Yes or No ")
print("Thank you..!")
Also, input() returns a string so you don't need to wrap it in a str() call.
Until this semester I didn't even know a while True was a thing. I have to write a while True loop to loop until the user enters 'n' to break. My problem is restarting the loop if the user enters anything other than 'y' or 'n'. Currently, I can loop with any character besides 'n'. I need a way to catch the if say 'q' was entered, "please enter 'y' or 'n'" and prompt the user again. I have considered doing another while loop within the loop but I feel like there is a more optimal way to achieve this.
def main():
userinput = "y"
display_title()
while True:
userinput.lower() == "y"
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ")
if userinput == "n":
print()
print("Thanks, Bye!")
break
You don't need another while loop. You could just need to put the input check to the beginning of the loop and add a check for any other character than 'y' and 'n', e.g.:
def main():
userinput = "y"
display_title()
while True:
if userinput == "n":
print()
print("Thanks, Bye!")
break
elif userinput != "y":
userinput = input("Please select yes (y) or no (n)").lower()
continue
### If you get this far, userinput must equal 'y'
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ").lower()
continue
Be aware, the way you implemented the inner loop asking for the conversion type doesn't allow you to exit the xcript if you suddenly decide abort the procedure e.g. a Keyboard interrupt.
[Edit]
I've not looked at your inner loop. As someone else has suggested,
while choice == "a" or "b"
will always evaluate to True. Why? beacuse internally python will split this expression:
(choice == "a") or "b"
It doesn't matter if choice == "a", as "b" is a non-empty string and thus evaluates to True.
If you were to rewrite yout inner loop as follws:
while choice: # Will evaluate to True as long as choice isn't an empty string.
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
else:
print("Please enter a valid option a or b")
choice = input("Select a conversion (a/b): ")
you'll be able to give the user an option to exit the inner loop by inputing nothing and you'll remove an uneccessary double-check if the choice equals a or b.
Tip: If you want to check if one variable matches one of some different options in a while statement, you could use the following:
while var in [opt1, opt2 ...]:
...
This is my first small python task when i found out about speedtest-cli.
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 2:
print(st.upload())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
i am just a beginner so i could't find any way to shorten this code. Any tips would be helpful :)
If you don't care about execution time but only about code length:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
st.get_servers([])
tst_results = [st.download(), st.upload(), st.results.ping]
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option >= 1 and option <= 3:
print(tst_results[option-1])
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
Did not really make it smarter, just shorter by creating a list and take option as index in the list
First, you can look at this line:
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
this line happens on each of the options, so we don't need to repeat it. instead you can add it at the end of the "while" clause. also add "continue" to your "else" clause to avoid asking this when wrong input is entered.
also, the "else" clause for the "while" loop is not needed
e.g:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice")
continue
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
print("Test is ended")
second, there is an error in your logic. your prompt says enter 1 to continue or 2 to quit, and indeed when you enter 2 the loop will end, but also when the user enters 3 or any other number. Even worse, if a user will enter a character that is not a number or nothing at all, they will get an exception. For this we use try-except clauses. another way to do this kind of loop is using "while "True" and then using "break" to exit.
while True:
... your code here ...
q = input("enter 1 or 2:")
try:
q = int(q)
except ValueError:
print("Invalid input")
if q == 2:
break
print("Test is ended")
This is helpful to you if:
you are a pentester
or you (for some other arbitrary reason) are looking for a way to have a very small python script
Disclaimer: I do not recommend this, just saying it may be helpful.
Steps
Replace all \n (newlines) by \\n
Replace two (or four) spaces (depending on your preferences) by \\t
Put """ (pythons long quotation marks) around it
Put that oneline string into the exec() function (not recommended, but do it if you want to)
Applied to this questions code
exec("""import speedtest\n\nq = 1\nwhile q == 1:\n\t\tst = speedtest.Speedtest()\n\t\toption = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))\n\t\tif\toption == 1:\n\t\t\t\tprint(st.download())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 2:\n\t\t\t\tprint(st.upload())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 3:\n\t\t\t\tservernames =[]\n\t\t\t\tst.get_servers(servernames)\n\t\t\t\tprint(st.results.ping)\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telse:\n\t\t\t\tprint("Please enter the correct choice")\nelse:\n\t\tprint("Test is ended")\n""")
I have found the solution to that by using the sys module. i suppose this could work if a wrong data is input.
import speedtest
import sys
#Loop for options
while True:
st = speedtest.Speedtest()
option = input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: ")
#To check if the input value is an integer
try:
option = int(option)
except ValueError:
print("Invalid input")
continue
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice: ")
continue
q = 0
#Choice to continue or to end
while (q != 1) or (q != 2):
q = input("Enter '1' if you want to continue or Enter '2' if you want to stop the test: ")
try:
q = int(q)
except ValueError:
print("Invalid input")
continue
if q == 1:
break
elif q == 2:
sys.exit("Test is ended")
else:
print("Invalid input")
continue
i am trying to learn about the while loop and am trying to build something with it.
i have a function that will hold a choice that the user will make but every time i run it the script is asking for the input twice..
can someone please explain to me what is wrong with my code?
thanks in advance!! :)
code:
def choice():
choice = int(input("what is your choice? "))
valid_choice = False
while not valid_choice:
if choice >= 1 and choice <= 4:
return choice
valid_choice = True
else:
print("Please enter a valid response..")
choice = int(input("what is your choice? "))
def beginning():
while True:
display_menu()
choose = choice()
if choose == 1: print("Your status")
print(Michael.status())
print()
print("Banks's status:")
print(Prod.status()) elif choose == 2: withraw = float(input("How much money do you want to withraw from the bank?: "))
Prod.withrawl(withraw)
Michael.withraw(withraw)
You were calling choice twice