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?
Related
I complete all the steps that I am given by my code and finally it asks 'again (Y or N)'. (I have written an except argument that will prevent someone from ending the code by typing a wrong answer) When they input the wrong answer it starts the user back to the top of the code. I would like it to output what step the user was already on.
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
again = str(input("Again? (Y or N) "))
again = again.upper()
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
EDIT:
So I have made some progress but I have one last problem
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
while True:
again = input("again? (Y or N)")
if again not in "yYnN":
continue
break
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
The problem is that the variable 'again' is not defined when outside of the while loop (outside the while loop that is in the while loop). How do I fix this?
You could create another loop (inside this main loop) where you are asking for input, and have a try block there, so that it loops just the section where the user is giving input until they give correct input.
This is my first small python task when i found out about speedtest-cli.
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 2:
print(st.upload())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
i am just a beginner so i could't find any way to shorten this code. Any tips would be helpful :)
If you don't care about execution time but only about code length:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
st.get_servers([])
tst_results = [st.download(), st.upload(), st.results.ping]
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option >= 1 and option <= 3:
print(tst_results[option-1])
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
Did not really make it smarter, just shorter by creating a list and take option as index in the list
First, you can look at this line:
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
this line happens on each of the options, so we don't need to repeat it. instead you can add it at the end of the "while" clause. also add "continue" to your "else" clause to avoid asking this when wrong input is entered.
also, the "else" clause for the "while" loop is not needed
e.g:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice")
continue
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
print("Test is ended")
second, there is an error in your logic. your prompt says enter 1 to continue or 2 to quit, and indeed when you enter 2 the loop will end, but also when the user enters 3 or any other number. Even worse, if a user will enter a character that is not a number or nothing at all, they will get an exception. For this we use try-except clauses. another way to do this kind of loop is using "while "True" and then using "break" to exit.
while True:
... your code here ...
q = input("enter 1 or 2:")
try:
q = int(q)
except ValueError:
print("Invalid input")
if q == 2:
break
print("Test is ended")
This is helpful to you if:
you are a pentester
or you (for some other arbitrary reason) are looking for a way to have a very small python script
Disclaimer: I do not recommend this, just saying it may be helpful.
Steps
Replace all \n (newlines) by \\n
Replace two (or four) spaces (depending on your preferences) by \\t
Put """ (pythons long quotation marks) around it
Put that oneline string into the exec() function (not recommended, but do it if you want to)
Applied to this questions code
exec("""import speedtest\n\nq = 1\nwhile q == 1:\n\t\tst = speedtest.Speedtest()\n\t\toption = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))\n\t\tif\toption == 1:\n\t\t\t\tprint(st.download())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 2:\n\t\t\t\tprint(st.upload())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 3:\n\t\t\t\tservernames =[]\n\t\t\t\tst.get_servers(servernames)\n\t\t\t\tprint(st.results.ping)\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telse:\n\t\t\t\tprint("Please enter the correct choice")\nelse:\n\t\tprint("Test is ended")\n""")
I have found the solution to that by using the sys module. i suppose this could work if a wrong data is input.
import speedtest
import sys
#Loop for options
while True:
st = speedtest.Speedtest()
option = input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: ")
#To check if the input value is an integer
try:
option = int(option)
except ValueError:
print("Invalid input")
continue
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice: ")
continue
q = 0
#Choice to continue or to end
while (q != 1) or (q != 2):
q = input("Enter '1' if you want to continue or Enter '2' if you want to stop the test: ")
try:
q = int(q)
except ValueError:
print("Invalid input")
continue
if q == 1:
break
elif q == 2:
sys.exit("Test is ended")
else:
print("Invalid input")
continue
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.
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.
so getBoundedNumber() is to let the user input some numbers and return the input. My other functions base on the return value and do calculations. I tried to assign it to a global variable outside the function(like var=getBoundedNumber(...)),but instead of storing the value from function, it executes the function again and ask for user to input again. How do I fix this?Thank you!
def getBoundedNumber(qq,ww,ee):
while True:
try:
AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
ee='%r is not between %r and %r'%(AA,qq,ww)
assert type(AA)==float or int,'not a valid input'
if qq<= AA <= ww:
break
else:
print(ee)
except ValueError:
print(' not a valid input')
exit
return AA
This is my main function:
def MAIN():
while True:
xx=menu()
if xx == 'A':
aa=getBoundedNumber(0.5,4.5,1)
elif xx == 'N':
numpoints=getBoundedNumber(10,100000,1)
elif xx == 'P':
print(' Parameter a:%20.3f'%aa,'[m]')#console gives me aa not defined
print(' Number of points:%20d'%numpoints)#console gives me numpoints not defined
print(' Length:%20.3f'%chainlength(xs,ys),'[m]')#this function requires value from aa and numpoints so it won't execute.
print(' Angle with support:%20.3f'%anglewithsupport(g_,dd,aa,numpoints))
print(' Net force:%20.3f'%netforce(),'[N]')
elif xx == 'Q':
break
else:
print(' not a valid option')
exit
This is my menu function
def menu():
print('Main menu choices')
print(' A - enter chain parameter a' )
print(' N - enter number of points in chain' )
print(' P - calculate and print chain results')
print(' Q - quit program')
while True:
try:
SELECTION = input('Enter your selection: ')
if SELECTION.upper()== 'A':
break
elif SELECTION.upper() == 'N':
break
elif SELECTION.upper()=='P':
break
elif SELECTION.upper()=='Q':
break
else:
print('%r is not a valid option'%SELECTION)
except ValueError:
print('%r is not a valid option'%SELECTION)
exit
return SELECTION.upper()
Here's some modified code. Instead of using recursion in MAINMENU, we're now using a while loop. Now we can maintain state within the lexical scope of the method MAINMENU by using local variables chain_param and num_points, which store the values input by the user.
It's important to realize that each function has its own scope. Variables defined in one function are not going to be defined in another function. If we want to pass chain_param and num_points along to a new function, say do_magic, we have to send them as parameters to the method: i.e. do_magic(chain_param, num_points).
Likewise, we want do_magic to pass the calculated value back to MAINMENU, so we return that value and collect it in a new variable defined by the lexical scope of MAINMENU, called magic_answer
def getBoundedNumber(qq,ww,ee):
while True:
try:
AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
ee='%r is not between %r and %r'%(AA,qq,ww)
assert type(AA)==float or int,'not a valid input'
if qq<= AA <= ww:
break
else:
print(ee)
except ValueError:
print(' not a valid input')
return AA
def do_magic(x,y):
if x and y:
return x / y
def MAINMENU():
print('A - enter chain parameter a' )
print('N - enter number of points in chain' )
print('P - calculate and print chain results')
print('Q - quit program')
chain_param = None
num_points = None
magic_answer = None
try:
while True:
SELECTION = input('Enter your selection: ')
if SELECTION.upper() == 'A':
chain_param = getBoundedNumber(0.5,4.5,1)
elif SELECTION.upper() == 'N':
num_points = getBoundedNumber(10,100000,1)
elif SELECTION.upper() == 'P':
#do something with chain_param and num_points to get magic_answer
if chain_param and num_points:
magic_answer = do_magic(chain_param,num_points)
print('Magic Answer = ', magic_answer)
elif SELECTION.upper() == 'Q':
return 1
else:
print('%r is not a valid option'%SELECTION)
except ValueError:
print('%r is not a valid option'%SELECTION)
return -1
MAINMENU()
out
A - enter chain parameter a
N - enter number of points in chain
P - calculate and print chain results
Q - quit program
Enter your selection: A
Enter chain parameter between 0.5 and 4.5 2
Enter your selection: N
Enter chain parameter between 10 and 100000 100
Enter your selection: P
Magic Answer = 0.02
Enter your selection: Q
Declare a global variable and then append the results before the return. Nevertheless you will not append the results because you are calling recursively the MAINMENU function so each execution will have it return value but it will be lost (unless you manage the calls and returns of MAINMENU)
Maybe you can do the same with a while-loop, and keep the values with a global variable.
Another way of achieving the same:
def getBoundedNumber(qq,ww,ee,aList):
while True:
try:
x = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
ee='%r is not between %r and %r'%(AA,qq,ww)
assert type(x)==float or int,'not a valid input'
if qq<= x <= ww:
aList.append(x)
break
else:
print(ee)
except ValueError:
print(' not a valid input')
exit
return aList
def MAINMENU():
print('A - enter chain parameter a' )
print('N - enter number of points in chain' )
print('P - calculate and print chain results')
print('Q - quit program')
AA = []
try:
SELECTION = input('Enter your selection: ')
if SELECTION.upper() == 'A':
AA = getBoundedNumber(0.5,4.5,1,AA)
MAINMENU()
elif SELECTION.upper() == 'N':
AA=getBoundedNumber(10,100000,1,AA)
MAINMENU()
elif SELECTION.upper() == 'P':
#calculations that base on user input from A and N
elif SELECTION.upper() == 'Q':
exit
else:
print('%r is not a valid option'%SELECTION)
MAINMENU()
except ValueError:
print('%r is not a valid option'%SELECTION)