Can anyone help me debug my program - python

I'm in a beginning programming class and our program is to create a program to gather information on four different zip codes and five different types of coffee drinks to see if our friend should open up a coffee shop in that area.
My program will not accept my variables
My other problem with my program is it won't loop back around to get more input. I tried to reset the user answer to allow it to go back to the beginning but it doesn't read it.
I set up an accumulater for my if statement
Example
while UserAnswer == "yes":
ZipCode = input("Enter Zip Code: ")
print("Here are your menu choices: \n m = Cafe Mocha\n l = Cafe Latte ")
print(" r = Cafe Regular \n d = Cafe Regular Decafe \n c = Cafe Carmel")
CoffeeType = input("Enter your order: ")
Quantity = input("Enter quantity: ")
#Start inner loop with if statements to determine the quantity of the coffee
while UserAnswer == "no"
if ZipCode == 48026:
if CoffeeType == "m":
CM48026 = Quanity + CM48026'
My accumulater CM48026 doesn't save and at the end it prints out 0.

You need to provide an initial value for the accumulator. And that should be done outside the inner loop. Because you are using the same variable in the expression which provides the value for the accumulator.
So, doing a = b + a will not really work, as the value of a at the right is not really defined.
Moreover, there's a typo for the variable quantity, and that might actually be the reason why your code is not working!

Related

How to get input from user, put them into a list and then choose a random one from them without having to ask multiple times

It's my 4th day learning programming so I'm very new to it. and I'm trying to get the user's info(hobbies) in one question and save them into a list then give back the user one of the hobbies they chose.
this what I've came up with
import random
fav_hobbies = []
hobbies = input("what are your favourite hobbies?(cooking, writing,ect) ").lower()
fav_hobbies.append(hobbies)
situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
print("you should try " + random.choice(fav_hobbies))
elif boredom_situation == "no":
print("awesome! have a nice day!")
The problem is that instead of choosing a word among the words that user has chosen it just prints all of the things they said.
How do I fix this?
You are just accepting a string from the User and storing it as it is without splitting.
Assuming that you are accepting a space separated input, You can do this in:
fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())
import random
fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())
situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
print("you should try " + random.choice(fav_hobbies))
elif boredom_situation == "no":
print("awesome! have a nice day!")
If you use some other separator like , you can just add it to split(',')

How to fix my leaderboard for my Music Quiz

I'm making a Music Quiz for a school project.
I've made a working game however I cannot get the leaderboard (which should be text and is saved as leaderboard.txt) to show different names as it overwrites the previous name.
For example, if "Sam" was to get a score of 9 and "Ben" was to get a score of 3, it would show up as "Ben-3-9" which is not what I'm after.
I am trying to get my leaderboard to work like:
Sam - 9
Ben - 3
...
My code looks like this right now:
username = input("What is your username?")
# this will ask for the persons name
password = str(input("What is the password?"))
# this will ask for a password which has been set already
if password == "1234":
print("User Authenticated")
# if the password is incorrect, tell the user so and exit
elif password != "1234":
print("Password Denied")
exit()
# GAME
# Creating a score variable
score=0
x = 0
# Reading song names and artist from the file
read = open("songnames.txt", "r")
songs = read.readlines()
songlist = []
# Removing the 'new line' code
for i in range(len(songs)):
songlist.append(songs[i].strip('\n'))
while x == 0:
# Randomly choosing a song and artist from the list
import random
choice = random.choice(songlist)
artist, song = choice.split('-')
# Splitting the song into the first letters of each word
songs = song.split()
letters = [word[0] for word in songs]
# Loop for guessing the answer
for x in range(0, 2):
print(artist, "".join(letters))
guess = str(input("Guess the song!"))
if guess == song:
if x == 0:
score = score + 3
break
if x == 1:
score = score + 1
break
quit()
# Printing score, Then waiting to start loop again.
import time
print("Your score is", score)
print("Nice Work!")
time.sleep(3)
leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
leaderboard.close()
leaderboard = open("leaderboard.txt", "r+")
leaderboardlist = leaderboard.readlines()
print(leaderboardlist)
leaderboard.close()
PS: this is not 100% my code I am trying to get help from different places as my school has not taught us how to code yet due to the pandemic closing down schools.
When you do this:
leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
you open the leaderboard in read-and-write mode, but it will start writing at the beginning of the file, overwriting whatever is there. If you just want to add new scores to the leaderboard, the simplest would be to open the file in "append" mode "a":
with open("leaderboard.txt", "a") as leaderboard:
leaderboard.write(username + '-' + '{}'.format(score))
Alternatively, you could open the file in "r" mode, then first read all the lines (scores) in a list or dictionary, merge / update them with the current player's new score (e.g. adding to the last score, replacing the last score, or getting the max of the new and last score of that player), and then open the file again in "w" mode and write the updated scores. (Left as an exercise to the reader.)
The problem lies within the final few lines of code, where you are writing to the leaderboard.txt file.
Using "r+" indicates that you are updating (reading and writing) the file. Opening a file this way, moves the cursor at the beginning of the file. Therefore any attempt to write to the file will override whatever is already there.
The proper way to do it, is to open the file using "a" (or "a+" if you are planning to read as well). This is append mode and will move the cursor to the end of the file.
Some other general notes:
Use the with-as statement to handle closing the file automatically after you are done.
Use f-strings as opposed to string concatenation to increase readability
With that in mind, here's the code:
with open("leaderboards.txt", "a") as f:
f.write(f"{username}-{score}")
For more on files, check this question.
For more on f-strings, check this quite extensive overview of them.

