Why this conversion program does not work? - python

I am trying to figure out what is wrong in here. Any help is very appreciated. I think one of the problem is the declaration of the variable that is inside the method. Can I make a global variable from the method?
def cycle():
choice = None
while not choice:
newcalc = input('Do you want to make a new calculation? \n \t (Y/N)')
if newcalc.lower() in ["no", "n"]:
choice = "no"
if newcalc.lower() in ["yes", "y"]:
choice = "yes"
else:
print('This is not the right answer')
continue
return choice
def counting_M(data):
while True:
concersion_1 = input('Do you want to convert from M to uM? (Y/N)')
if concersion_1.lower() in ["y", "yes"]:
print('This is the result of the conversion {} uM'.format(str(data/1000)))
else:
print('Not converting')
while True:
mw = input('What is the Molecular Weight of your compound, please in g/M?')
try:
mw = float(mw)
break
except ValueError:
print("Not a valid float!")
print('Your coumpound weights ug/ml', str((data/1000) / (mw / 1000)))
def measure():
while True :
data = input('Please, provide the absolute amount of compound you have, without units \n \t')
try:
data = float(data)
break
except ValueError:
print("Not a valid float value!")
units = input('Please, indicate the measure unit you have \n A)M, B)mM, C)uM '
'\n 1A)g/liter, 2A)mg/ml, 3A)ug/ml \n \t')
if units.lower() == "a":
print('Ok so you have M')
counting_M(data)
choice = cycle()
print(choice)
elif units.lower() == "b":
print('Ok so you have mM')
counting_M(data)
choice = cycle()
print(choice)
elif units.lower() == "c":
print('Ok so you have uM which it the right concentration')
cycle()
elif units.lower() == "1a":
print('Ok so you have g/liter you have now mg/ml')
counting_M(data)
choice = cycle()
print(choice)
elif units.lower() == "2a":
print('Ok so you have mg/ml')
counting_M(data)
choice = cycle()
print(choice)
elif units.lower() == "3a":
print('Ok so you have ug/ml, hence nothing to do')
cycle()
else:
print('You have to select one of the options above')
counting_M(data)
choice = cycle()
print(choice)
Thank you for your help

Related

If statement not executing. Python

I am still new to programming and I wanted to do a simple calculator in python. However, I could only reach this point of my code:
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
float(variableA)
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
float(variableB)
break
else:
print("Incorrect input. Please try again.")
continue
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
Not sure why my if statement is not executing after all the correct inputs from the user. I mostly focused on the error handling part and after everything going well, the if statement is just not executing after that. There could probably be a simple mistake but even I can't understand what's going on here.
You have an issue with type casting. So when you are taking input from the user all the userInput is str not int, so you need to cast it like userInput = int(userInput) before doing further calculator operations.
Also, you need to assign the float casting to a variable like this variableA = float(variableA) and variableB = float(variableB) otherwise your add/sub/divide/multiply etc. will not do expected operations.
For example add will do concatenation i.e '2' + '4' = 24 not 2 + 4 = 6.0
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
variableA = float(variableA) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
variableB = float(variableB) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
userInput = int(userInput) # <-- fix this line
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
If the user input is supposed to be an int, convert it early and fail fast.
while True:
userInput = input(...)
try:
userInput = int(userInput)
except ValueError:
print("Not an integer, try again")
continue
if userInput in range(1, 7):
break
print("Number out of range, try again")
and similarly for the operands
while True:
variableA = input("Enter the first value: ")
try:
variableA = float(variableA)
break
except ValueError:
print("not a float")
There's little reason to convert the menu choice to an integer, though. You could simply write
while True:
userInput = input(...)
if userInput in "123456": # ... in ["1", "2", "3", "4", "5", "6"]
break
print("Invalid choice, try again")

Python incorrect answer input

