Comparing 2 string values, not working!? - python

I'm trying to compare two string values that was retrieved in my first function, but it doesn't work. It keeps telling me 'invalid syntax' and moves my cursor over to the elif line.
This is my program...
def find_number_of_service():
with open('TheData.txt', 'r') as data_file:
data = data_file.read()
countS = data.count('S')
countW = data.count('W')
print ("There are " + str(countS) + " S's")
print ("There are " + str(countW) + " W's")
return
def find_popular_service():
if (countS) > (countW):
print ("The most used service to buy tickets was the school.")
elif print ("The most used service to buy tickets was the website.")
return
#Main program
find_number_of_service()
find_popular_service()
Thank you in advance.

Problem in second function elif you have not defined correctly it should be elif <condition>:
Here the working function
def find_popular_service():
if (countS) > (countW):
print ("The most used service to buy tickets was the school.")
else:
print ("The most used service to buy tickets was the website.")
return

You don't give elif a condition. elif means otherwise if.... Perhaps you mean else.
elif should be in line with if
print ... should be on a new line.

Related

String argument error with dictionary commands

I am trying to create a basic online store in python. But whenever I try to 'buy' an item it shows an error with my dictionary or something I am not sure.
The error: users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
TypeError: str() takes at most 3 arguments (6 given)
coun = 0
users = [{"name":"Jack","username":"ja", "cc":'12345',"email":'whwhwwhh', "code": '111', "Transactions": ""}]
def sign_in():
username = input("Enter username")
for i in range (len(users)):
for x in users[i].values():
if x == username:
pin = input("Enter pin")
if pin == users[i].get("code"):
print("Welcome", users[i].get("name"))
menu(username,users[i].get("name"))
break
else:
print("Wrong pin")
sign_in()
def menu (usern, names_f):
global coun
if coun == 0:
order = ''
total = 0
for i in range (len(categories)):
print(str(i+1)+".", categories[i])
choice = int(input("Choose a category by typing the number beside the categories name."))-1
print("Items in this list are")
print("Itemname \t Price \t Stock")
final = location[choice]
for c in range((int(len(final)/3))):
print(str(c+1)+'.',str(final[c*3]),"\t",'$'+str(final[c*3+1])), "\t", str(final[(c*3)+2])
choice = int(input("Which item (Type number on left of the item name)"))-1
while True:
quanti = int(input("How many do you want to buy"))
if quanti > final[choice*3+2]:
print("Sorry your request for", quanti, "Is more than we have at the store please try again")
continue
else:
price = str(quanti*final[choice*3+1])
final[choice*3+2] = final[choice*3+2]-quanti
print("Thank you for your purchasing",quanti,"of", final[choice*3], "Your total price of this buy is", '$'+price)
for n in range (len(users)):
if usern == users[n].get("username"):
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
order += str(quanti, 'of', final[choice*3])
price += int(price)
done = input("Do you want to check out then type '1' if you want to continue type '2'")
if done == '1':
print("Thank you")
print ("Invoice:", order, "/n total price (HKD) $"+str(price))
else:
coun += 1
menu(usern,names_f)
variable_name = users[n]["Transactions"] + str(names_f) + "bought" + str(quanti) + "of" + str(final[choice*3]) + "with a total price of $"+ str(price)
users[n]["Transactions"] = variable_name
You will maybe need to declare variable_name somewhere.
Problem is that str usage is following
str(object, encoding=encoding, errors=errors)
but whenever you pass comma it count it as another parameter.
P.S. I'm not sure if you need all those str in my solution.
str is a class, and as stated in the docs you can pass up to 3 parameters to it:
class str(object=b'', encoding='utf-8', errors='strict')
Also, it also says what it does:
Return a string version of object. If object is not provided, returns the empty string.
Meaning it is used to cast other types to string. Thus, you need to convert every int individually:
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f) + " bought " + str(quanti) + " of " + str(final[choice*3]) + " with a total price of " + str(price)
Note the spaces before and after every string. Alternatively, you can format your string:
users[n]["Transactions"] = users[n]["Transactions"] + '%s bought %s of %s with a total price of %s' % (names_f, quanti, final[choice*3], price)
As a side note, it's worth checking what happens when the first transaction is made. If the key Transactions does not yet exist, you need to add an initial value before accessing it.
I usually do it like:
if key not in dict_:
dict_[key] = 'my initial value'
dict_[key] += 'add my stuff'
another solution would be using the get method, which allows you to add a default value:
dict_.get(key, 'default')
Note that this will not add the key to the dictionary, meaning that trying to access its value later on will still result in a Key Error.

Python While Loop w/ Exception handling never ending