Python 3.x: User using enter to input user's list vertically while using a loop

My task is to have the user input an unlimited amount of words while using enter.
Example:
(this is where the program asks the user to input names)
Please input names one by one.
Input END after you've entered the last name.
(this is where the user would input the names)
Sarah
Tyler
Matthew
END
(by pressing enter, they are entering the names into a list until they enter END)
I'm not sure where the coding for this will be. I assume I would use a while loop but I'm not sure how. Thanks.
I'm really really new to programming and I'm really lost. This is what I have so far:
def main() :
name = []
print("Please input names one-by-one for validation.")
diffPasswords = input("Input END after you've entered the last name.")
while True :
if
Try using the below while loop:
l = []
while 'END' not in l:
l.append(input('Name: '))
l.pop()
print(l)
Output:
Name: Sarah
Name: Tyler
Name: Matthew
Name: END
['Sarah', 'Tyler', 'Matthew']
it's simply done with a while loop.
name_list=[]
while True:
i = input('enter').rstrip()
if i == 'END':
break
name_list.append(i)
Basically keep on getting a new line but if it equals END\n then stop. The \n is from the enter. Otherwise add it to the list but make sure to omit the last character because that is the newline character(\n) from the enter.
import sys
list = []
while True:
c = sys.stdin.readline()
if c == "END\n":
break
else:
list.append(c[0:-1])
print(list)

How to find variations of a word from source code (python 3)

I have to write a program that takes user input for a website and keyword, and then reads the source code of the website for that word. I have to code it so it detects many variations of the word (ex. hello vs. hello, vs. hello!) and am not sure how to do this. I have it coded like this so far to detect the exact input, but I'm not sure how to get multiple variations. Any help would be greatly appreciated, thank you!
def main():
[n,l]=user()
print("Okay", n, "from", l, ", let's get started.")
webname=input("What is the name of the website you wish to browse? ")
website=requests.get(input("Please enter the URL: "))
txt = website.text
list=txt.split(",")
print(type(txt))
print(type(list))
print(list[0:10])
while True:
numkey=input("Would you like to enter a keyword? Please enter yes or no: ")
if numkey=="yes":
key=input("Please enter the keyword to find: ")
else:
newurl()
break
find(webname,txt,key)
def find(web,txt,key):
findtext=txt
list=findtext.split(sep=" ")
count = 0
for item in list:
if item==key:
count=count+1
print("The word", key, "appears", count, "times on", web)
def newurl():
while True:
new=input("Would you like to browse another website? Please enter yes or no: ")
if new=="yes":
main()
else:
[w,r]=experience()
return new
break
def user():
name=input("Hello, what is your name? ")
loc=input("Where are you from? ")
return [name,loc]
def experience():
wordeval=input("Please enter 3 words to describe the experience, separated by spaces (ex. fun cool interesting): ")
list=wordeval.split(sep=" ")
rate=eval(input("Please rate your experience from 1-10: "))
if rate < 6:
print("We're sorry you had a negative", list[0], "and", list[2], "experience!")
else:
print("Okay, thanks for participating. We're glad your experience was", list[1], "!")
return[wordeval,rate]
main()
What you're looking for is the re module. You can get indices of the matches, individual match instances, etc. There are some good tutorials here that you can look at for how to use the module, but looping through the html source code line by line and looking for matches is easy enough, or you can find the indices within the string itself (if you've split it by newline, or just left it as one long text string).

Sending information gathered from questionnaire to a Python document?

I'm brand new to both Python and StackOverflow, and I have a problem that has been stumping me for the past couple of hours.
I am making a peer-evaluation script for my high-school class. When you run the script, you input your classmate's name, then you rate them 1-10 on effort, accountability, and participation. These 3 values are then averaged. This average is assigned to the variable "grade". Since each classmate is going to get multiple grades, I need to have the "grade" variable export to another Python document where I can average every grade for each respective classmate.
So far, I have the script create a .txt file with the same name as the evaluated classmate, and the grade integer is stored there. Does anyone know of a way that I can export that integer to a Python file where I can append each successive grade so they can then be averaged?
Thanks
Python peer evaluation script
def script():
classmate = input('Please enter your classmate\'s name: ')
classmateString = str(classmate)
effortString = input('Please enter an integer from 1-10 signifying your classmate\'s overall effort during LLS: ')
effort = int(effortString)
accountabilityString = input('Please enter an integer from 1-10 signifying how accountable your classmate was during LLS: ')
accountability = int(accountabilityString)
participationString = input('Please enter an integer from 1-10 signifying your classmate\'s overall participation: ')
participation = int(participationString)
add = effort + accountability + participation
grade = add / 3
gradeString = str(grade)
print ('Your grade for ', classmate, 'is: ', grade)
print ('Thank you for your participation. Your input will help represent your classmate\'s grade for the LLS event.')
filename = (classmateString)+'.txt'
file = open(filename, 'a+')
file.write(gradeString)
file.close()
print ('Move on to next classmate?')
yes = set(['yes','y','Yes','Y'])
no = set(['no','n','No','n'])
choice = input().lower()
if choice in yes:
script()
elif choice in no:
sys.exit(0)
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
script()
script()
put
import name_of_script_file
at the top of your Python file, assuming they are in the same folder.
Then you can access the variable like:
name_of_script_file.variable_name

Categories