Python Forum
Python, While loop & lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python, While loop & lists
#1
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!
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Hot mess with functions, lists, and while loop johneven 7 4,624 Jul-15-2019, 09:47 PM
Last Post: johneven

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020