Completing a Startup Menu in Function - Python - python

I'm trying to finish writing this function that contains five different options and uses a While loop to allow the user to enter in their choice with the entry '5' exiting the loop. Below is the code I have so far, I'm having trouble completing the menu part within the def_main function. I keep getting an error after else:
break
Any input would be appreciated. Thank you for reading.
def main():
menuOption = 0
while 1 == 1:
print("1. Expanded Sum\n2. Reverse Expanded Sum\n3. Reverse Integer\n4. Product Table\n5. Exit\n")
menuOption = int(input("Enter correct menu option: "))
while menuOption<1 or menuOption>5:
print("Incorrect menu option!!")
menuOption = int(input("Enter correct menu option: "))
if menuOption == 5:
return
while 1 == 1:
num = int(input("Enter positive Integer: "))
if num <= 0:
print("You have entered negative integer or zero.")
continue
else:
break
if menuOption == 1:
printSum(num, int(False))
elif menuOption == 2:
printSum(num, int(True))
elif menuOption == 3:
print(str(reverseInt(num)))
elif menuOption == 4:
printProductTable(num)
if __name__ == "__main__": main()
def printSum(n, reverse):
s = sum(range(n+1))
if reverse:
print('+'.join(str(i) for i in range(1, n+1)) + ' = ' + str(s))
else:
print('+'.join(str(i) for i in range(n, 0, -1)) + ' = ' + str(s))
def reverse_int(n):
Reverse = 0
while(n > 0):
Reminder = n %10
Reverse = (Reverse *10) + Reminder
n = n //10
print(Reverse)
def printProductTable(n):
for row in range(1,n+1):
print(*("{:3}".format(row*col) for col in range(1, n+1)))

What is the error you are getting at the break?
It looks like your spacing might be off in the continue, I assume your else goes to the if at the top of the statement, but your continue does not match with it.

Rather than doing while 1==1 you can write while True. And also you have already checked while menuOption<1 or menuOption>5. So if your menuOption is a negative number it already falls into this condition as, say, -2 < 1.
And also seems like your code is not formatted. Means, continue is just above the else. It will generate the error. Re-formate your code. Give proper indentation.

Related

How to print superscript in Python

I'm aware of the sympy module in python and I know how to use it most of the time, however, I need to append different values to a list and then join it into a string. I need to append the superscript 'x' at the end of the list. Here's my code:
from functions import *
from subprocess import run
from sympy import pretty_print as pp
from sympy.abc import x
try:
run("clear", shell=True)
print("\033[92m[*] Initializing Exponential Equation Calculator", end='', flush=True)
print_dots(3)
while True:
print("\n\n================================Select Option================================")
print("1. Create exponential equation\n2. Calculate exponential growth\n3. Calculate exponential decay\n4. Exit")
try:
option = int(input(">>> "))
except ValueError:
handle_error("Please enter an option from above")
continue
if option == 1:
equation = ["y = "]
while True:
points_table = get_points()
for j in points_table:
i = 0
status = 0
while i < len(j):
if j[i] == 0:
yInt = j[i + 1]
status += 1
break
i += 1
if status == 1:
break
growth_rate = find_pattern(points_table)
if growth_rate is None:
handle_error("There is no exponential pattern in the table provided. Try again", 1)
continue
equation.append(str(yInt))
equation.append(" * ")
equation.append(str(growth_rate))
result = ''.join(equation)
print(f"\033[93m[*] Equation Calculated! The equation is \033[96m{result}\033[92m")
sleep(2)
while True:
try:
print("================================Select Option================================")
print("Would you like to:\n\n1. Calculate another equation\n2. Choose a different option\n3. Exit")
choice = int(input(">>> "))
if choice == 1 or choice == 2:
break
elif choice == 3:
raise KeyboardInterrupt
else:
handle_error("Please enter a valid option")
continue
except ValueError:
handle_error("Please enter a valid option")
continue
if choice == 2:
break
elif option == 2:
pass
elif option == 3:
pass
elif option == 4:
raise KeyboardInterrupt
else:
handle_error("Please enter an option from above")
continue
break
except KeyboardInterrupt:
print("\n\033[96m[*] Shutting down...\n\033[0m")
exit(0)
In the lines where there's 3 append functions, I don't know how I'm supposed to add the superscript 'x' to the end of the list. Can someone help me please?

