I'm writing a simple program that is basically a signup program for a run. I am very new to python, but cant seem to find out why this isn't working. My error message is saying something is wrong with line 9. I would really appreciate if someone could help me work this out. I have been looking around for ages trying to find solutions, it's probably a very easy mistake.
Cheers!!
allnames = []
allages = []
allgenders = []
alltimes = []
allhouses = []
more = "yes"
print "---- RUN ----"
while (more) == "yes":
runnername = input("Input runner name:")
allnames.append(runnername)
print str(allnames)
Thanks for all the help! Got it now. It's for NAT 5 Computing so i'm very new and inexperienced. Appreciate everyones answers!!
Use this:
while (more == "yes"):
instead of :
while (more) == "yes":
and it should work fine.
Change:
input() to raw_input()
Read more here:
What's the difference between raw_input() and input() in python3.x?
You're in an infinite loop. Try this:
allnames = []
more = "yes"
print "---- RUN ----"
while more == "yes":
runnername = raw_input("Input runner's name: ")
allnames.append(runnername)
if len(allnames) == 5:
more = "no"
print allnames
Change the condition in if len(allnames) == 5 according to your requirement.
in this code you have looking ages also. In your code you miss the '()' bracket in print statment and also miss secound time run statment for ages.
allnames = []
allages = []
allgenders = []
alltimes = []
allhouses = []
more = "yes"
print("---- RUN ----")
while (more) == "yes":
runnername = input("Input runner name:")
allnames.append(runnername)
print(str(allnames))
runnerages = input("Input runner ages:")
allages.append(runnerages)
print(str(allages))
You are getting error beacuse of input(). Replace it with raw_input() for python2.X .
Then try this way :
allnames = []
allages = []
allgenders = []
alltimes = []
allhouses = []
more = "yes"
print "---- RUN ----"
while (more) == "yes":
runnername = raw_input("Input runner name:")
allnames.append(runnername)
print str(allnames)
N.B: python2.X
Related
I am working on a stupid yet funny practice program to improve my understanding of OOP in Python.
The program is meant to randomly generate some band names from a randomly selected adjective and another randomly selected noun - producing a lot of hilarious band names.
For the most part, the program works fine, but for some reason, there are some problems with the if-statements and the while loop in the menu(self)- method all the way down in the BandList class.
My hypothesis is that there is something wrong with the nesting of the else-if statements, or that the loop doesn't manage to advance the loop when I call on the self._generateBand() method in line 60 due to some technicality I'm not aware of. Either way, I'm not sure.
However, my question is:
Why does my loop stop at the line self._writeBand() and not continue executing the code that follows? (As shown below)
done = False
while done != True:
print("\n=============== BAND NAME GENEREATOR ==================")
start = input("\nDo you want to generate a list of bandnames? (y/n): ")
if start.lower() == "y":
self._generateBand()
self._writeBand() #The loop stops here for some reason and asks the same question over and over.
#The program won't execute this part of the code.
inp = ("\nDo you want to save these band names? (y/n): ")
if inp.lower() == "y":
outfile = input("What do you want to name the file?: ")
self._saveBand(f"{oufile}.txt")
If anyone can help me fix this, I would be super grateful.
In advance: Thank you for your help.
The complete program is pasted in below
import random
class Band:
def __init__(self, name):
self._Bandname = name
def __str__(self):
return f"{self._Bandname}"
def hentName(self):
return self._Bandname
class BandList:
def __init__(self):
self._BandList = []
def _readFile(self, filename1, filename2):
with open(filename1) as infile1, open(filename2) as infile2:
lineAdjective = infile1.read().splitlines()
lineNoun = infile2.read().splitlines()
adjective = random.choice(lineAdjective)
noun = random.choice(lineNoun)
return f"{adjective} {noun}"
def _saveBand(self, filename):
with open(filename, "w") as outfile:
for j, i in enumerate(self._BandList):
outfile.write(f"Nr: {j}\t-{i}\n")
def _generateBand(self):
num = int(input("\nHow many band names would you like to generate?: "))
for i in range(num):
bandname = f"The {self._readFile('adjective.txt', 'noun.txt')}s"
self._BandList.append(Band(name= bandname))
def _writeBand(self):
print("\n========= Genererte bandname =========")
for i in self._BandList:
print(i)
#print(i.hentName())
def _deleteBand(self):
self._BandList.clear()
def _writeGoodbyeMsg(self):
print("\n============ PROGRAM TERMINATING ================")
print("\t- thanks for using the program, goodbye!")
def menu(self):
done = False
while done != True:
print("\n=============== BAND NAME GENEREATOR ==================")
start = input("\nDo you want to generate a list of bandnames? (y/n): ")
if start.lower() == "y":
self._generateBand()
self._writeBand() #This is probably where the bug is...
inp = ("\nDo you want to save these band names? (y/n): ")
if inp.lower() == "y":
utfil = input("What do you want to name the file?: ")
self._saveBand(f"{utfil}.txt")
elif inp.lower() == "n":
self._deleteBand()
inp2 = input("Do you want to generate more band names? (y/n)?: ")
if inp2.lower() == "y":
self._generateBand()
elif inp2.lower() == "n":
done = True
self._writeGoodbyeMsg()
else:
print("Unknown command, please try again")
else:
self._writeGoodbyeMsg()
done = True
if __name__ == '__main__':
new = BandList()
new.menu()
You're missing an input call on your 2nd question for saving the band names. It should be:
inp = input("\nDo you want to save these band names? (y/n): ")
It does work. You just haven't given any values in self._BandList.
Its returning "BandList": null.
so I am writing program based on this instructions:
Write a function to exit the program, which automatically generates usernames based on the first letter of the first and last name and saves the entries in the dictionary.
For example: Brad Pitt --> bpitt
When the user no longer wants to enter names, write STOP.
Then the program asks him: Do you want to leave the program (yes / no)?
If the user enters "yes", the program ends with the greeting "Thank you for using".
If the user enters "no", the program continues to ask for first and last name.
If the user does not enter "yes" or "no", the program asks him if he really wants to leave the program until he enters one of the mentioned options.
At the end the program displays the contents of the dictionary.
I write this:
dict = {}
while True:
x = input('Enter name and surname: ').lower()
if x != 'STOP':
def name(s):
l = s.split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
s = x
print(name(s))
dict[x] = (name(s))
elif x == 'STOP':
a = input('Do you want to leave the program (yes / no)? ')
if a == 'Yes':
print('Thank you for using.')
exit()
elif a == 'No':
if x != 'STOP':
def name(s):
l = s.split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
s = x
print(name(s))
else:
a = input('Do you want to leave the program (yes / no)? ')
if a == 'Yes':
print('Thank you for using.')
print(dict)
exit()
elif a == 'No':
x = input('Enter name and surname: ')
if x != 'STOP':
def name(s):
l = s.split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
s = x
print(name(s))
At first it worked somehow, but not properly. Now I have made a mistake that I cannot find, because I am totally lost. Is there any easier way to write this code including function?
To answer your basic question, yes there is an easier way to write this code including the function. To begin, lets look at your basic coding style.
Using the variable name dict is a bad idea, since this can and will be confused with the builtin dict structure. This can lead to confusion in understand ing the code as well as subtle errors in execution should the compiler confuser your variable for the builtin function.
The creation of the function name is a great idea, since it splits out this operation into a separately executable and testable piece of code. Embedding thise function within the while loop is not such a good idea since it is unnecessary and I believe reduces the efficiency of the overall python script.
exit is a helper function for for the interactive shell and is not needed in this application
The following is my recommendations for improving your script.
def name(s):
l = s.lower().split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
def createDict():
names_dict = dict()
while True:
indata = input('Enter name and surname: ')
if indata.lower() == 'stop':
indata = input('Do you want to leave the program (yes / no)? ')
if indata.lower()[0] == 'y':
print('Thank you for using.')
print(names_dict)
break
else:
nm = name(indata)
print(nm)
names_dict[indata] = nm
To run use createDict()
I am new to Python. I am trying to run the following code. But every time I try to run it, the IDE says that the break is outside the loop
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Can you please help me?
Thanks
You use break when you want to break free from a loop, to exit the loop, to jump to the nearest code after the loop.
Your code doesn't contain a loop, so nothing to break free from, hence the error.
I think you meant exit() instead of break
You use "break" just inside the loop ("for" or "while"), you are trying use brake inside the "if"
How about this:
if name != '':
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Your break statement is not in a loop, it's just inside an if statement.
But maybe you want to do something like the following.
If you want to let the user enter an random number of names and print the names out, when the user entered nothing, you can do the following:
# Here we declare the list in which we want to save the names
catnames = []
# start endless loop
while True:
# get the input (choose the line which fits your Python version)
# comment out the other or delete it
name = input("Enter the name of a cat\n") # input is for Python 3
# name = raw_input("Enter the name of a cat\n") # raw_input is for Python 2
# break loop if name is a empty string
if name == '':
break
# append name to the list catnames
catnames.append(name)
print("The cat names are :")
# print the names
for name in catnames:
print(name)
What you are looking for is exit().
However, your code has also other problems, here is a piece of code that does what you probably want (when prompted, enter the names separated by spaces, like: Cat1 Cat2):
name = raw_input("Enter the name of the cats: ")
if len(name) == 0:
exit()
print("\nThe cat Names are:")
for c_name in name.split():
print(c_name)
If this is the entirety of your code, then it's telling you exactly what the problem is:
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
You have a break statement in the code that's not contained inside a loop. What do you expect the code above to do?
What I want to check for is if the user input is an empty string. I want the code to execute and output: "No input", however whenever I enter no input it goes to the next if statement and executes that with a blank value.
import urllib
import re
myString = " "
i = 0
def getStockPrice():
text_file = open("data.txt", "w")
url = "http://finance.yahoo.com/q?s=" + symbolslist
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
regex = '<span id="yfs_l84_' + symbolslist+ '">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern,htmltext)
if str(price) == myString:
print "No input"
else:
print "the price of", symbolslist," is ", price
text_file.write(str(price))
text_file.close()
dino = raw_input("What stock would you like to Check?: ")
symbolslist = dino
getStockPrice()
while i < 1000:
lilly = raw_input("What other stocks do you want to check?: ")
symbolslist = lilly
getStockPrice()
"Empty string is the one which len(String) == 0. In your case len(MyString) == 1"_wanderlust2
This gave me some insight on the issue, it was very amateurish for me to make this mistake. Thanks!
In Python, an empty string evaluates to False. That means that you can use a simple code to improve your if statement:
user_input = raw_input("Stock to check")
user_input = user_input.strip() # be sure to clear any whitespace!
if user_input:
# continue on with your program
...
If you use this Python idiom, your code will be more concise and easier to read. If you get used to it, you'll understand other Python programs that use the feature too.
For your code, I would refactor what you have to something like this:
while True:
user_input = raw_input("Stock to check")
user_input = user_input.strip() # be sure to clear any whitespace!
if user_input:
if user_input.lower() == 'quit':
break
getStockPrice(user_input)
That would rely on you changing your getStockPrice function to accept an argument though! That's a simple change. Try adding an extra word within your parentheses:
def getStockPrice(symbolslist):
I'm working on a school project and I have a problem. I have to write code for apothecary where clients can buy medicine. So, I need to make restrictions, which one doesn't go with others and etc. Here is the code:
def prodajLek():
lekovi = Fajl1.UcitavanjeLekova()
lekoviRed = []
brojacZaForPetlju = 1
n = 0
cena = 0
kolicina = []
korpa = []
rednibrojevilekova = []
ukupnacena = 0
print(" Fabricki naziv Genericki naziv Serijski broj Kolicina Cena \n")
for i in lekovi:
x = i.strip().split("|")
lekoviRed.append(x)
if lekoviRed[n][5] == "False":
print(brojacZaForPetlju,"\t {:10} \t {:10} \t\t\t {:3} \t\t\t {:4} \t\t {:5}".format(x[0],x[1],x[2],x[3],x[4]))
brojacZaForPetlju = brojacZaForPetlju + 1
n = n + 1
print("\n\n\n\n")
rednibrleka = input("Izaberite redni broj leka koji zelite da prodate:\n>>\t")
rednibrleka = int(rednibrleka)
rednibrleka = rednibrleka - 1
rednibrojevilekova.append(rednibrleka)
kolicinaZahteva = input("Koju kolicinu zelite da prodate?\n>>\t")
kolicinaZahteva = int(kolicinaZahteva)
if kolicinaZahteva > int(lekoviRed[rednibrleka][3]):
print("Nema toliko na lageru!\n")
Fajl1.LekarMenu()
kolicina.append(kolicinaZahteva)
cena = int(lekoviRed[rednibrleka][4])
korpa.append(cena)
print("Da li zelite da kupite jos lekova?\n1.Da\n2.Ne\n")
nastavakKupovine = input(">>")
if nastavakKupovine == "1":
prodajLek()
elif nastavakKupovine == "2":
Fajl1.LekarMenu()
So, when I get to the nastavakKupovine input, when I press 1, I need to continue shopping and store my row numbers, my price and quantity in arrays rednibrojlekova = [] , korpa = [] and kolicina = []. But I have a problem, because I dont know how to continue this without reseting these arrays to empty.
The standard idiom for what you want to do is a while True loop. Rather than show how to change your (rather long) function, here's a very simple one which hopefully shows the principle in a straightforward way:
def ask():
answers = []
while True:
response = input("What do you have to say? ")
answers.append(response)
check = input("Type 'q' to quit, anything else to repeat: ")
if check == "q":
break
else:
continue
return answers
For this simple function, the else: continue part isn't necessary, because the loop will continue anyway, but I've included it so you can see how to use it.
Here's an example of the function in action:
>>> ask()
What do you have to say? Something
Type 'q' to quit, anything else to repeat:
What do you have to say? Another thing
Type 'q' to quit, anything else to repeat:
What do you have to say? Ok, done
Type 'q' to quit, anything else to repeat: q
['Something', 'Another thing', 'Ok, done']
>>>
You can find out more about while, break and continue by reading the More Control Flow Tools chapter of the official Python tutorial.