Python String Iteration/Functions - python

I need my 'items' variable to print each item on a new line. I keep getting a total in 'items' and the total in 'total'. The 'total' prints out how I want, but I want the items to print individually.
Thoughts?
def adding_report():
user_input = input("Report Types include All Items ('A') or Total Only ('T')\nChoose Report Type ('A'or'T'):")
items = "\n"
total = 0
while True:
if user_input == 'A'.lower():
user_input1 = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input1.isdigit():
items = int(user_input1)
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower():
print("Items\n", items)
print("Total\n", total)
break
elif user_input1.startswith('q'):
print('Items\n', int(items))
print("Total\n", total)
break
else:
print("Input is not valid")
elif user_input == 'T'.lower():
user_input2 = input("Input an integer to add the total or 'Q' to quit: ")
adding_report()

user_input = raw_input("Report Types include All Items ('A') or Total Only ('T')\nChoose Report Type ('A'or'T'):")
items=[]
total = 0
print user_input
total = 0
while True:
user_input1 = raw_input("Input an integer to add to the total or 'Q' to quit: ")
if user_input == 'A'.lower() or user_input == "A":
if user_input1.isdigit():
items.append(int(user_input1))
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower() or user_input1 =="Q" or user_input1.startswith('q'):
print "List of items is"
for item in items:
print item
print "Total ", total
break
else:
print("Input is not valid")
elif user_input == 'T'.lower() or user_input == "T":
if user_input1.isdigit():
items.append(int(user_input1))
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower() or user_input1 =="Q" or user_input1.startswith('q'):
print "Total ",total
break
else:
print("Input is not valid")

Here is a modified code. It is hard to exactly understand what your script is supposed to do:
import textwrap # nice library to format text inside functions
def adding_report():
# initiate variables
total = 0
items = 0
# Make sure you get the right input
while True:
user_input = input(textwrap.dedent("""\
Report Types include All Items ('A') or Total Only ('T')
Choose Report Type ('A'or'T'):"""))
if user_input list("AT"):
break
# Create a loop where you ask the user for input
# Q or q quits (the print is outside the function)
while True:
user_input1 = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input1.lower() == 'q':
break
if user_input1.isdigit():
if user_input == 'A':
items = int(user_input1)
total += int(user_input1)
elif user_input == 'T':
total += int(user_input1)
else:
print("Input is not valid")
# Return variables
return items,total
items,total = adding_report()
print("Items\n", items)
print("Total\n", total)

Here's my attempt at understanding what you trying to do:
print("Report Types includes All Items ('A') or Total Only ('T')")
report_type_raw = input("Choose Report Type ('A' or 'T'): ")
report_type = report_type_raw.lower()
if report_type in 'at':
items = []
total = 0
user_input = ''
while user_input != 'q':
user_input_raw = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input_raw.isdigit():
current_item = int(user_input_raw)
if report_type == 'a':
items.append(user_input_raw)
total += current_item
user_input = ''
else:
user_input = user_input_raw.lower()
if user_input != 'q':
print("Input is not valid")
if report_type == 'a':
how_items_to_be_printed = ', '.join(items)
print("Items :", how_items_to_be_printed)
print("Total :", total)
else:
print("Report type is not valid")
Otherwise you'll have to clarify what you were trying to do.

Related

