Can`t exit from program - python-3.x

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

Related

Cannot get it to accept input

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)

Code Not Compiling- Unable to figure out Issue

I have been stumped on this for days now and I can seem to figure out what the problem is. I am able to run all of it fine except when I select option 1 on the console menu. I will be able to make through the first inputs and then I get an error every time. Also for some reason when another option is selected, it does not jump to that option, it just starts going the password generator code instead. Any help would be appreciated. Still fairly new to all this.
import math
import sys
import random
import datetime
import string
import secrets
from datetime import date
while 1:
print("\nWelcome to the application that will solve your everday problems!")
print("\nPlease Select an Option from the List Below:")
print("1: To Generate a New Secure Password ")
print("2: To Calculate and Format a Percentage ")
print("3: To Receive the amount of days until Jul 4th, 2025 ")
print("4: To Calculate the Leg of Triangle by using the Law of Cosines ")
print("5: To Calculate the Volume of a Right Circular Cylinder ")
print("6: To Exit the Program ")
choice = int(input("Please enter your Selected Option: "))
if choice == 6:
print("\nThank you for coming, Have a Great Day!")
break
elif choice == 1:
def input_length(message):
while True:
try: #check if input is integer
length = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
if length < 5: #check if password's length is greater then 5
print("Too short password!")
continue
else:
return length
def input_yes_no(message):
while True:
option = input(message).lower()
if option not in ('y', 'n'): #check if user entered y/n (or Y/N)
print("Enter y or n !")
else:
return option
def get_options():
while True:
use_upper_case = input_yes_no("Use upper case? [y/n]: ")
use_lower_case = input_yes_no("Use lower case? [y/n]: ")
use_numbers = input_yes_no("Use numbers? [y/n]: ")
use_special_characters = input_yes_no("Use special characters? [y/n]: ")
options = (use_upper_case, use_lower_case, use_numbers, use_special_characters)
if all(option == 'n' for option in options): #check if all options are 'n'
print("Choose some options!")
elif all(option == 'n' for option in options[:-1]) and options[-1] == 'y':
print("Password can not contain only special characters")
return options
def generate_alphabet(use_upper_case, use_lower_case, use_numbers, use_special_characters):
alphabet = ''
if use_upper_case == 'y' and use_lower_case == 'y':
alphabet = string.ascii_letters
elif use_upper_case == 'y' and use_lower_case == 'n':
alphabet = string.ascii_uppercase
elif use_upper_case == 'n' and use_lower_case == 'y':
alphabet = string.ascii_lowercase
if use_numbers == 'y':
alphabet += string.digits
if use_special_characters == 'y':
alphabet += string.punctuation
def generate_password(alphabet, password_length, options):
use_upper_case = options[0]
use_lower_case = options[1]
use_numbers = options[2]
use_special_characters = options[3]
while True:
password = ''.join(secrets.choice(alphabet) for i in range(password_length))
if use_upper_case == 'y':
if not any(c.isupper() for c in password):
continue
if use_lower_case == 'y':
if not any(c.islower() for c in password):
continue
if use_numbers == 'y':
if not sum(c.isdigit() for c in password) >= 2:
continue
if use_special_characters == 'y':
if not any(c in string.punctuation for c in password):
continue
break
def main():
password_length = input_length("Enter the length of the password: ")
options = get_options()
alphabet = generate_alphabet(*options)
password = generate_password(alphabet, password_length, options)
print("Your password is: ", password)
if __name__ == "__main__":
main()
elif choice == 2:
Num = float(input("Please Enter the Numerator: "))
Denom = float(input("Please Enter the Denomenator: "))
Deci = int(input("Please Enter the Number of Decimal Places You Would Like: "))
Val = Num/Denom*100
Val = round(Val, Deci)
print("\nThe Percentage of the numbers you entered is", Val, "%")
elif choice == 3:
Today = datetime.date.today()
Future = date(2025, 7, 25)
Diff = Future - Today
print("\nTotal numbers of days till July 4th, 2025 is:", Diff.days)
elif choice == 4:
A = int(input("Please Enter angle A: "))
B = int(input("Please enter angle B: "))
Angle = int(input("Please Enter the Angle of the Triangle: "))
c = A*A + B*B - 2*A*B*math.cos(math.pi/180*Angle)
print("\nThe Leg of the Triangle is:", round(c))
elif choice == 5:
Radius = int(input("Please Enter the Radius of the Cylinder: "))
Height = int(input("Please Enter the Height of the Cylinder: "))
Volume = (math.pi*Radius*Radius)*Height
print("\nThe Volume of the Cylinder is:", Volume)

How would I trigger an automatic enter key press after an Input function?

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)

Why doesn't my hangman game work the way it's supposed to

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'm trying to make this program repetitive while using all the functions but cannot seem to get it working

So all I want to create is a loop for this program so that it will be able to be used more than once without re-running through the shell, I would like to also learn how to do this with any program involving functions
Everything
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is not prime")
break
else:
print(num, "is prime")
else:
print(num, "is not a prime number")
is_prime(num)
def print_factors(num):
print("The factors of",num,"are:")
for i in range(1, num + 1):
if num % i == 0:
print(i)
print_factors(num)
def main():
choice = "y"
while choice.lower() == "y":
# get input
#num = int(input("Enter any number between 1 - 5000: "))
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
print('Finished!')
I just want it to work when you press y and re-run the entire program like its first time
Structure your code. Create functions. Call functions. Respect indentations.
def check_primes():
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
# do checking -your current code makes not much sense
# and does not do what the methodnames imply
# see f.e. https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime
print("Did prime checking")
def main():
choice = "y"
while choice.lower() == "y":
check_primes()
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
if __name__ == "__main__":
main()

Resources