how can i force to make it to only string - python

Hello How can i force to make the nname to only string input because even though i put number it still continue to the next function and i only like it to be a name of the people nname= str(input()) does not work thats why im asking if there is other alternative to make it work with only a string
print("Good Day Welcome To our Shop.")
mnu = ["Milktea","Foods", "Drinks", "Dessert"]
lsa = ["1.Matcha", "Taro", "Winter Melon", "Okinawa", "Chocolate",
"Cheese Cake"]
fds = {'Chicken'}
shot = ["tubig"]
mtms = ["ice cream"]
laht = []
print("Hi what would you like to be called, "
"So we can inform you if your order is ready")
def cstmrinfo(name):
print("Okay " + name, "So what would you like to get " )
print(*mnu,sep = "\n")
nname= input().lower()
def kuha_order():
while True:
order = input()
if (order == "Milktea") or (order == "milktea"):
print(lsa)
laht.append(order)
break
elif (order == "Foods") or (order == "foods"):
print(fds)
laht.append(order)
break
elif (order == "Drinks") or (order == "drinks"):
print(shot)
laht.append(order)
break
elif (order == "Dessert") or (order == "dessert"):
print(mtms)
laht.append(order)
break
else:
print("Sorry you input a thing that is not available on our menu, "
"Please Try again:")
continue
def pnglhtn():
while True:
print("I Would like to get a: ")
qwe = input()
if qwe in lsa:
print(qwe)
elif qwe in fds:
print(qwe)
elif qwe in shot:
print(qwe)
elif qwe in mtms:
print(qwe)
else:
print("There is no such thing like that ")
continue
dmi = int(input("How Many Servings Would you Like: "))
laht.append(qwe)
laht.append(dmi)
print("So " + pngln, "you Like a " + str(laht[:2]))
print (dmi, "Serves of: " + str(laht[:2]))
break
cstmrinfo(nname)
kuha_order()
pnglhtn()

You can use either lower() or upper(). Please check the following answer:
if order.lower()=="milktea":
print(flvrs)
laht.append(order)
break
OR
if order.upper()=="MILKTEA":
print(flvrs)
laht.append(order)
break

When using the logical "or" operator in an if...else statement in python you have to repeat the variable as well as the value (i know that sounds confusing so look at the example)
this means that this won't work:
if order == "Milktea" or "milktea":
the correct formation should be:
if (order == "Milktea") or (order == "milktea"):
alternatively if you want to simply check one variable against a range of values check out the match...case statements in python 3.10+: https://learnpython.com/blog/python-match-case-statement/
######################################################
Remove the if order in mmu line and indent the corresponding else (code listed below)
def kuha_order():
while True:
order = input()
print(order)
if order == "Milktea":
print(flvrs)
laht.append(order)
break
elif order == "Foods":
print(pgkn)
laht.append(order)
break
elif order == "Drinks":
print(shot)
laht.append(order)
break
elif order == "Dessert":
print(mtms)
laht.append(order)
break
else:
print("Sorry you input a thing that is not available on our menu")
continue
you can combine this with my answer above to get what you need :)

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 trouble getting code to work

update so it seems like no matter what i do or type it asks
what would you like to add?
instead of doing the other options it just keeps asking this
it should only be asking this if the user types a
this is a 2 issue thing im having and the main original post is here
How to debug errors in Python?
but the bigger issue im having is i cant get the bottom half of my code to work
it just ignores the inputs given to it and continues to add them to the list
#.....
elif user == "d" :
listdelete = input("what item do you want deleted")
list.remove (listdelete)
elif user == "p" : # prints the list
print (list)
elif user == "x" : # exits the program
print ("good bye")
print ("!!!!!!that is not a choice!!!!!!")
#right now everything is being called through a single procedure
print (option())
and on the bottom here is going to be the entire code sorry for pasting the entire code on the bottom here but i thought it would be easy to understand the whole issue if i showed the whole code and then the section thats not working since its all under one procedure
list = []
def option() :
print ("(a) -to add item ")
print ("(d) -to delete item")
print ("(p) -to see items on your list")
print ("(x) -to exit ")
#above just prints out user options with a input after
user = input("please select a choice")
if user == "a" :
item = input("what would you like to add? ")
list.append (item)
# next im going to ask if they would like to add another item
more = input(" would you like to add something else? yes or no")
while more == "yes":
if more == "yes" :
item = input("what else would you like to add? type b to back ")
if item == "b" :
print (option())
else :
list.append(item)
elif more == "no" :
print (option())
#.....
elif user == "d" :
listdelete = input("what item do you want deleted")
list.remove (listdelete)
elif user == "p" : # prints the list
print (list)
elif user == "x" : # exits the program
print ("good bye")
print ("!!!!!!that is not a choice!!!!!!")
#right now everything is being called through a single procedure
print (option())
I have updated your code which still has flaws and exploits the mutability of the list datatype but does work as you would expect it:
#!/usr/bin/env python
def AddElement(collection):
elementToAdd = input("What would you like to add: ")
collection.append(elementToAdd)
return collection
def DeleteElement(collection):
print("You have the following items:", collection)
elementToDelete = input("What item do you want deleted: ")
for elements in collection:
if elements == elementToDelete:
collection.remove(elements)
print("You have the following items left:", collection)
return collection
def WriteMenu():
print("(a) -to add item")
print("(d) -to delete item")
print("(p) -to see items on your lst1")
print("(x) -to exit")
return True
def option():
WriteMenu()
UserInput = input("Please select a choice: ")
while UserInput:
if UserInput == "a":
AddElement(collection)
elif UserInput == "d":
DeleteElement(collection)
elif UserInput == "p":
print(collection)
elif UserInput == "x":
print("Good bye!")
break
WriteMenu()
UserInput = input("Please select a choice: ")
else:
print(collection)
#right now everything is being called through a single procedure
collection = []
option()

