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.")
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.
when input is asked, I type Rock it loops back as though i did not type the right input.
I've tried retyping the error checking but nothing is working. The only input it will accept is 'q'. Here is the code:
import random
user_wins = 0 #setting default score
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint(0, 2) #rock: 0 , paper: 1, scissors: 2
computer_pick = options[random_number] #using computer's pick from a random from the list to be stored.
print('Computer picked:', computer_pick + ".") #printing the result of computer's pick
if user_input == "rock" and computer_pick == "scissors": #setting win or lose conditions
print('Rock Crushes Scissors...You Win!')
user_wins += 1
elif user_input == "paper" and computer_pick == "rock":
print('Paper Covers Rock...You Win!')
user_wins += 1
elif user_input == "scissors" and computer_pick == "paper":
print('Scissors Cuts Paper...You Win!')
user_wins += 1
else:
print("You Lose")
computer_wins += 1
print("You won ", user_wins, "times.")
print("Computer won ", computer_wins, "times.")
print('Goodbye')
It's because you need to break the loop when input is in options, so the loop could be
while True:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
if user_input not in options:
continue
else:
break
Anyways, a better implementation could be creating the empty option and assign it if matches, so
answer = ''
while not answer:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
elif user_input in options:
answer = user_input
In you case try this code. You will need to have two while loops: one is for checking the input, the other is for continuing the game.
exit = False #this helps you to exit from the main while loop.
while not exit:
options = ['rock', 'scissors', 'paper']
user_input = ""
while True:
user_input = input('pls write paper, rock, scissors, or
q(quit) ').lower()
if user_input in options:
break
elif user_input == 'q':
exit = True
break
#do some calculations
# do some summary calculations and print them
I hope you will find it helpful)
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
play_func()
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append()
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
I think the problem is here:
besides from no
if secret_word[x] == guess:
guess_word[x] == guess
print(guess_word)
if not '-' in guess_word:
print('You Won!')
break
else:
print('The letter is not in the word. Try Again!')
guess_taken += 1
if guess_taken == 8:
print('You Lost, the secret word was: ', secret_word)
change()
guessing()
print('Game Over!')
if secret_word[x] == guess:
guess_word[x] == guess
I think the problem is on these lines of code because they don't actually replace guess_word
This should hopefully get you on the right track. I just created a new method/function to contain all of your other functions, and fixed the append statement. Good Luck!
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def main():
play_func()
change()
guessing()
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append(guess)
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
print(x)
main()
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()
Here is my code (for hangman game):
import random, os
def main():
print("******THIS IS HANGMAN******")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["school", "holiday", "computer", "books"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, x in enumerate(word):
if x == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print('You won')
elif choice == "2":
os.system("cls")
main()
else:
print("that is not a valid option")
main()
I have tried os.system("clear") but it doesn't clear the screen, I want it to clear the entire screen but instead (cls) makes it print my menu again and (clear) does nothing except clear the 2. If I'm missing something obvious it's probably because I'm new to python.
It prints the menu again because you call main() again instead of just stopping there. :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
Now for the clearing itself, os.system("cls") works on Windows and os.system("clear") works on Linux / OS X as answered here.
Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()