I am running into a little problem that I cannot figure out. I am getting stuck in a while loop. I have 3 while loops, the first one executes as planned and then goes into the second. But then it just gets stuck in the second and I cannot figure out why.
A little explanation on what I am trying to do:
I am suppose to get 3 inputs: years of experience (yearsexp), performance (performance) and a random int generated between 1-10(level). The program will ask the user for their experience, if it is between 3-11 they are qualified. If not, it will tell them they are not qualified and ask to re-enter a value. Same thing with performance. If they enter a number less than or equal to 11 it will procede to generate the random int (level) at which point level will be used to asses their bonus. The user gets prompted for experience and will function correctly and proceed to performace. However, even when entering a valid input, it keeps asking them to re-enter the performance #. I cannot figure out why its getting stuck this way.
import random
error = True
expError = True
performanceError = True
# Get users name
name = input("Enter your name: ")
# Get users experience *MINIMUM of 3 yrs py
while (expError):
try:
yearsexp = int (input(name+", Enter the years of your experience: "))
if (yearsexp >= 3 and yearsexp <= 11):
expError = False
print(name, "You are qualified")
else:
raise ValueError
except:
print ("You have entered an invalid number! Try again...")
#Get users performance
while (performanceError):
try:
performance = int (input(name+", Enter the performance: "))
if (performance <= 11):
expError = False
print(name, "You are qualified")
else:
raise ValueError
except:
print ("You have entered an invalid number! Try again...")
performanceError = False
# Get random level number
level = random.randint(1,11)
print ("Random Level: ", end =' ')
print (level)
bonus = 5000.00
while (error):
try:
if (level >=5 and level <=8):
error = False
print ("Expected Bonus: $5,000.00")
print (name + ", your bonus is $", end =' ')
print (bonus)
elif (level <= 4 ):
error = False
bonus = bonus * yearsexp * performance * level
print ("Expected bonus: ", end =' ')
print (bonus)
print (name + ", your bonus is $", end =' ')
print (bonus)
else:
raise ValueError
except:
print ("You do not get a bonus")
You didn't set the performanceError to False
if (performance <= 11):
expError = False
needs to be changed to
if (performance <= 11):
performanceError= False

This Python quiz is driving me crazy

I'm new to StackOverflow (1st time posting) and new to coding with python. Currently enrolled in a course through Udacity. I'm having a very hard time with a project we were given for this course and decided to come here to see if anyone could help.
The project is to create a quiz with 4 blanks that need to be answered correctly by the player. It's required to have the quiz print out with the correct answer, but I'm having a very hard time getting this to print out correctly.
My code is below. Would appreciate any help or advice I can get on this.
Thanks!
easy_quiz = "If you ever get stuck, check out the __1__ for common
problems students face when attempting this project. If you need
additional help, you can schedule a 1:1 appointment with one of our
__2__ to get you un-stuck. This project should be __3__. If at any time
it becomes not fun, take a step back, deep breath, and ask for __4__!.
\n\n"
easy_answers = ["forums", "mentors", "fun", "help"]
medium_quiz = "Game must have 3 or more levels and each level contains 4 or more __1__ to fill in. Immediately after running the program, user is prompted to select a difficulty level from easy / __2__ / hard. Once a level is selected, game displays a fill-in-the-blank and a prompt to fill in the first one. When player guesses __3__, new prompt shows with correct answer in the previous blank and a new prompt for the next blank. When player guesses __4__, they are prompted to try again. \n"
medium_answers = ["blanks", "medium", "correctly", "incorrectly"]
hard_quiz = "__1__ are used as __2__ to automate tasks which are likely to be repeated. Functions produce the appropriate output (typically with a __3__ statement) from the appropriate input (function parameters). Your code should take advantage of __4__ and variable names should reflect the values they store. \n"
hard_answers = ["Functions", "tools", "return", "variables"]
blanks = ["__1__", "__2__", "__3__", "__4__"]
difficulty = raw_input("\nChoose your difficuty level = easy, medium, or hard? ")
print ""
if difficulty == "easy":
quiz = easy_quiz
answers = easy_answers
print "You chose easy!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + easy_quiz
elif difficulty == "medium":
quiz = medium_quiz
answers = medium_answers
print "You chose medium!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + medium_quiz
elif difficulty == "hard":
quiz = hard_quiz
answers = hard_answers
print "You chose hard!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + hard_quiz
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return pos
return None
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement != None:
user_input = raw_input("Type an answer for: " + replacement + " " )
word = word.replace(replacement, user_input)
replaced.append(word)
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
print "Incorrect, try again \n" + " ".join(replaced)
user_input = raw_input("Type an answer for: " + replacement + " ")
if guesses == 4:
return "\nGame Over! Better luck next time. \n"
print "Correct \n" + " ".join(replaced)
i = i + 1
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
print play_game(quiz, blanks)
Here is a working version of your play_game() method:
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement is not None:
user_input = raw_input("Type an answer for: " + replacement + " " )
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
if guesses == 5:
return "\nGame Over! Better luck next time. \n"
print "Incorrect, try again \n" + " ".join(replaced) + " " + replacement
user_input = raw_input("Type an answer for: " + replacement + " ")
replaced.append(user_input)
print "Correct \n" + " ".join(replaced)
i = i + 1
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
The main change is to delay modifying the replaced list until the correct answer has been given. That simplifies a lot of the code, eliminating the need for the word variable.

