'int' object not subscriptable error - python

while 1 == 1:
import csv
from time import sleep
import sys
bill = 0
with open('list2.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
GTINs = []
products = []
prices = []
for row in readCSV:
GTIN = row[0]
product = str(row[1])
price = float(row[2])
GTINs.append(GTIN)
products.append(product)
prices.append(price)
x = 1
print("Welcome to the GTIN shop!")
while x == 1:
try:
sleep(1)
print("Please input the 8 digit GTIN code")
sleep(0.5)
GTIN0 = GTIN[0]
GTIN1 = GTIN[1]
GTIN2 = GTIN[2]
GTIN3 = GTIN[3]
GTINx = input("--> ")
The error brought up here is that on the lines GTIN0 = GTIN[0] etc, the 'int' object not subscriptable, I can't work out how to fix it, it used to work before.
For reference, here is "list2.txt".
45112454,Milk,1.29
55555555,Bread,0.49
87595376,Milkshake,1.99
The next error comes up here (continuing from last segment):
GTINx = input("--> ")
if GTINx == GTIN0:
product1 = products[0]
price1 = prices[0]
x = 2
elif GTINx == GTIN1:
product1 = products[1]
price1 = prices[1]
x = 2
elif GTINx == GTIN2:
product1 = products[2]
price1 = prices[2]
x = 2
elif GTINx == GTIN3: (this one is just here for if another one is added)
product1 = products[3]
price1 = prices[3]
x = 2
else:
print("Have another go")
except:
print("ERROR - Try Again")
To retrieve milk, the code is 7. For bread the code is 8, and for milkshake, the code is 9. I have no idea where python got these numbers from...
while x == 3:
try:
sleep(1)
print("So you would like", number, product1, "?")
sleep(0.5)
confirmation = input("Please enter \"YES\" or \"NO\": --> ")
if confirmation == ("YES") or ("Yes") or ("yes"):
x = 4
elif confirmation == ("NO") or ("No") or ("no"):
x = 1
else:
sleep(0.5)
print("Have another go")
except:
print("ERROR - Try Again")
So, this was supposed to end that loop, and send them back to the start if they said no (relooped via while 1 == 1:) but, it acts as if they said yes, no matter what was typed.
Next is a similar issue...
while x == 4:
try:
cost = price1 * number
bill = bill + cost
print("The cost is", cost)
sleep(5)
print("Would you like to purchase anything else?")
sleep(0.5)
anythingelse = input("Please enter \"YES\" or \"NO\": --> ")
sleep(1)
if anythingelse == ("YES") or ("Yes") or ("yes"):
x = 1
elif anythingelse == ("NO") or ("No") or ("no"):
x = 5
else:
sleep(0.5)
print("Have another go")
except:
print("ERROR - Try Again")
Again, it answers yes, no matter what is inputted.
Sorry for the spam, thanks for any help that I get.

For your loops if confirmation == ("YES") or ("Yes") or ("yes"):
That's never going to work in Python because you are basically asking if confirmation is equal to "YES" or if ("Yes") or if ("yes") ; and if ("Yes") is true because it's valid and not None or 0 or empty. You want:
if confirmation == ("YES") or confirmation == ("Yes") or confirmation == ("yes"):
There are other ways to do your or checking but I'm just going to correct what you have.
As the comments and other answers has pointed out, a better way of checking "yes" would be:
if confirmation.lower() == "yes"
Just turn the input to lower case and check the value.
As for your first issue. GTIN0 = GTIN[0] do you mean GTIN0 = GTINs[0]. Because GTIN is an int not something "subscriptable" just like what the error is telling you.
As for your second issue with GTIN0 and what not, see if the fix fixes it for you since the GTIN0 and so on, was never set correctly. Edit your question if it's still wrong after the fixes.
Also this line
elif GTINx == GTIN3: (this one is just here for if another one is added)
is not really correct for commenting (I'm guessing your commenting, use a # in front of comment lines)
elif GTINx == GTIN3: #(this one is just here for if another one is added)

In relation with the 'if' comparison issue, I would recommend you to firstly remove the Upper format from the string and then compare. It would be then more idiomatic and also youre problem would be solved:
if anythingelse.lower() == ("yes"):
x = 1
elif anythingelse.lower() == ("no"):
x = 5
else:
sleep(0.5)
print("Have another go")

Related

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\": ")

Python Coursework tidying

I need help with a one or two things on my coursework. firstly when I input an incorrect username/password it will output more than one error message at a time. Secondly, when the men function ends the program will go back to the login loop( that allows the user to re-enter their username/password), I have fixed this by using the B variable but this feels extremely janky and I know there is a better way of doing it. Any Modifications or Tips are greatly appreciated (even if they're not related to my above problems). also the way i code is a bit weird so it's probs best you read from bottom to top :)
def quiz():
print ("quiz")# place holder for real code (let's me know the function has been run)
def report():
print ("report") # place holder for real code (let's me know the function has been run)
def a_menu():# Admin menu
print ("Welcome to the student quiz!")
print ("Please choose a option")
while True:
print ("1: Computer science")
print ("2: Histroy")
print ("3: Reports")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
elif menu_in == 3:
report()
break
else:
print ("Invalid input! Please try again..")
def menu():
print ("Welcome to the student quiz!")
print ("Please choose a quiz")
while True:
print ("1: Computer science")
print ("2: Histroy")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
def login():
b = False
print ("Please enter your username and password")
while True:
if b == True:
break
log_user = input("Username:")
log_pass = input ("Password:")
with open("D:\\Computer science\\Computing test\\logindata.txt","r") as log_read:
num_lines = sum(1 for line in open('D:\\Computer science\\Computing test\\logindata.txt'))
num_lines = num_lines-1
for line in log_read:
log_line = log_read.readline()
log_splt = log_line.split(",")
if log_user == log_splt[0] and log_pass == log_splt[2]:
if log_splt[5] == "a": # Admin will have to mannually change the admin status of other user's through .txt file.
b = True
a_menu()
else:
b = True
log_read.close()
menu()
break
else:
print ("Incorrect username or password, please try again!")
def register():
print ("enter your name, age, and year group and password")
while True:
reg_name = input("Name:")
reg_pass = input ("Password:")
reg_age = input ("age:")
reg_group = input ("Year Group:")
print ("Is this infomation correct?")
print ("Name:",reg_name)
print ("password:",reg_pass)
print ("Age:",reg_age)
print ("Year Group:", reg_group)
reg_correct = input ("[Y/N]").lower()
if reg_correct == "y":
reg_user = reg_name[0:3]+reg_age
reg_write = open("D:\\Computer science\\Computing test\\logindata.txt","a")
reg_write.write (reg_user+","+reg_name+","+reg_pass+","+reg_age+","+reg_group+","+"u"+"\n")
print ("Your username is:",reg_user)
reg_write.close()
login()
break
elif reg_correct == "n":
print ("Please Re-enter your infomation")
else:
Print ("Invalid input! Please try again...!")
def login_ask():
print ("Do you already have an account?")
while True:
ask_in = input("[Y/N]").lower()
if ask_in == "y":
login()
break
elif ask_in == "n":
register()
break
login_ask()

How to I make a code Loop 3 times in Python as well as having a while loop around it

Very limited on using python and totally stuck, I've managed to get a while loop running on the code below so that the user can keep entering a code until they put in the correct one.
What I'm now looking to do is add a for loop so that it only asks the user to enter the code (4 wrong digits) 3 times and then locks them out. At the same time it needs a while loop to ensure if the user puts more than or less than 4 digits it continually runs and doesn't lock them out.
I just cant get the for loop and while loop working at the same time and don't know what I'm doing wrong.
user = ("1234")
valid = False
while not valid:
#for i in range (3):
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
if user != ("1234") :
print ("that is incorrect, please try again")
valid = False
elif len(user) > 4:
print ("That is incorrect, please try again")
valid = False
elif len(user) < 4:
print ("That is incorrect, please try again")
valid = False
else:
print ("You have been locked out!! Alarm!!!!!!")
user = ("1234")
counter = 0
while counter < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if len(user) != 4:
print("I said 4 digits!")
continue
if user == ("1234") :
print("You have cracked the code, well done")
break
print ("that is incorrect, please try again")
counter += 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
else:
print ("Everything is fine.")
I adapted your code a little bit and added a counter variable
user = ("1234")
valid = False
counter = 0
while not valid:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
elif len(user) != 4:
print ("That is incorrect, please try again")
else:
print ("that is incorrect, please try again")
counter = counter + 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
#Do stuff to actually abort here...
It counts up if there is a wrong answer now
the inner loop is just for valid input:
user = '1234'
locked = False
miss_cnt = 0
while True:
while True:
ans = raw_input('User -> ')
if len(ans) == 4 and ans.isdigit():
break
if ans != user:
miss_cnt += 1
if miss_cnt >= 3:
locked = True
break
else:
break
I left out the prints for clarity of flow
The following code should work for you.
answer = "1234"
valid = False
count = 0
while not valid and count < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == answer:
print("You have cracked the code, well done")
valid = True
elif count < 2:
print ("that is incorrect, please try again")
else:
print ("You have been locked out")
count += 1
I took the () off of the strings because that would make them sets so the if statement would never be true, because sets don't equal string inputs.

How to create a random 4 digit number and store it as a variable [duplicate]

This question already has answers here:
Python: How to generate a 12-digit random number?
(6 answers)
Closed 7 years ago.
I am working on a guess-the-4-digit-number game in python 2.7.10. But I cannot find how to randomly make a 4 digit number, and store it as a variable. The digit has to be somewhere between 1111 and 9999
The hard part is, that I want to store it as a variable, and not print it out for the player to see.
If you want to, I'll post the code when I'm finished.
The code is finally here!
import random
number = random.randint(1111,9999)
tryagain = 'yes'
print ('hello! ')
print ('------------------------------------------------------------- ')
print ('Try and guess the 4 digit number in the least number of tries ')
print ('------------------------------------------------------------- ')
while tryagain == 'yes':
lowoutput = None
highoutput = None
guess = None
guess = input('Guess: ')
if guess == number:
print ('Correct! ')
correctoutput str(raw_input(Enter 'exit' to exit: "))
If correctoutput == 'exit':
print 'Goodbye'
exit()
else:
print 'invalid input'
elif guess > number:
print 'Your answer is too high'
highoutput = str(raw_input("Try again? 'Y'/'N'))
if highoutput == 'n':
tryagain = 'n'
elif highoutput == 'y'
try again = 'yes'
else:
print 'invalid input'
else:
print 'Your answer is too low'
lowoutput = str(raw_input("Try again 'y'/'n'"))
if lowoutput == 'n':
try again = 'n'
elif lowoutput == 'y'
tryagain = 'yes'
else:
print 'invalid input'
print 'too bad, the right answer was: '
print (number)
exit()
This should work. There might be some mistakes cos I wrote this on my tablet. All improvements would be accepted
try with
import random
r = random.randint(1111,9999)
print "%04d" % r
or
print '{0:04d}'.format(r)

How to restart a simple coin tossing game

I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.

Categories