Python Forum
Python, While loop & lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Python, While loop & lists (/thread-11207.html)



Python, While loop & lists - jaki - Jun-28-2018

Hello everyone,
I have a homework assignment where we are supposed to make a basic arithmetics calculator using:
• Lists
• Built-in functions including split(), upper(), len()etc.
• in, not in, == etc. operators
• String manipulation
• Conditional statements (if-elif-else)
• Iterative statements (while)
also
We cannot use the built-in functions eval( ) or exec().
We cannot use break or continue or pass or sys.exit( ) in our Python program.

I'm having difficulties with 2 things:
1) How to end a while loop without using break, our teacher suggested using
carryON = True
# Loop until the user has entered either ‘Q’ or ‘q’
while carryON :
but I don't know how to make the statement False

2) How to add the users values from a list
So far I have:
print("Select operation:")
print(" Add by using the statement: Add N1 and N2")
print(" Subtract by using the statement: Sub N2 from N1")
print(" Multiply by using the statment: Mul N1 by N2")
print(" Divide by using the statment: Div N1 by N2")
print(" Or to Exit enter: Q")
#Ask user for input and display approprite message
operation=input("Enter an arithmetic statement or 'Q' to quit the calculator: ").split()
sum = 
print ("Answer: " +operation[0]+" "+operation[1]+" "+operation[2]+" "+operation[3]+ " = " + (sum))
So if I want to add the values of operation 1&3 how would I do that?
Ex: [Add, 5, and, 3]

Thank you!


RE: Python, While loop & lists - ichabod801 - Jun-28-2018

The while loop is easy. If it's based on a variable, you just set that variable to False:

while carry_on:
    ...
    if operation[0].lower() == 'q':
        carry_on = False
Depending on the structure of your program, you can often simplify this to while operation[0].lower() != 'q':.

If you can expect a list like ['Add', '8', 'and', '1'], you just need to get the second and fourth items (with zero-indexing these are operation[1] and operation [3]), convert them to numbers with the built-in int(), and add them together.