'int' object not subscriptable error

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

My programme enteres a blank row before entering data to CSV file how to delete the row or stop it from adding the row?

This is my code and when I enter the programme and try to find the records and get them sorted it shows up list index out of range and when I take the quiz it shows up everything all right but when I enter the CSV file there is an empty row between the input and the beginning of the file I tried deleting the empty rows and the programme works sorts the data and prints it but with the empty rows it just shows up the error mentioned above.
a=True
b=True
c=True
import random #Here i imported a random module
import csv
import operator
score=0 #I made a variable called score and set it to 0
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
if menu1 == ("s"):
menu2=input("How do you want it sorted? alpabetically(a) acording to score highest to lowest(s) or according to average score highest to lowest(a) ")
if menu2 == ("a"):
menu3=input("Which class are you in a b or c ")
if menu3 == ("a"):
sample = open("ClassA.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
if menu3 == ("b"):
sample = open("ClassB.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
menu4=input("Do you want to take the quiz now? ")
if menu4 == ("no"):
print("Thank you for Looking At the scores!")
if menu4 == ("yes"):
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
elif menu1 == ("t"):
while a == True: #Opens a loop called a
name=input("What is your name? ") #I asked the user their name here if name == (""):
if name.isdigit() or name == (""): #If the user enters a number or nothing something will happen
print("Incorrect Name") #This is the message that appears when the the name is a number or is nothing is incorrect
else:
a=False #Here i closed a loop
print("Welcome To my quiz " +str(name))#This is the welcoming message
while b == True:
group=input("What Class Are you A,B,C ") #Asks The User their class
if group == ("a") or group == ("b") or group == ("c") or group == ("A") or group == ("B") or group == ("C"):
break
else:
print("No such class!")
def addition(): #Here i define a function called addition
score=0 #Here the score shows score
first_number_a=random.randint(1,10) #The program gets a random number
second_number_a=random.randint(1,10) #The program gets another random number
question1=int(input("What is " +str(first_number_a)+ "+" +str(second_number_a)+ " ")) #Here the program asks the user a question
total_a=(first_number_a+second_number_a) #The answer to the question above
if question1 == total_a: #If answer is equal to the new variable c which is the answer to the question
print("Correct!") #This tells the user they got it correct
score=score+1 #This adds a point to the score
else: # if answer is not the variable
print("Incorrect!") #Here the program will print that the user is incorrect
print(total_a) #Here the program prints the correct answer if they got the question wrong
return score #This keeps the score safe
def multiplication():
score=0
first_number_m=random.randint(1,10)
second_number_m=random.randint(1,10)
question2=int(input("What is " +str(first_number_m)+ "*" +str(second_number_m)+ " "))
total_m=(first_number_m*second_number_m)
if question2 == total_m:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_m)
return score
def subtraction():
score=0
first_number_s=random.randint(1,10)
second_number_s=random.randint(1,10)
question3=int(input("What is " +str(first_number_s)+ "-" +str(second_number_s)+ " "))
total_s=(first_number_s-second_number_s)
if question3 == total_s:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_s)
return score
qw=["a" , "b" , "c"] #List Of Letters that will be randomly selected to then start a function
for i in range(0,10): #Thsi willrepeat the process listed below however many times in this example 10 times
random_Letter=random.choice(qw) #Selets a random letter
if random_Letter == "a": #If the random letter is a
score += addition() #It will use the function addition
elif random_Letter == "b":
score += multiplication()
elif random_Letter == "c":
score += subtraction()
print("your score is " +str(score)+ " Out of 10")#Tells the user their final score
if group == ("a") or group == ("A"): # If users input is as specified
f=open("ClassA.csv","a")#This opens a file
c = csv.writer(f)
c.writerow([name,score]) #Writes To A file
f.close() #This closes the file saving anything the user wrote to it
elif group == ("b") or group == ("B"):
f=open("ClassB.csv","a")
c = csv.writer(f)
c.writerow([name,score])
f.close()
elif group == ("c") or group == ("C"):
f=open("ClassC.csv","a")
f.write(name)
f.write(str(score)+ "\n")
f.close()

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