Text-base game inventory list (Python)

so I'm new to python and I am making a text base game. I created an inventory list and in case the player picks up an item more than once, the second time it should be able to give a message saying that they already have this item. I got it to work to an extent where the item doesn't go over the value more than one, but it does not print the message. Please help!!
elif decision == "use H on comb":
global inventory
if inventory.count("comb")>1:
print ("You already got this item.")
print ("")
print ("Inventory: " + str(inventory))
if inventory.count("comb")<1:
print ("(pick up comb)")
print ("You went over to the table and picked up the comb,")
print ("it's been added to your inventory.")
add_to_inventory("comb")
print("")
print ("Inventory: " + str(inventory))
game()
just use the in operator to test for membership
if "comb" in inventory:
print("I have found the comb already...")
else:
print("Nope not here")
but as to why your code was failing was that
inventory.count('comb') == 1
# which fails inventory.count('comb') > 1 test
# but also fails inventory.count('comb') < 1 test so its not re added
you could have easily solved this yourself by printing the value of inventory.count('comb') , which is a useful method for debugging your program for beginners... basically when something doesnt work correctly, try printing it, chances are the variable is not what you think it is...
maybe a little more structuring can be done and avoid using global inventory .jsut a basic idea below:
def game():
inventory = []
# simulate picking up items( replace this loop with your custom logic )
while True:
item = raw_input('pick up something')
if item in inventory: # use in operator to check membership
print ("you already have got this")
print (" ".join(inventory))
else:
print ("pick up the item")
print ("its been added to inventory")
inventory.append(item)
print (" ".join(inventory))

Python: ' ' is not defined

Here is my code:
# This program makes the robot calculate the average amount of light in a simulated room
from myro import *
init("simulator")
from random import*
def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
entry = raw_input("Press c to continue. ")
print("Thank you. ")
print
def randomPosition():
""" This gets the robot to drive to a random position """
result = randint(1, 2)
if(result == 1):
forward(random(), random())
if(result == 2):
backward(random(), random())
def scan():
""" This allows the robot to rotate and print the numbers that each light sensors obtains """
leftLightSeries = [0,0,0,0,0,0]
centerLightSeries = [0,0,0,0,0,0]
rightLightSeries = [0,0,0,0,0,0]
for index in range(1,6):
leftLight = getLight("left")
leftLightSeries[index] = leftLightSeries[index] + leftLight
centerLight = getLight("center")
centerLightSeries[index] = centerLightSeries[index] + centerLight
rightLight = getLight("right")
rightLightSeries[index] = rightLightSeries[index] + rightLight
turnRight(.5,2.739)
return leftLightSeries
return centerLightSeries
return rightLightSeries
def printResults():
""" This function prints the results of the dice roll simulation."""
print " Average Light Levels "
print " L C R "
print "========================="
for index in range(1, 6):
print str(index) + " " + str(leftLightSeries[index]) + " " + str(centerLightSeries[index]) + " " + str(rightLightSeries[index])
def main():
senses()
pressC()
randomPosition()
scan()
printResults()
main()
So, I am getting this error when I run my program.
NameError: global name 'leftLightSeries' is not defined
I understand that I must be doing something wrong related to the return statement. I'm not sure if I can only return one variable at the end of a user-defined function. If that were to be true, then I should probably separate the scan(): function. Anyways, I would appreciate any help on how to fix this error. Also, this is the result that I am looking for when I successfully complete my program:
Click Here
I am looking to complete the average values like the picture shows, but I am not worried about them at this point, only the list of values from the light sensors. I do not need to reach those exact numbers, the numbers will vary in the simulator.
If you want to return multiple items from scan(), don't use three separate return statements. Instead, do this:
return leftLightSeries, centerLightSeries, rightLightSeries
Also, when you call the function, you have to assign variable(s) to the returned values; it won't automatically create new local variables with the same names. So in main, call scan() like this:
leftLightSeries, centerLightSeries, rightLightSeries = scan()

Categories

Resources