Giving one hint for each of the tries (guessing number game)

I am making a game which requires the user to enter a number. They get four tries, and if they get the number wrong, they get a hint.
How can I try to give only one hint for each of the four tries the user has to get the number right? For example, after the user gets the first try wrong, I would like the program to display the even_or_odd hint.
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
for x in range(1, 5):
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {x}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number and x == 1: #hint after first attempt
print('You win!')
break
else:
print('Incorrect!')
hint.even_or_odd()
if user_input == new_number and x == 2: #hint after second attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple3to5()
if user_input == new_number and x == 3: #hint after third attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple6to10()
if x == 4:
print('You are out of attempts!')
print(f'The number was {new_number}')
break
You should make one if statement that checks for the correct answer. In the else statement you can use if - elif statements to check for the attempt number.
if user_input == new_number:
print('You win!')
break
else:
print('Incorrect!')
if x == 1:
hint.even_or_odd()
elif x == 2:
hint.multiple3to5()
elif x == 3:
hint.multiple6to10()
else:
print('You are out of attempts!')
print(f'The number was {new_number}')
The reason you see multiple hints on attempt is that for multiple if statements their condition is not true, so their 'else' block is run
Here is a neat trick:
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
self.choices = {
1: self.even_or_odd,
2: self.multiple3to5,
3: self.multiple6to10
}
def run(self,key):
action = self.choices.get(key)
action()
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
else:
print("Well, Not a multple of 3 or 5")
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
else:
print("Well, Not a multple of 6 or 10")
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
print(new_number)
i = 3
win = False
while i >= 1 :
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {i}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number:
print('You win!, Number is: {new_number}')
win = True
break
hint.run(i)
i -= 1
if not win:
print("You lost!")
print(f"Number is {new_number}")

How do i not print it twice

I'm new to python and experimenting with functions. Here's the sample code that I'm working wtih
def menu():
print(" 1. Divide")
def test1(x,y):
if y == 0:
return "The result is undefined"
else:
return x/y
num1=int(input("First: "))
num2=int(input("Second: "))
menu()
answer=int(input("Choose: "))
while answer != 0:
if answer == 1:
print()
print(" The result is", test1(num1,num2))
print()
menu()
answer=int(input("Choose: "))
When I run the program and input a y value of 0, the result prints twice. How do I make it print once only then return to menu? Thank you
This is not a bug in your code,
you can simply Change your zero condition to this:
if y == 0:
return "undefined"

Access a function variable from outside the function in python

I have a python function and would like to retrieve a value from outside the function. How can achieve that without to use global variable. I had an idea, if functions in python are objects then this could be a right solution?
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
while check_difficulty.tries > 0:
I am new to python so excuse me...
def check_difficulty(difficulty):
if (difficulty == 1):
return 10
elif (difficulty == 2):
return 5
elif (difficulty == 3):
return 3
tries = 0
while tries > 0:
difficulty = int(input("Choose your difficulty: "))
tries = check_difficulty(difficulty)
tries = tries - 1
if you use a while loop and put everything inside in a structured way, a function will not be needed.
You can change this to a class to get your tries:
class MyClass:
def __init__(self):
self.tries = 0
def check_difficulty(self, difficulty):
if (difficulty == 1):
self.tries = 10
elif (difficulty == 2):
self.tries = 5
elif (difficulty == 3):
self.tries = 3
ch = MyClass()
try:
difficulty = int(input("Choose your difficulty: "))
ch.check_difficulty(difficulty)
except ValueError:
difficulty = int(input("Type a valid number: "))
ch.check_difficulty(difficulty)
ch.tries
# 5
If you want the question answered within the construct of your current code simply put your try, except before the function. You can call a function anywhere in the code it doesn't ave to be after the function is created . So something like this:
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
while check_difficulty.tries > 0:
however, I would have to agree with the other answers and just kind of put everything together within the same loop and you won't have to worry about this. I created a guessing game recently that actually had something similar to this. Here is the difficulty portion of that code:
def guessing_game():
again = ''
# Define guesses/lives
while True:
try:
guesses_left = int(input('How many guess would you like(up to 4)?: '))
if 1 > guesses_left or guesses_left > 4:
print('You must choose between 1 and 4 for your guess amount. Try again.')
continue
break
except:
print('You must enter a valid number between 1 and 4. Try again.')
# Define difficulty based on guesses_left
difficulty = ''
if guesses_left == 1:
difficulty = 'Hard Mode'
elif guesses_left == 2:
difficulty = 'Medium Mode'
elif guesses_left == 3:
difficulty = 'Easy Mode'
elif guesses_left == 4:
difficulty = 'Super Easy Mode'
print('You are playing on ' + difficulty + ' with ' + str(guesses_left) + ' guesses.')
#code continues under this line to finish#

