Here's my code:
cont = "y"
cont1 = "0"
cont2 = "yes"
log = 0
data = open("songs.txt", "r")
songs = data.readlines()
songs.sort()
while cont1 == "0":
cont = input("Do you want to make a playlist? [Y or N]") #Need to change to change cont1 if a playlist is not wanted to be created
if cont == "y":
new = "playlist" + str(log) + ".txt"
print(new, "Please remember the number. Thanks")
log = log + 1
else:
break
while cont == "y":
print ("1. ", songs[0],"2. ", songs[1],"3. ", songs[2],"4. ", songs[3],"5. ", songs[4],"6. ", songs[5],"7. ", songs[6],"8. ", songs[7],"9. ", songs[8],"10. ", songs[9],"11. ", songs[10],"12. ", songs[11],"13. ", songs[12],"14. ", songs[13],"15. ", songs[14],"16. ", songs[15],"17. ", songs[16],"18. ", songs[17],"19. ", songs[18],"20. ", songs[19])
choice = int(input("Please enter the first choice of song you would like in your playlist [Type the allocated number please]"))
choice1 = choice - 1
with open("playlist" + str(log) + ".txt", "a") as playlist:
playlist.write(str(songs[choice1]))
cont = input("Do you want to add another song? [Y or N]")
if cont == "n":
break
view = input("Which playlist would you like to view? Please enter the number
you were given before.")
with open("playlist" + str(view) + ".txt", "a") as see:
print(see)
The function of my code is a playlist generator for the user using the songs I already have. That all works up to now, but when trying to allow the user to view the playlist of their choice in this section of the code:
view = input("Which playlist would you like to view? Please enter the number
you were given before.")
with open("playlist" + str(view) + ".txt", "a") as see:
print(see)
I got an error message saying:
<_io.TextIOWrapper name='playlist2.txt' mode='a' encoding='UTF-8'>
Does this make sense to anyone?
Thanks!
By the way, the songs.txt contains a list of 20 songs in it. Cheers!
I think there might be a couple things here. playlist2.txt is not opened in a readable mode, so open needs r instead of a. see is a file object, so print needs see.read() to print the file contents.
Related
Question 1: I am not sure how to get first_name to display on lines 27-28. What code do I add?
Question 2: I want the input for lines 27-28 with the question "What type of Coffee would you like today?" to be bypassed using only the correct coffee types of ["Expresso", "Latte", "Cappuccino", "Mocha", "Frappuccino"] with a loop containing "break" to pass to next question and "continue" to retry if the user input did not choose from 1 or more coffee types and in which they can also include the word "and" and comma "," for correct input like "Expresso and Latte" or "Expresso Latte" or "Expresso, Latte and Mocha" or even "Expresso Latte Mocha", all which still allow comma's, "and" and 5 coffee type choices ONLY to bypass to the next question.
What code do I need to add?
Code
company_name = "Daniel's Coffee"
def greet():
print("\n" + "Hello" + "!" + " " + "Welcome to" + " " + company_name + "!" + "\n")
greet()
def name():
while True:
first_name = input("Can I start off with your first name?" + "\n\n")
if len(first_name) >= 3:
print("\n" + "Thank you," + " " + first_name.capitalize() + "!")
break
else:
print("\n" + "Invalid input," + " " + "please try again" + "!" + "\n")
continue
name()
def coffee_order():
while True:
order = input("\n" + first_name + "What type of Coffee would you like today?" +
"\n\n"
+ "\n".join(["Expresso", "Latte", "Cappuccino", "Mocha",
"Frappuccino"]) + "\n\n")
order = order.replace("and a", "")
order = order.replace("and", "")
order = order.replace(",", "")
order = order.lower().split()
union = " and a " if len(order) > 1 else ""
plural = "" if len(order) > 1 else ""
if order:
order = input("\n" + "You have selected a" + " " + ", ".join(order[:-1]).title()
+ union + plural +
order[-1].title() + "!" + " " + "\n\n" + "Is that correct?" +
"\n\n")
if order.capitalize() == "Yes":
print("\n" + "Wonderful" + "!")
break
elif order.capitalize() == "No":
continue
else:
print("Invalid input, please try again" + "!")
continue
coffee_order()
For the first name to be available you need to provide it as an argument to coffee_order or have a global variable defined outside and then accessed inside the function using global first_name before usage.
A much better approach would be to group these attributes and functions in a class. Below I have provided a template for this to help you experiment and use it for your project:
class CoffeeShop:
"""Coffee shop class."""
COFFEE_TYPES = ["Expresso", "Latte", "Cappuccino", "Mocha", "Frappuccino"]
def __init__(self):
self.company_name = "Daniel's Coffee"
self.first_name = None
def greet(self):
"""Print greeting."""
print(f"Hello! Welcome to {self.company_name}!")
def get_name(self):
"""Get customer first name."""
while True:
self.first_name = input("Can I start off with your first name?\n")
if len(self.first_name) >= 3:
print(f"Thank you {self.first_name}!")
return
print("You must enter at least 3 characters!\n")
def coffee_order(self):
"""Process coffee order."""
while True:
order = input(f"{self.first_name}, what coffee would you like today?\n "
f"Available coffee types are : {CoffeeShop.COFFEE_TYPES}\n")
if order in CoffeeShop.COFFEE_TYPES:
print(f"You have selected {order}. Thank you!")
return
print(f"{order} is not currently available.\n Please chose one of following: {CoffeeShop.COFFEE_TYPES}")
coffee_shop = CoffeeShop()
coffee_shop.greet()
coffee_shop.get_name()
coffee_shop.coffee_order()
I'm still learning python and programming and i've got myself into a problem that i can't solve. I want to make a command that would make a bot send an image that its name corresponds to number what user wrote (e.g. user wrote "!image_nr 22" and bot sends 22.jpg). I've only made code that sends random image from folder but I cant get into chosen. Here's my latest code for this problem:
elif message.content.startswith("!obrazeknr"): #missing an argument or something, idk what to make here
obrazDirectoryChc = "C:/Users/Lewando54/Downloads/Localisation/English/" + liczba + ".jpg"
await client.send_file(message.channel, obrazDirectoryChc, content=obrazName[1])
You could try inside this elif statement:
msg = message.content[12:] #skips the command word and the '!' and the " "
msg = msg.split() #split the message into an array at the spaces.
#msg = ["!image_nr","22"]
if msg[0] == "!image_nr" and msg[1].isnumeric():
obrazDirectoryChc = "C:/Users/Lewando54/Downloads/Localisation/English/" +
liczba + ".jpg"
await client.send_file(message.channel, obrazDirectoryChc,
content=obrazName[int(msg[1]])
now it should send the user requested photo.
e.g. !obrazeknr image_nr 22
Hope this helps. Sorry for the long wait; I just saw this today.
Might be a better idea, for next time, posting on https://programming.stackoverflow.com could give you more help.
It works. I've slightly modified it and it works. Thx for idea :D
elif message.content.startswith('!obrazeknr'):
msg1 = message.content #skips the command word and the '!' and the " "
msg1 = msg1.split() #split the message into an array at the spaces.
#msg = ["!obrazeknr","22"]
if msg1[0] == "!obrazeknr" and msg1[1].isnumeric() == True:
await client.send_file(message.channel, "C:/Users/Lewando54/Downloads/Localisation/English/" + str(int(msg1[1])) + ".jpg")
I have a simple data entry form that writes the inputs to a csv file. Everything seems to be working ok, except that there are extra columns being added to the file in the process somewhere, seems to be during the user input phase. Here is the code:
import pandas as pd
#adds all spreadsheets into one list
Batteries= ["MAT0001.csv","MAT0002.csv", "MAT0003.csv", "MAT0004.csv",
"MAT0005.csv", "MAT0006.csv", "MAT0007.csv", "MAT0008.csv"]
#User selects battery to log
choice = (int(input("Which battery? (1-8):")))
def choosebattery(c):
done = False
while not done:
if(c in range(1,9)):
return Batteries[c]
done = True
else:
print('Sorry, selection must be between 1-8')
cfile = choosebattery(choice)
cbat = pd.read_csv(cfile)
#Collect Cycle input
print ("Enter Current Cycle")
response = None
while response not in {"Y", "N", "y", "n"}:
response = input("Please enter Y or N: ")
cy = response
#Charger input
print ("Enter Current Charger")
response = None
while response not in {"SC-G", "QS", "Bosca", "off", "other"}:
response = input("Please enter one: 'SC-G', 'QS', 'Bosca', 'off', 'other'")
if response == "other":
explain = input("Please explain")
ch = response + ":" + explain
else:
ch = response
#Location
print ("Enter Current Location")
response = None
while response not in {"Rack 1", "Rack 2", "Rack 3", "Rack 4", "EV001", "EV002", "EV003", "EV004", "Floor", "other"}:
response = input("Please enter one: 'Rack 1 - 4', 'EV001 - 004', 'Floor' or 'other'")
if response == "other":
explain = input("Please explain")
lo = response + ":" + explain
else:
lo = response
#Voltage
done = False
while not done:
choice = (float(input("Enter Current Voltage:")))
modchoice = choice * 10
if(modchoice in range(500,700)):
vo = choice
done = True
else:
print('Sorry, selection must be between 50 and 70')
#add inputs to current battery dataframe
log = pd.DataFrame([[cy,ch,lo,vo]],columns=["Cycle", "Charger", "Location", "Voltage"])
clog = pd.concat([cbat,log], axis=0)
clog.to_csv(cfile, index = False)
pd.read_csv(cfile)
And I receive:
Out[18]:
Charger Cycle Location Unnamed: 0 Voltage
0 off n Floor NaN 50.0
Where is the "Unnamed" column coming from?
There's an 'unnamed' column coming from your csv. The reason most likely is that the lines in your input csv files end with a comma (i.e. your separator), so pandas interprets that as an additional (nameless) column. If that's the case, check whether your lines end with your separator. For example, if your files are separated by commas:
Column1,Column2,Column3,
val_11, val12, val12,
...
Into:
Column1,Column2,Column3
val_11, val12, val12
...
Alternatively, try specifying the index column explicitly as in this answer. I believe some of the confusion stems from pandas concat reordering your columns .
this is how i have it printed now, but i want all numbers to be one same level, but i can't do it, because emails have different lengths - hotmail.com, mail.com etc
my code:
def count_domains(date, emails):
print(date)
my_emails = []
for email in emails:
current_email = email.split("#", 2)[1]
my_emails.append(current_email)
unique_emails = list(set(my_emails))
for x in range(len(unique_emails)):
print( str(unique_emails[x]).rjust(2) + " : " + str(my_emails.count(unique_emails[x])).rjust(4))
What about something like this:
print((str(unique_emails[x]) + ": ").ljust(20) +
str(my_emails.count(unique_emails[x])).rjust(4))
My program seems to be experiencing logical errors. I have looked it over multiple times and even written another program similar to this one (also seems to have the same error). I cannot figure out what is wrong, although I think it may involve my usage of string.gsub...
repeat
local file = io.open("out.txt", "w")
print("would you like to translate Cipher to English or English to Cipher?")
print("enter 1 for translation to English. enter 2 for translation to Cipher")
tchoice=io.read()
if tchoice=="2" then
print(" enter any text to translate it: ")
rawtextin=io.read()
text=string.lower(rawtextin)
text1=string.gsub(text,"a","q")
text2=string.gsub(text1,"b","e")
text3=string.gsub(text2,"c","h")
text4=string.gsub(text3,"d","c")
text5=string.gsub(text4,"e","j")
text6=string.gsub(text5,"f","m")
text7=string.gsub(text6,"g","r")
text8=string.gsub(text7,"h","g")
text9=string.gsub(text8,"i","b")
text10=string.gsub(text9,"j","a")
text11=string.gsub(text10,"k","d")
text12=string.gsub(text11,"l","y")
text13=string.gsub(text12,"m","v")
text14=string.gsub(text13,"n","z")
text15=string.gsub(text14,"o","x")
text16=string.gsub(text15,"p","k")
text17=string.gsub(text16,"q","i")
text18=string.gsub(text17,"r","l")
text19=string.gsub(text18,"s","f")
text20=string.gsub(text19,"t","s")
text21=string.gsub(text20,"u","w")
text22=string.gsub(text21,"v","t")
text23=string.gsub(text22,"w","p")
text24=string.gsub(text23,"x","u")
text25=string.gsub(text24,"y","n")
text26=string.gsub(text25,"z","o")
text27=string.gsub(text26," ","#")
print(text27)
elseif tchoice=="1" then
print("enter text!")
rawtextin=io.read()
text=string.lower(rawtextin)
text1=string.gsub(text,"q","a")
text2=string.gsub(text1,"e","b")
text3=string.gsub(text2,"h","c")
text4=string.gsub(text3,"c","d")
text5=string.gsub(text4,"j","e")
text6=string.gsub(text5,"m","f")
text7=string.gsub(text6,"r","g")
text8=string.gsub(text7,"g","h")
text9=string.gsub(text8,"b","i")
text10=string.gsub(text9,"a","j")
text11=string.gsub(text10,"d","k")
text12=string.gsub(text11,"y","l")
text13=string.gsub(text12,"v","m")
text14=string.gsub(text13,"z","n")
text15=string.gsub(text14,"x","o")
text16=string.gsub(text15,"k","p")
text17=string.gsub(text16,"i","q")
text18=string.gsub(text17,"l","r")
text19=string.gsub(text18,"f","s")
text20=string.gsub(text19,"s","t")
text21=string.gsub(text20,"w","u")
text22=string.gsub(text21,"t","v")
text23=string.gsub(text22,"p","w")
text24=string.gsub(text23,"u","x")
text25=string.gsub(text24,"n","y")
text26=string.gsub(text25,"o","z")
text27=string.gsub(text26,"#"," ")
print(text27)
end
print("writing to out.txt...")
file:write(text27)
file:close()
print("done!")
print("again? type y for yes or anything else for no.")
again=io.read()
until again~="y"
x=io.read()
No errors in the code - What am I missing? I am aware this is not the most efficient way of doing this but I need to figure out what is going wrong before I write a more efficient program using loops and tables.
Sample run (with only significant data included):
in:2
in:hi test
out:gb#safs
in:y
in:1
in:gb#safs
out:hq vjvv
local decoded = 'abcdefghijklmnopqrstuvwxyz #'
local encoded = 'qehcjmrgbadyvzxkilfswtpuno# '
local enc, dec = {}, {}
for i = 1, #decoded do
local e, d = encoded:sub(i,i), decoded:sub(i,i)
enc[d] = e
dec[e] = d
end
repeat
local file = io.open("out.txt", "w")
local text27, rawtextin
print("would you like to translate Cipher to English or English to Cipher?")
print("enter 1 for translation to English. enter 2 for translation to Cipher")
local tchoice = io.read()
if tchoice == "2" then
print(" enter any text to translate it: ")
rawtextin = io.read()
text27 = rawtextin:lower():gsub('.',enc)
print(text27)
elseif tchoice == "1" then
print("enter text!")
rawtextin = io.read()
text27 = rawtextin:lower():gsub('.',dec)
print(text27)
end
print("writing to out.txt...")
file:write(text27)
file:close()
print("done!")
print("again? type y for yes or anything else for no.")
local again = io.read()
until again ~= "y"