if statement calls out out to one function only, why? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
see this is my code
print("""1. ADD
2. SUBTRACT
3. MULTIPLY
4. DIVIDE
5. SQUARE
6. SQUARE ROOT
7. CUBE
8. CUBE ROOT
9. POWER OF A NUMBER
10. FACTORIAL
11. TRIANGLE'S PERIMETER
12. TRIANGLE'S AREA
13. QUADRILATERAL'S PERIMETER
14. PARALLELOGRAM'S AREA
15. RHOMBUS'S AREA
17. RECTANGLE'S AREA
18. SQUARE'S AREA
19. TRAPEZIUM'S AREA
20. CIRCLE'S CIRCUMFERENCE
21. CIRCLE'S AREA
22. QUADRATIC EQUATION
23. SIMPLE INTEREST
24. COMPOUND INTEREST""")
while True:
user = str(input("Enter GO to continue or Q to exit: "))
if user == 'GO':
user_input = str(input("Enter here the serial number or the name in capital for what you want to calculate: "))
if user_input == 'ADD' or 1 :
add()
elif user_input == 'SUBTRACT' or 2 :
sub()
elif user_input == 'MULTIPLY' or 3 :
mlt()
elif user_input == 'DIVIDE' or 4 :
div()
elif user_input == 'SQUARE' or 5 :
sqr()
elif user_input == 'SQUARE ROOT' or 6 :
sqrt()
elif user_input == 'CUBE' or 7 :
cube()
elif user_input == 'CUBE ROOT' or 8 :
cube_root()
elif user_input == 'POWER OF A NUMBER' or 9 :
power()
elif user_input == "TRIANGLE'S PERIMETER" or 11 :
triangle_perimeter()
elif user_input == "QUADRILATERAL'S PERIMETER" or 13 :
quadrilateral_perimeter()
elif user_input == "PARALLELOGRAM'S AREA" or 14 :
parallelogram_area()
elif user_input == 'FACTORIAL' or 10 :
factorial()
elif user_input == "RHOMBUS'S AREA" or 15 :
rhombus_area()
elif user_input == "RECTANGLE'S AREA" or 17 :
rectangle_area()
elif user_input == "SQUARE'S AREA" or 18 :
square_area()
elif user_input == "CIRCLE'S AREA" or 21 :
circle_area()
elif user_input == "CIRCLE'S CIRCUMFERENCE" or 20 :
circle_circumference()
elif user_input == "QUADRATIC EQUATION" or 22 :
qaudratic_solver()
elif user_input == "SIMPLE INTEREST" or 23 :
simple_interest()
elif user_input == "COMPOUND INTEREST" or 24 :
compound_interest()
elif user_input == "TRIANGLE'S AREA" or 12 :
triangle_area()
elif user_input == "TRAPEZIUM'S AREA" or 19 :
trapezium_area()
else:
print("Invalid input!!")
elif user == 'Q':
break
else:
print("Invalid input!!")
and when I run it when I put any number or name in the input line instead of calling out the function with respect to the number or name it calls out to the add() function which relates number 1 and and name "ADD"
Why is this happening? Please help me...
PS: I had done this in google colab so the actual functions are written in a separate "cell" if you know google colab you'll know :) but anyways here are functions too
import cmath
import functools
def add():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1 + val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sub():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1 - val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def mlt():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def div():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1/val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sqrt():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", cmath.sqrt(val1))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sqr():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val1**2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def power():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
val2 = float(input("Enter the power of the number: "))
print("The result is: ", val1**val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def square_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of the side: "))
print("The area of the square is: ", val1**2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def rectangle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of the length: "))
val2 = float(input("Enter the value of the breadth: "))
print("The area of the square is: ", val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def circle_circumference():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the radius of the circle: "))
print("The circumference of the circle is: ", (val1*44)/7)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def circle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the radius of the circle: "))
print("The area of the circle is: ", (val1*val1*22)/7)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def rhombus_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of first diagonal: "))
val2 = float(input("Enter the value of the second diagonal: "))
print("The area of the rhombus is: ", 0.5*val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def parallelogram_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of height: "))
val2 = float(input("Enter the value of the correspondent base: "))
print("The area of the parallelogram is: ", 0.5*val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def quadrilateral_perimeter():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the first side of the quadrilateral: "))
b = float(input("Enter the second side of the quadrilateral: "))
c = float(input("Enter the third side of the quadrilateral: "))
d = float(input("Enter the foruth side of the quadrilateral: "))
if ((a + b + c> d) and (a + b + d> c) and (b + c + d> a) and (a + d + c> b)) :
print("The perimeter of the qaudrilateral is : ", a+b+c+d)
else :
print("Quadrilateral is not valid.")
elif user_input == 'Q':
break
else:
print("invalid input")
def trapezium_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
par1 = float(input("Enter the value of the first parallel side: "))
par2 = float(input("Enter the value of the second parallel side: "))
hei1 = float(input("Enter the the value of the height: "))
print("The area of the trapezium is: ", 0.5*hei1*(par1+par2))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def triangle_perimeter():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
if ((a + b > c) and (a + c > b) and (b + c > a)) :
print("The perimeter of the traingle is: ", a+b+c)
else :
print("Triangle is not valid.")
elif user_input == 'Q':
break
else:
print("invalid input")
def triangle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
area_method = str(input("Enter Heron or Traditional(0.5*height*base): "))
if area_method == 'Heron':
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
if ((a + b > c) and (a + c > b) and (b + c > a)) :
s = (a+b+c)*0.5
print("The area of the triangle is ", cmath.sqrt((s-a)*(s-b)*(s-c)*(s)))
else:
print("Triangle is not valid!!")
elif user_input == 'Traditional':
a = float(input("Enter the value of the height: "))
b = float(input("Enter the value of the correspondent base: "))
print("The area of the triangle is ", 0.5*a*b)
else:
print("Invalid input!!")
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def qaudratic_solver():
while True:
user_input = str(input("Enter the GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the coeffiecient of x^2: "))
b = float(input("Enter the coeffiecient of x: "))
c = float(input("Enter the constant: "))
D = cmath.sqrt(b*b - 4*a*c)
F = 2*a
X1 = (-b + D)/(F)
X2 = (-b - D)/(F)
print("The values of x are: ", X1, ", ", X2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def cube():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val1**3)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def cube_root():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val**1/3)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def compound_interest():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
P = float(input("Enter the principal amount: "))
IR = float(input("Enter the interest rate: "))
T = float(input("Enter the time period: "))
N = float(input("Enter the number of times interest is compunded per unit time 't': "))
A = P*((1+((IR/100)/N))**(N*T))
CI = A-P
print("The final amount will be ", A, " and the compund interest will total up to ", CI)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def simple_interest():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
P = float(input("Enter the principal amount: "))
R = float(input("Enter the interest rate: "))
T = float(input("Enter the time period: "))
SI = (P*R*T)/100
A = P + SI
print("The final amount will be ", A, " and the simple interest will total up to ", SI)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def factorial():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = int(input("Enter the number: "))
print(functools.reduce(lambda x,y : x * y, range(1,a+1)))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
The condition in:
if user_input == 'ADD' or 1:
doesn't quite do what you think it does.
Each side of an or is usually a separate sub-expression that is evaluated independently, then the results are or'ed together. The proper expression for your case would be:
if user_input == 'ADD' or user_input == '1':
Note the quoted '1' in my version, the string '1' is not the same as the integer 1, and you are working with strings here.
However, a more Pythonic way would be:
if user_input in ['ADD', '1']:
which would allow you to keep code much shorter for things like:
if number in [2, 3, 5, 7, 11, 13, 17, 19]:
print(f"{number} is a prime under twenty")
Interestingly enough, the result of an expression False or something is not necessarily True or False, it's actually something. You can see this with the following transcript:
>>> True or 'hello'
True
>>> False or 'hello'
'hello'
More detail can be found here:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value.
When the something is an expression like a == b, it is a boolean value that comes out. But that's not the or doing that, it's the comparison.
That means the result of the expression you've used, user_input == 'ADD' or 1, will be True if the input was ADD, or 1 if not.
And it's not until you evaluate that 1 in a truthy context that it gets forced to True. Python's truthiness rules are basically everything is truthy except for:
empty strings.
empty collections (lists, tuples, dictionaries, sets, frozensets, and ranges).
zero of any numeric type (integer, floating point, or complex).
None.
user defined classed that implement the __bool__ method and decide to return a falsey value.
and, of course, False itself.
And, just as an aside, you should probably be aware that input() already gives you a string, there's no need to call str() on it.
In other words, the expression str(input("What? ")) is about as useful as int(42), harmless but unnecessary :-)
The or statement is to check for another condition. Here with your or 1 you are checking if 1 != 0 (because in boolean is 0 is false and everything else is true).
So what you need in the end is to check if user_input is 1.
You need to change your conditions line to if user_input == 'ADD' or user_input == '1' :
EDIT: as paxdiablo said if user_input in ['ADD', '1'] would be a more pythonic way to do it.
Hope this helps and you understood your mistake.
if user_input == 'ADD' or 1 :
The above condition is evaluates to true due to 1.

How to stop the list, missing number from user enter

I'm doing this exercise:
In your main function, you need to keep asking user to enter an
integer, then store those integers in a list. Once the user decides to
stop entering, the function should print out all the integers from the
list, and also find the largest number in that list. If the user did
not enter any number, you should print out “Your list is empty”.
I tried to code it but I got stuck on print "Your list is empty". I don't know where to put the statement.
And when the user enters the number, the list will come out missing the first number the user entered.
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
index = 0
while index < len(user_list):
user_list[index] = int(user_list[index])
index += 1
print ('Here is the list of the numberyou entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your listis: ',largest)
main()
Simple, change:
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
To:
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(user_num)
elif not user_list:
print('Your List is empty')
exit()
else:
break
Here is the optimized code:
def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(int(user_num))
elif not user_list:
print('Your List is empty')
exit()
else:
break
print ('Here is the list of the numbers you entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your list is: ', largest)
main()
if user_list == []:
print('Your List is empty')
exit()
You should write this portion outside the while loop. Like this
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num == 'x':
break # exit the "while" loop
user_list.append(user_num)
# this is after the loop:
if user_list == []:
print('Your List is empty')
exit()
# user_list = list(map(int, user_list))
for index in range(len(user_list)): # range is a list-like thing of 0, 1, 2, 3... up to the length of the list
user_list[index] = int(user_list[index])
print ('Here is the list of numbers you entered:')
print (*user_list, sep='\n')
largest = max(user_list)
print ('The largest number in your lists: ', largest)
main()

How do I use function 1 inside function 2 without getting an error?

I declared the view_songs() function which I want to use separately and I also want to use it inside another function add_songs() with a conditional, after the code which does the part of adding songs to the collection.
user_input = input('Enter "a" to add songs,"f" to find existing songs,"v" to view entire collection and "q" to quit :')
while user_input != "q":
if user_input == "v":
def view_songs():
for song in enumerate(Songs_collection, 1):
print(song)
view_songs()
elif user_input == "a":
def add_songs():
elements_in_list = len(Songs_collection)
song_name = input('Enter the name of the song to be added to the collection: ')
song_artist = input('Enter the name of the artist of the song which was added previously :')
Songs_collection.insert(elements_in_list, ({elements_in_list + 101: f'{song_name}', f'{elements_in_list + 101}_Artist': f'{song_artist}'}))
print('Song added to the collection!')
post_add_input = input('Press "v" to print whole collection or "q" to quit:')
if post_add_input == "v":
view_songs()
elif post_add_input == "q":
print('Quitting loop...')
else:
print('Invalid Input')
add_songs()
It gives me an error which says free variable view_songs referenced before assignment in the enclosing scope. How can I go about to using this function inside add_Songs()?
As per my comment above this should hopefully solve the issues you're having?
def view_songs():
for song in enumerate(Songs_collection, 1):
print(song)
def add_songs():
elements_in_list = len(Songs_collection)
song_name = input('Enter the name of the song to be added to the collection: ')
song_artist = input('Enter the name of the artist of the song which was added previously :')
Songs_collection.insert(elements_in_list, ({elements_in_list + 101: f'{song_name}', f'{elements_in_list + 101}_Artist': f'{song_artist}'}))
print('Song added to the collection!')
post_add_input = input('Press "v" to print whole collection or "q" to quit:')
if post_add_input == "v":
view_songs()
elif post_add_input == "q":
print('Quitting loop...')
else:
print('Invalid Input')
while user_input != "q":
if user_input == "v":
view_songs()
elif user_input == "a":
add_songs()
#Some way to redefine user_input?
#user_input = input()

Python while loop isn't doing as expected

I'm trying to complete my assignment and have been struggling. The idea is that you select report type, A or T. From there you enter keep entering integers until you quit. Once you quit, it should print out the total of integers added together for report 'T'; or for report 'A', it should print the total, plus a list of integers entered.
The problem I'm encountering at the moment is from report 'T', once I'm entering integers nothing will make it error or quit. It just keeps constantly asking me to enter another integer. Then from report 'A', every integer I enter it just comes up with 'invalid input'. I'm sure there are probably plenty more issues with my code but can't get past these ones at the moment. Any pointers would really be appreciated. Thanks
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an ingteger to add to the total or \"Q\" to quit: ")
if report.upper == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
while True:
if report.upper() in "A T":
adding_report(report)
else:
print ("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")
The in operator needs a collection of possible values. Use
if report.upper() in ("A", "T")
or (closer to what you have)
if report.upper() in "A T".split()
Your first problem is in this line:
if report.upper == "A":
This always evaluates to False, because report.upper is a function object, not a value. You need
if report.upper() == "A":
to return the value. You would also do well to rename the input variable and replace its value to the internal one you want:
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
report = report.upper()
This saves you the mess and time of calling upper every time you access that letter.
Please look through your code for repeated items and typos; you'll save headaches in the long run -- I know from personal experience.
Try this
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an integer to add to the total or \"Q\" to quit: ")
#You used "report.upper" instead of "report.upper()"
if report.upper() == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
#You forgot ot add this : "items.append(user_number)"
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
break
#Add this for loop termination: "or 0 to quit: "
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\" Or 0 to quit: ")
while True:
#it should be this ""if report.upper() in "A" or "T":"" not this ""if report.upper() in "A T":""
if report.upper() in "A" or "T":
adding_report(report)
#The condition below terminates the program
elif report == '0':
break
else:
print("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")