I would like to make it so my menu works in a way which if a letter is input or anything other than a correct answer is input my script doesn't just end abruptly and it asks to input a correct option. Could anyone help me do this please? Here is the code i have so far:
#variables for password entry
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
#password entry code
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("enter guess: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("out of guesses!")
else:
print("You are into the secret lair!")
#Menu code
def menu(menu):
print("--------------------------\nMenu\n--------------------------\n1.Secret
Sauce\n2.More secret stuff\n3.Even more secret stuff\n4.Exit")
choice = int(input("--------------------------\nENTER CHOICE: "))
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4:
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
#exit loop for the def
running = True
while running:
menuChoice = menu(menu)
if menuChoice == False:
print("\nGoodbye")
running = False
Instead of
choice = int(input("--------------------------\nENTER CHOICE: "))
You can do the following:
choice = input("--------------------------\nENTER CHOICE: ")
and then after it we need to check if the string is a digit, so you can transfer it to "int" type safely.
if choice.isdigit():
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4 or choice != (1,2,3,4):
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
In your menu() function,
Instead of immediately casting the input into an int, you can use a try statement to make sure the input is an integer, so if the user types in a letter your program will not stop. For example:
validInput = False
while validInput == False:
choice = input("--------------------------\nENTER CHOICE: ")
try:
choice = int(choice)
validInput = True
except:
print("Please enter an integer.")
Replace choice = int(input("--------------------------\nENTER CHOICE: ")) with the above code and it will work.

I don't understand why I need to input "q" for n times of question generate, to quit program

I dont know why I have to input q n times of question generated to quit the program, what should I do so that the program closes instantly when I input q only once?
greetings = input("Hello, what should i call you? ")
def generate_again_or_quit():
while True:
option = input("Press any key to generate another question or Q to exit" ).lower()
if option == "q":
break
generate_questions()
def generate_questions():
print(random_questions_dict.get((random.randint(1, 30))))
generate_again_or_quit()
while True:
greetings2 = input("Do you want me to generate some questions "+greetings+"?").lower()
if greetings2 == "yes":
generate_questions()
break
elif greetings2 == "no":
print("See you later...")
break
else:
print("Please answer with yes or no")
continue
As the comments suggest, pick iteration or recursion. Here's a recursion example for your case
import random
random_questions_dict = {1: "why", 2: "what", 3: "when", 4: "which", 5: "how"}
def generate_questions():
print(random_questions_dict.get((random.randint(1, 5))))
option = input("Press any key to generate another question or Q to exit" ).lower()
if option == "q":
return
generate_questions()
greetings = input("Hello, what should i call you? ")
while True:
greetings2 = input("Do you want me to generate some questions "+greetings+"?").lower()
if greetings2 == "yes":
generate_questions()
break
elif greetings2 == "no":
print("See you later...")
break
else:
print("Please answer with yes or no")
continue

Python program asks for input twice, doesn't return value the first time

Here is my code, in the get_response() function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.
How do I fix this?
import random
MIN = 1
MAX = 6
def main():
userValue = 0
compValue = 0
again = get_response()
while again == 'y':
userRoll, compRoll = rollDice()
userValue += userRoll
compValue += compRoll
if userValue > 21:
print("User's points: ", userValue)
print("Computer's points: ", compValue)
print("Computer wins")
else:
print('Points: ', userValue, sep='')
again = get_response()
if again == 'n':
print("User's points: ", userValue)
print("Computer's points: ", compValue)
if userValue > compValue:
print('User wins')
elif userValue == compValue:
print('Tie Game!')
else:
print('Computer wins')
def rollDice():
userRoll = random.randint(MIN, MAX)
compRoll = random.randint(MIN, MAX)
return userRoll, compRoll
def get_response():
answer = input('Do you want to roll? ')
if answer != 'y' or answer != 'n':
print("Invalid response. Please enter 'y' or 'n'.")
answer = input('Do you want to roll? ')
main()
answer != 'y' or answer != 'n': is always true; or should be and.
It should be answer != 'y' and answer != 'n':
You're logically thinking that "answer is not y OR n", but in code that is
not (answer == 'y' or answer == 'n')
Apply DeMorgans' rule you get
answer != 'y' and answer != 'n'
Perhaps you should restructure using in.
You'll also want to return answer
def get_response():
while True:
answer = input('Do you want to roll? ')
if answer not in {'y', 'n'}:
print("Invalid response. Please enter 'y' or 'n'.")
else:
return answer

Python - Looping an Input [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python, basic question on loops
how to let a raw_input repeat until I wanna quit?
I would like some help with Python please.
I'm writing a program in Py2.7.2, but am having some issues.
What I have so far is something like this:
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
But after the user chooses either 1, 2, 3 or 4, the program automatically exits. Is there a way that I can loop the program back up so that it asks them again "What would you like to do?"; and so that this continues to happen, until the user exits the program.
You can accomplish that with a while loop. More info here:
http://wiki.python.org/moin/WhileLoop
Example code:
choice = ""
while choice != "exit":
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
Use a While Loop -
choice = raw_input("What would you like to do (press q to quit)")
while choice != 'q':
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
choice = raw_input("What would you like to do (press q to quit)")
You need a loop:
while True:
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
Personally this is how i would suggest you do it. I would put it into a while loop with the main being your program then it runs the exit statement after the first loop is done. This is a much cleaner way to do things as you can edit the choices without having to worry about the exit code having to be edited. :)
def main():
choice=str(raw_input('What would you like to do?'))
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
if __name__=='__main__':
choice2=""
while choice2 != 'quit':
main()
choice2=str(raw_input('Would you like to exit?: '))
if choice2=='y' or choice2=='ye' or choice2=='yes':
choice2='quit'
elif choice2== 'n' or choice2=='no':
pass

Categories

Resources