Encryption / Decryption String Indices Must Be Integers

I have spent a lot of time creating this encryption program that is specific to an assignment. The encryption works perfectly, i thought i would be able to copy the code and do the opposite to decrypt the message, however i receive the error:
letter = encryptionCharacters[temp_k]
"TypeError: String indices must be integers"
Not sure if anyone can fix this issue to be able to decrypt a message, but hopefully someone can give me some help.
Steps to use the program:
Select option 1 by entering that number from the menu.
Enter 854417 as the number
Then press 2 and choose a message to encrypt / decrypt.
from itertools import cycle
listOfDigits = []
listOfIllegalCharacters = []
encryptionCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz .'
encryptedMessageLettersPosition = []
decryptedMessageLettersPosition =[]
encryptedMessageList = []
def main(): #This Function is the base of the main menu
print()
print("********* Welcome to the Encryption Program *********")
print()
while True: #Start of while loop to get the users choice.
try: #Start of try method.
choice = int(input("""
1: Set Person Number
2. Encrypt a Message
3. Decrypt a Message
4. Quit
Please Choose an Option (1 - 4): """)) #Interactive menu itself taking in the users option as an integer.
except ValueError: #End of try method, in order to catch the possible value error of entering a string instead of an integer.
print("!!!!!!ERROR!!!!!!")
print()
print("ERROR: Choice was not valid!")
print("Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main() #Call to menu method (a.k.a restart).
if choice == 1:
personNumberInput() #Call to personNumberInput method, which allows the user to enter their personal ID number for the encryption.
elif choice == 2:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageEncrypt()
elif choice == 3:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageDecrypt()
elif choice == 4:
menuQuit()
else:
print()
print("!!!!!!ERROR!!!!!!") #If none of the options are chosen, restart and provide a suitable error message.
print()
print("You must only select 1, 2, 3 or 4.")
print("Please Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main()
def menuQuit(): #This function is the 4th option on the menu.
print()
userOption = input("Are you sure you want to Quit / Exit the Program? (Y/N): ") #Taking the users input to get their decision.
if userOption == "y":
exit()
elif userOption == "Y":
exit() #Exit the program if the user confirms their choice with "y" or "Y".
else:
print()
print("You have been returned to the Main Menu")
main() #Returning the user to the menu for any other option including "n" or "N".
def personNumberInput():
while True:
try:
print()
personNumber = int(input("Please enter your Person Number: ")) #Checking the input from the user.
except ValueError: #Catching the value error of unexpected value (non integer).
print()
print("ERROR: Person Number contained a non integer, Try Again")
continue
else:
personNumberInt = len(str(abs(personNumber))) #Getting the length of the string as well as the absolute value of each digit entered.
break
while True:
if (personNumberInt) != 6: #If the length of the number entered is not 6, try again.
print()
print("ERROR: Person Number length not equal to 6, Try Again")
return personNumberInput()
else:
print()
print ("The Person Number you have entered is:", personNumber)
print ("Ready to Encrypt / Decrypt a Message")
personNumberDigits = [int(x) for x in str(personNumber)]
listOfDigits.extend(personNumberDigits)
break
def messageEncrypt():
print()
message = input("Please Enter a Message to Encrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit - value*3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
print()
print ("Your message has been Encrypted!")
print ("Encrypted Message Output:",(''.join(encryptedMessageList)))
encryptedMessageLettersPosition.clear()
encryptedMessageList.clear()
def messageDecrypt():
print()
message = input("Please Enter a Message to Decrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit + value/3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
main()
Try making temp_k an integer using int()
temp_k = int( k % len(encryptionCharacters) )
letter = encryptionCharacters[temp_k]
Some of the values in encryptedMessageLettersPosition are floats, not integers.
Therefore temp_k = k % len(encryptionCharacters) sometimes returns a float value, and you cannot use a float as a string index.

Categories