Python caesar cipher A-Z capital only - python-3.x

Just need a suggest for my code as, I have my code at the moment so that it will work and just add 5 to the ASCII value, but what I need to know is how can I make this work for just moving 5 places along the alphabet e.g. now if I were to type Z I would just get a _ when I would like to get a D.
Ceaser Cipher
bLoopProgram = True
while bLoopProgram == True:
sEncryptOrDecrypt = input("Encrypt Or Decrypt : ").lower()
if sEncryptOrDecrypt == "encrypt":
while sEncryptOrDecrypt == "encrypt":
sPassNonEnc = input("Enter a password to encrypt : ")
aPass = []
for i in range(0, len(sPassNonEnc)):
nASCII_VALUE = ord(sPassNonEnc[i])
if nASCII_VALUE < 64:
nASCII_VALUE += 10
aPass.append(chr(nASCII_VALUE))
elif nASCII_VALUE > 63:
nASCII_VALUE -= 10
aPass.append(chr(nASCII_VALUE))
else:
print("\n * Unknown Character [ASCII INDEX]")
aPass.append()
print("".join(aPass))
sSaveToTxt = input("Would you like to save your encrypted password to a text document?\nThe Text document will be found next to this python file and called password_enc (Yes/no): ").lower()
if sSaveToTxt == "yes":
fFileRequestedOpen = open('password_enc.txt', 'w')
fFileRequestedOpen.write("".join(aPass))
fFileRequestedOpen.close()
print("Saved to text document have a nice day!")
break
elif sSaveToTxt == "no":
print("okay have a nice day!")
break
else:
print("\n*Invalid Option*\n")
if sEncryptOrDecrypt == "decrypt":
while sEncryptOrDecrypt == "decrypt":
sReadOrInput = input("Would you like to load password from text document if saved,\n or would you like to input a encypted password (read/enter): ").lower()
if sReadOrInput == "read":
fFileRequestedOpen = open('password_enc.txt', 'r')
sPassEnc = fFileRequestedOpen.read()
fFileRequestedOpen.close()
aPass = []
for i in range(0, len(sPassEnc)):
nASCII_VALUE = ord(sPassEnc[i])
if nASCII_VALUE < 64:
nASCII_VALUE -= 10
aPass.append(chr(nASCII_VALUE))
elif nASCII_VALUE > 63:
nASCII_VALUE += 10
aPass.append(chr(nASCII_VALUE))
else:
print("\n * Unknown Character [ASCII INDEX]")
print("".join(aPass))
break
if sReadOrInput == "enter":
sPassEnc = input("Enter a password to decrypt : ")
aPass = []
for i in range(0, len(sPassEnc)):
nASCII_VALUE = ord(sPassEnc[i])
if nASCII_VALUE < 64:
nASCII_VALUE -= 10
aPass.append(chr(nASCII_VALUE))
elif nASCII_VALUE > 63:
nASCII_VALUE += 10
aPass.append(chr(nASCII_VALUE))
else:
print("\n * Unknown Character [ASCII INDEX]")
print("The now unencrypted password is:")
print("".join(aPass))
break
elif sEncryptOrDecrypt == "quit":
quit()
else:
print("")

You have to use modulo (%) to restrict your values within 65 (A) and 90 (Z)
For instance:
nASCII_VALUE = 90 # This is a Z
nASCII_VALUE += 5 # chr(95) = _
print(chr(((nASCII_VALUE - 64) % 26) + 64))
This will print 'E' (5th letter of alphabeth)

Related

Why the "stop" input doesnt stop the hitorstop() and run the code for the condition elif todo == "stop"