Not decrypting what I have encrypted [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having an issue with my decryption algorithm. It outputs to a text file a huge list of repeated ((((( and other things. What's wrong with my code, and how can I fix it? I think it has something to do with the last function of the decrypting process. But I am not sure.
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&()-_=+[]{}\\|;:\'",./<>?\n\t '''
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (evenChars >(oddChars)):
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
for ch in text: #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(ch)
else:
oddNums.append(ch)
index += 1
decrypted= []
if (evenNums >(oddNums)):
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line + "\n"
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
matrices = getMatrices(text)
for value in matrices:
encrypted_file.write(str(value) + "\n")
encrypted_file.close()
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()
Well this was a fun one!
in def convertToNum(ch): the alpha does not equal the alpha in def outPutString(text): (missing an *) causing (in my case) tabs instead of spaces and a ? to appear at the end of my decrypted string. I would recommend using a global variable to prevent things like this happening in the future.
Your encryption algorithm worked great and didn't need any adjustment. There were some incompatible variable types in the decryption phase but I managed to get everything to work and have included the working code (my comments marked with ##) I hope this helped.
Edit: As Eric points out in the comments, if (evenNum>(oddNum)) is probably not doing what you want it to do. According to the python docs:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
I Assume you want to compare the lengths of the two arrays to make sure they are equal. If this is the case then you would want to use if (len(evenNum)>len(oddNum))
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' #you forgot your asterix
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (len(evenChars) >len(oddChars)): ## comparing lengths instead of contents
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
newText = text[0].strip('[ ]') ## these two lines convert the string to an array
textArray = newText.split(',')
for ch in textArray: ## changed text to textArray(see above) #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(int(ch)) ## converting string number to int for later operations
else:
oddNums.append(int(ch))
index += 1
decrypted= []
if (len(evenNums) >len(oddNums)): ## comparing lengths instead of arrays
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
print(finalString)
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line ##+ "\n" ##you don't need to add a new line as '\n' is already included at the end of every line.
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
##matrices = getMatrices(text)
##for value in matrices:
##encrypted_file.write(str(value) + "\n")
##encrypted_file.close()
## I added the line below(and removed lines above) to be consistent with your later usage
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()

Categories