import difflib
import json
from difflib import SequenceMatcher
from difflib import get_close_matches
data=json.load(open("data.json"))
#word= input("enter a word:")
def tranlate(word):
word = word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word,data.keys()))> 0 :
x=get_close_matches(word,data.keys())[0]
z = input("do u mean %s instead?Enter Y if yes or N if no" %x)
if z.lower() == "y" or "yes":
return data[x]
elif z.lower()== "n" or "no":
return "please enter correct word"
else:
return "we do not understand your entry"
else:
return "this word does not exixt,please double check it"
#ratio = SequenceMatcher(None, a, b).ratio()
word= input("enter a word:")
print(tranlate(word))
this below code are not running and it keeps executing
if z.lower() == "y" or "yes":
return data[x]
elif z.lower()== "n" or "no":
return "please enter correct word"
else:
return "we do not understand your entry"
Your if condition is incorrect :
It should be written as :
if z.lower() == "y" or z.lower()== "yes":
return data[x]
elif z.lower()== "n" or z.lower()== "no":
return "please enter correct word"
else:
return "we do not understand your entry"
Originally, you are doing : z.lower() == "y" or "yes"
this leads to : "y" or "yes", which always return true, and hence it will never go to the other conditions.
Related
I'm racking my brain on this and I'm sure it's unnecessary. I've tried looking for the answer online but it's leading me nowhere.
I'm writing a simple menu script (probably not the nicest format). In prompt 2, 3, 4 I'm in need of an option to get back to the previous prompt. Based on what I've found I just keep looping myself into a bigger and bigger issue.
Here is what I have:
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_cluster = 'Outdoors'
elif user_input2 == "2":
user_selected_cluster = 'Gym'
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_cluster = 'AM'
elif user_input4 == "2":
user_selected_cluster = 'PM'
else:
print("Invalid option selected. Run script again.")
exit()
I've tried a variety of while loops and even turning these into functions, which to be honest, I don't have a complete grasp of.
Every solution has just ended up with me looping the prompt I'm on, looping the entire script, or ending the script after prompt_1
Honestly would prefer to learn it instead of someone doing it but I can't even find good videos that address the subject.
Python (like many other languages) does not have a go to option.
The "goto" statement, which allows for unconditional jumps in program flow, was considered to be a bad programming practice because it can lead to confusing and difficult-to-maintain code. Instead, Python uses structured control flow statements, such as if, for, and while loops, which encourage clear and organized code that is easy to understand and debug.
However, you can put the code into functions to achieve the same result, like this:
def main():
''' the main module '''
# have 3 attempts at each question, then move on.
for i in range(3):
x = action_01()
if x != 'invalid': break
for i in range(3):
x = action_02()
if x != 'invalid': break
for i in range(3):
x = action_03()
if x != 'invalid': break
for i in range(3):
x = action_04()
if x != 'invalid': break
def action_01():
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_02():
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_action = 'Outdoors'
elif user_input2 == "2":
user_selected_action = 'Gym'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_03():
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_04():
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_action = 'AM'
elif user_input4 == "2":
user_selected_action = 'PM'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
if __name__ == '__main__':
main()
Note, there are even more efficient ways, but this will be a good starting point for you.
choice = input(">>")
if choice.lower() == "+":
death = death0.IncreaseDeath()
elif choice.lower() == "-":
death = death0.DecreaseDeath()
elif choice.lower() == "r":
death = death0.ResetDeath()
elif choice.lower() == "q":
sys.exit()
I have this code, but its supposed to be a death counter, where the user should jus press + or - or r or q and it increments automatically, without the user needing to press enter. I tried keyboard.press_and_release('enter') and keyboard.add_hotkey('+', death = death0.IncreaseDeath()) but 2nd one doesn't work, and second one works AFTER input finishes and user presses Enter, and now its spamming enter on the input(which isnt what i want, i want the user to type one letter and then have it press Enter automatically. How would I do this to make it happen so user doesnt need to press "Enter" after the input
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
if key_stroke == b'+':
death = death0.IncreaseDeath()
elif key_stroke == b'-':
death = death0.DecreaseDeath()
elif key_stroke == b'r':
death = death0.ResetDeath()
elif key_stroke == b'q':
sys.exit()
Also tried this BUT my code before which is:
def DeathCount(death,DEATH_NAME):
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print ("####################")
print (f" {DEATH_NAME}: {death} ")
print ("####################")
print (" * + : increase * ")
print (" * - : decrease * ")
print (" * r : reset * ")
print (" * q : quit * ")
print ("####################")
doesn't show up and it gives no clue to the user what to press and whether its actually incrementing or not.
hope this code helps
import sys
from getkey import getkey
death0 = 15
death = death0
print(death)
while True:
print(">>")
choice = getkey()
if choice.lower() == "+":
death += 1
elif choice.lower() == "-":
death -= 1
elif choice.lower() == "r":
death = death0
elif choice.lower() == "q":
sys.exit()
else:
print("invalid input")
print(death)
Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here
#import sys
def body_cycle(*args):
if option == "/":
error_func_for_zero(first_number, second_number, option)
print(division_option(first_number, second_number))
print()
print(begin)
def error_func_for_zero(*args):
try:
first_number / 0 or second_number / 0
except ZeroDivisionError:
print("YOU CANNOT DIVIDE BY ZERO!")
print(begin)
def division_option(*args):
return first_number / second_number
begin = " "
while begin:
print("Hello, I am calculator. ")
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")
print(body_cycle(first_number, second_number, option))
ask = " "
while ask:
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")
if exit_or_continue == "Y" or "y":
print("OK")
elif exit_or_continue == "N" or "n":
#break
ask == False
else:
print("Break program. ")
break
You just want to replace ask == False by ask = False.
In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:
def operation(a, b, option):
if option == "+":
return a + b
elif option == "-":
return a - b
elif option == "*":
return a * b
elif option == "/":
try:
return a / b
except ZeroDivsionError
return "YOU CANNOT DIVIDE BY ZERO!"
The rest can be put in a single loop instead of two, like so:
print("Hello, I am calculator. ")
while True:
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\n
Choose your option (+, -, *, /): ")
# Result.
print(operation(first_number, second_number, option))
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
Choice: ").lower()
if exit_or_continue == "y":
print("OK")
elif exit_or_continue == "n":
break
I am a complete newbie and was trying to make a number magic trick. I want the program to stop when the user types "No". Here is my code below!
print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
print("Yay!!")
print("Pick an integer number from 1 to 10 but don't tell me!")
print("Multiply this number with 2")
print("Multiply the new number by 5")
print("Now, divide your current number with your original number")
print("Subtract 7 from your current number")
print("Is the answer 3 ?")
elif x == "No":
print("Boo!!")
else:
print("Invalid Input")
y = input ("Yes or No")
if y == "Yes":
print("Cool isn't it?")
elif y == "No":
print("You can't do math!")
else:
print("Invalid input")
You don't have to raise an error, you could simply use the exit method instead:
if x.strip().lower() == "no":
print("You said no!")
exit(0)
You could even use the exit method from the sys module, like this:
import sys
if x.strip().lower() == "no":
print("You said no!")
sys.exit(0)
INFO: The 0 in the exit method's parenthesis means that "this program finished without any errors" but replacing the 0 with a 1 would mean that "something went wrong with the program" and it's exiting with an error.
Good luck.
You could raise an exception. Also, it's good practice to put one-line if/else statements on the same line... For example,
print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
print("Yay!!")
print("Pick an integer number from 1 to 10 but don't tell me!")
print("Multiply this number with 2")
print("Multiply the new number by 5")
print("Now, divide your current number with your original number")
print("Subtract 7 from your current number")
print("Is the answer 3 ?")
elif x == "No":
print("Boo!!")
raise SystemExit()
else:
print("Invalid Input")
raise SystemExit()
y = input ("Yes or No")
if y == "Yes":
print("Cool isn't it?")
elif y == "No":
print("You can't do math!")
raise SystemExit()
else:
print("Invalid input")
raise SystemExit()
You're welcome to use this code...
if x == "No":
quit()
OR
from sys import exit
if x == "No":
exit()
I don't have a lot of experience with python but I think this can be much simpler. If anything available for the same result. Using a dictionary mapping to functions instead of all those elif maybe?
choice = input("Select an option: ")
if choice == "1":
try:
new_contact = create_contact()
except NotAPhoneNumberException:
print("The phone number entered is invalid, creation aborted!")
else:
contacts[new_contact['name']] = new_contact
save_contacts(contacts, filename)
elif choice == "2":
print_contact()
elif choice == "3":
search = input("Please enter name (case sensitive): ")
try:
print_contact(contacts[search])
except KeyError:
print("Contact not found")
elif choice == "0":
print("Ending Phone Book.\nHave a nice day!")
break
else:
print("Invalid Input! Try again.")