import random
class Player:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
run = True
def __init__(self):
self.name = input("Enter your name : ")
self.Bet = inputs.bet(self)
self.Aceval = inputs.Aval(self)
class Dealer:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
class inputs:
def bet(self):
"""
takes in the bet from the user and stores it in the player class
:return: output
"""
self.bet = input("Enter the amount for your bet : ")
output = self.bet
if self.bet.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.bet(self)
else:
return int(output)
def Aval(self):
"""
Takes the value for ace and stores it in the player class
:return: output
"""
self.aval = input("Enter the value for ACE (1 or 10) : ")
output = self.aval
if self.aval.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.Aval(self)
elif self.aval.isnumeric() == True:
if self.aval in ["1", "10"]:
return int(output)
else:
print("I understand you suffer braincell deficiency but I need you to fire up those 2 braincells you have and enter the proper number")
return inputs.Aval(self)
def valcalc(card):
"""
takes the card for player.deck and returns the value of that card
:return: card value
"""
if card[0] in ("K", "Q", "J"):
return 10
elif card[0] == "A":
return p.Aceval
else:
if len(card) > 2:
return int(card[0:2])
else:
return int(card[0])
def hitorstop(todo):
if todo.lower() == ("hit" or "stop"):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
if todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
p = Player()
d = Dealer()
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
print("Dealer's card is :" + str(dcard) + "+")
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
hitorstop(input("Do you want to hit or stop : "))
Why does the code below todo == "stop" run when i put in stop as input , it just keeps looping asking for the input again and again if i put "stop" for hitorstop() function
.................................................................................................................................................................................................................................................................................................................................................
You need to replace the line todo.lower() == ("hit" or "stop"): with todo.lower() in ("hit", "stop"): to make it work.
However, this entire condition is redundant in the first place and you can remove it.
You don't need it since you compare the input with "hit" and "stop" later, so it is useless to compare twice.
Here is the replace:
def hitorstop(todo):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
elif todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
else:
hitorstop(input("\n\nDo you want to hit or stop : "))

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)

Python Error handling for an input requiring a integer

I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review

How to implement a timer for a math quiz in python?

import random
import time
import pathlib
import hashlib
import operator
level = 1
score = 1
def sign_up():
username = input("Enter a username: ")
while True:
password = input("Enter a password (6 character long): ")
if len(password) < 6:
password = input("Enter a password (6 character long): ")
else:
break
hashed_password = hashlib.sha1(password.encode("utf-8")).hexdigest()
# print(hashed_password)
with open("credentials.txt", mode="w") as writable_password:
writable_password.write(username+"\n")
writable_password.write(hashed_password+"\n")
log_in()
def log_in():
print("Please, enter your usarname and password to sign in")
username = input("Username: ")+"\n"
while True:
password = input("Password (6 character long): ")
if len(password) < 6:
password = input("Password (6 character long): ")
else:
break
with open(".credentials.txt", mode="r") as credentials:
user_data = credentials.readlines()
for i in user_data:
# print(i)
if i == username and hashlib.sha1(password.encode("utf-8")).hexdigest()+"\n" == user_data[user_data.index(i)+1]:
print("You have succesfully signed in")
start_game()
break
def start_game():
start = "ll"
start = input("Please press any key to start the game")
# print(start)
if start != "ll" and level == 1:
level_one()
overall = 0
def level_one():
global score
global overall
if score <= 0:
return print("Haha, You lost")
answer = 0
first_number = random.randint(1, 100)
second_number = random.randint(1, 100)
random_operator = random.choice(["+", "-"])
if random_operator == "+":
response = input(f"{first_number} + {second_number}: ")
answer = first_number + second_number
if int(response) == answer:
score += 10
overall += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
else:
response = input(f"{first_number} - {second_number}: ")
answer = first_number - second_number
if int(response) == answer:
score += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
# print(first_number, second_number, answer)
# def main():
# if __name__ = "__main__":
# main()
# sign_up()
# log_in()
start_game()
I want to implement a timer for my math quiz. The user should have 2 minutes at the beginning and for each correct answer 10 seconds will be added. For wrong answers 6 sec will be removed. How can I do this with Python 3.8?
I would add a new methode and using the threading.Timer modul (https://docs.python.org/3/library/threading.html#timer-objects):
from threading import Timer
global time_to_play
time_to_play=2*60 # in seconds
....
def check_for_end:
if time_to_play == 0: # time runs out
print("You lose")
exit(0) # exit program
else: # still playing
t = Timer(2.0, check_for_end) # start Timer wich runs the check methode in 2 sec
t.start()
and now you just have to adjust the global variable time_to_play accordingly.
The Timer will check all 2 seconds, if time_to_play is 0

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()

Resources