I even used print statements to check if y.name and favourite were the same when checking this and they were yet it still wasn't entering the if statement when using
if y.name == favourite
or
if favourite ==y.name
I'm super confused as to why that is since I thought this was just a standard equality check (The beginning of the code is mostly set up, just included it for context in the case that there was a problem there and not the if statement). Thank you in advance!
class Anime(object):
name: str = ""
year_aired = 0
genre1: str = ""
def __init__(self, name, genre1, year_aired):
self.name = name
self.genre1 = genre1
self.year_aired = year_aired
def _make_anime(name, genre1, year_aired):
anime = Anime()
return anime
animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
if i.find("*") != -1:
animearr[numanime].genre1 = i
else:
k = Anime("","", 2018)
k.name = i
animearr.append(k)
numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
if y.name == favourite:
favgenre = y.genre1
print(favgenre)
I think you should add strip.("\n") before you compare two string.
class Anime(object):
name: str = ""
year_aired = 0
genre1: str = ""
def __init__(self, name, genre1, year_aired):
self.name = name
self.genre1 = genre1
self.year_aired = year_aired
def _make_anime(name, genre1, year_aired):
anime = Anime()
return anime
animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
if i.find("*") != -1:
animearr[numanime].genre1 = i
else:
k = Anime("","", 2018)
k.name = i
animearr.append(k)
numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
if y.name == favourite.strip("\n"):
favgenre = y.genre1
print(favgenre)
Related
I have the following code, however when I run it, the variable stored under employee_name is stated as "Name '[name inputted]' is not defined.
I've tried to comment it out, and the issue just arises with another line. Employee_num needs to be a string, as putting it as an integer claims it to not be iterable.
Can anyone help?
import time
ListNames = []
ListIDs = []
ListComissions = []
total_properties = 0
highest = 0
employee_num = "a"
employee_name = "aa"
employee_id= "a"
employee_properties = "a"
employee_comission = "a"
employee_num = str(input("Enter the number of employees: "))
for y in employee_num:
employee_name = input("Enter the name of the employee: ")
ListNames.append(employee_name)
employee_id = str(input("Enter the ID of the employee: "))
ListIDS.append(employee_id)
employee_properties = int(input("Enter the number of properties sold by the employee: "))
ListProperties.append(employee_properties)
total_properties = total_properties + employee_properties
employee_comission = employee_properties * 500
ListComissions.append(employee_comission)
total_comission = total_comission + employee_comission
for i in ListProperties:
if ListProperties[i] > highest:
highest = ListProperties[i]
i = i + 1
star = ListProperties.index(highest)
print (ListNames[star])
print (ListIDs[star])
print (ListProperties[star])
print (ListComissions[star])
starcomission = ListComissions[star] + (ListComissions[star] * 0.15)
x = 1
for x in employee_num:
if x != star:
print (ListNames[x])
print (ListIDs[x])
print (ListProperties[x])
print (ListComissions[x])
x = x + 1
My assignment requires 3 functions. The 1st takes several inputs and then returns a string. The 2nd and 3rd functions pull information from the 1st and return their own strings. The problem I'm having is that when I call the 2nd and 3rd functions in the main(), I'm being prompted for the inputs in the 1st function again. Otherwise, the 2nd and 3rd functions eventually produce the output I'm looking for.
I'm somewhat limited in how I can approach writing the functions due to the assignment criteria, so apologies if it's a bit roundabout. I'm pretty sure I'm missing the forest for the trees here, any help would be greatly appreciated!
def get_book_info():
input_book_title = str(input("enter book title: "))
format_title = input_book_title.strip()
format_title = format_title.title()
input_book_isbn = str(input("enter book ISBN: "))
format_isbn = input_book_isbn.strip()
input_author_name = str(input("enter author name: "))
format_author = input_author_name.strip()
format_author = format_author.title()
input_publisher = str(input("Enter publisher: "))
format_publisher = input_publisher.strip()
format_publisher = format_publisher.title()
input_year_published = int(input("enter year published: "))
input_price = float(input("enter book price: "))
info = f"{format_title}/{format_isbn}/{format_author}/{format_publisher}/{input_year_published}/{input_price:.2f}"
return info
def to_csv_format():
book_info_string = get_book_info()
book_csv = book_info_string.replace("/", ", ")
return book_csv
def to_json_format():
book_info_string = get_book_info()
# find title
separator = book_info_string.find("/")
json_title = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find ISBN
separator = book_info_string.find("/")
json_isbn = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find author
separator = book_info_string.find("/")
json_author = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find publisher
separator = book_info_string.find("/")
json_publisher = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find year published
separator = book_info_string.find("/")
json_year = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find price
json_price = book_info_string
book_json = f'"title":"{json_title}","isbn":"{json_isbn}",author_name":"{json_author}","publisher":"{json_publisher}","year_published:":"{json_year}","price":"{json_price}"'
return book_json
def main():
get_book_info()
print("----------------")
book_csv = to_csv_format()
print(book_csv)
print("----------------")
book_json = to_json_format()
print(book_json)
pass
main()
Every time you call get_book_info() you will prompted to enter your data. You have to call it only once in the main, store the result in a variable and pass this variable to your other functions.
def get_book_info():
input_book_title = str(input("enter book title: "))
format_title = input_book_title.strip()
format_title = format_title.title()
input_book_isbn = str(input("enter book ISBN: "))
format_isbn = input_book_isbn.strip()
input_author_name = str(input("enter author name: "))
format_author = input_author_name.strip()
format_author = format_author.title()
input_publisher = str(input("Enter publisher: "))
format_publisher = input_publisher.strip()
format_publisher = format_publisher.title()
input_year_published = int(input("enter year published: "))
input_price = float(input("enter book price: "))
info = f"{format_title}/{format_isbn}/{format_author}/{format_publisher}/{input_year_published}/{input_price:.2f}"
return info
def to_csv_format (book_info_string):
book_csv = book_info_string.replace("/", ", ")
return book_csv
def to_json_format (book_info_string):
# find title
separator = book_info_string.find("/")
json_title = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find ISBN
separator = book_info_string.find("/")
json_isbn = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find author
separator = book_info_string.find("/")
json_author = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find publisher
separator = book_info_string.find("/")
json_publisher = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find year published
separator = book_info_string.find("/")
json_year = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find price
json_price = book_info_string
book_json = f'"title":"{json_title}","isbn":"{json_isbn}",author_name":"{json_author}","publisher":"{json_publisher}","year_published:":"{json_year}","price":"{json_price}"'
return book_json
def main():
info = get_book_info()
print("----------------")
book_csv = to_csv_format (info)
print(book_csv)
print("----------------")
book_json = to_json_format (info)
print(book_json)
pass
main()
I am currently working on a program that takes in user inputs, and depending on that users input the string should change. I was wondering if there was a way I could alter the string once the user input has been received. The following is a sample code.
title = input('Title: ')
subtitle = input('Subtitle: ')
chapter = input('Chapter: ')
subchapter = input('Subchapter: ')
title1 = '/title{}'.format(title)
subtitle1 = '/subtitle{}'.format(subtitle)
chapter1 = '/chapter{}'.format(chapter)
subchapter1 = '/subchapter{}'.format(subchapter)
output_txt = title1+subtitle1+chapter1+subchapter1
print(output_txt)
Input taken by user: Should be a number
The input would then be formatted to its perspective string
Based on the user input the string, output_txt, should be formatted accordingly
Scenario 1:
User Input
Title: 4
Subtitle:
Chapter: 12
Subchapter: 1
output_txt should be
output_txt = '/title4/chapter12/subchapter1'
Scenario 2:
User Input
Title: 9
Subtitle:
Chapter: 2
Subchapter:
output_txt should be
output_txt = '/title9/chapter2'
I have been using if elif but since there could be multiple combinations I do not think doing it that way is the most efficient.
Any help or tips in the right direction is greatly appreciated
You could use an if-else condition while assigning string values to the variable
title = input('Title: ')
subtitle = input('Subtitle: ')
chapter = input('Chapter: ')
subchapter = input('Subchapter: ')
title1 = '/title{}'.format(title) if title else ''
subtitle1 = '/subtitle{}'.format(subtitle) if subtitle else ''
chapter1 = '/chapter{}'.format(chapter) if chapter else ''
subchapter1 = '/subchapter{}'.format(subchapter) if subchapter else ''
output_txt = title1+subtitle1+chapter1+subchapter1
print(output_txt)
Let me introduce you to typer
typer will help you to create a CLI with python easily
for your code can be approached like this
import typer
# By defining the data type, we can set the input only a number
def main(title: int = None, subtitle: int = None, chapter: int = None, subchapter: int = None):
title = f'/title{title}' if title else ''
subtitle = f'/subtitle{subtitle}' if subtitle else ''
chapter = f'/chapter{chapter}' if chapter else ''
subchapter = f'/subchapter{subchapter}' if subchapter else ''
output_txt = title+subtitle+chapter+subchapter
print(output_txt)
if __name__ == "__main__":
typer.run(main)
And you just need to run it by adding the parameter for each one you need
python script_name.py --title 5 --chapter 2 --subchapter 7
Here's an approach that uses a regular expression for input validation and list comprehensions to gather the inputs and build the output string.
import re
def get_input( label: str = None ) -> int:
entry = input(label + ': ')
if re.match(r'^\d+$', entry) is None:
return None
if int(entry) <= 0:
return None
return int(entry)
tpl_labels = ('Title', 'Subtitle', 'Chapter', 'Subchapter')
lst_values = [get_input(x) for x in tpl_labels]
output_txt = '/'.join([f'{x.lower()}{y}' for x, y in zip(tpl_labels, lst_values) if y])
if not output_txt:
print('No valid responses given.')
else:
output_txt = '/' + output_txt
print(output_txt)
The get_input() function expects each value entered by the user to be a positive integer. All other input is silently ignored (and None is returned).
Just for completeness you might want to test for a number as well.
# Test
def test_for_int(testcase):
try:
int(testcase)
return True
except ValueError: # Strings
return False
except TypeError: # None
return False
# Get the inputs
title = input('Title: ')
subtitle = input('Subtitle: ')
chapter = input('Chapter: ')
subchapter = input('Subchapter: ')
# Run the tests and build the string
output_txt = ''
if test_for_int(title):
output_txt += '/title{}'.format(title)
if test_for_int(subtitle):
output_txt += '/subtitle{}'.format(subtitle)
if test_for_int(chapter):
output_txt += '/chapter{}'.format(chapter)
if test_for_int(subchapter):
output_txt += '/subchapter{}'.format(subchapter)
print(output_txt)
You can do something like this...
def get_user_input(message):
user_input = input(message+' : ')
if user_input == '' or user_input.isdigit() == True:
return user_input
else:
return False
def f():
title = ''
while True:
title = get_user_input('title')
if title == False:
continue
else:
break
subtitle = ''
while True:
subtitle = get_user_input('subtitle')
if subtitle == False:
continue
else:
break
chapter = ''
while True:
chapter = get_user_input('chapter')
if chapter == False:
continue
else:
break
subchapter = ''
while True:
subchapter = get_user_input('subchapter')
if subchapter == False:
continue
else:
break
s = ''
s += '/title'+str(title) if title != '' else ''
s += '/subtitle'+str(subtitle) if subtitle != '' else ''
s += '/chapter'+str(chapter) if chapter != '' else ''
s += '/subchapter'+str(subchapter) if subchapter != '' else ''
return s
Output...
title : 1
subtitle : 2
chapter : 3
subchapter : 4
'/title1/subtitle2/chapter3/subchapter4'
title : 1
subtitle :
chapter : 3
subchapter :
'/title1/chapter3'
Obviously you need to add few changes to the code for your specific purpose.
def warehouseInventoryCreationBios():
bios = []
warehouseName = ["\nWarehouse: WBS"]
bios.append(warehouseName)
warehouse_initial_quantity_aircondSec = 1000
aircondSec = ["Section: AS", "Parts: compressor", "Part ID: ABS01", "Initial Quantity in the warehouse:", warehouse_initial_quantity_aircondSec, '\n']
bios.append(aircondSec)
.
.
return bios
warehouseInventoryCreationBios()
def updateBiosWarehouseInventory():
bios = warehouseInventoryCreationBios()
warehouseUpdateSupplier = []
name = input('Enter Supplier name: ')
name = name.lower()
id_parts = input('The id of the part: ')
id_parts = id_parts.upper()
order_from_supplier = int(input('How many orders from supplier: '))
warehouseUpdateSupplier.append(name)
warehouseUpdateSupplier.append(id_parts)
warehouseUpdateSupplier.append(str(order_from_supplier))
if name == 'tab':
if id_parts == "ABS01" or id_parts == "TBS05" or id_parts == "BBS02":
if id_parts == "ABS01":
compressor_quantity_warehouse = warehouse_initial_quantity_aircondSec + order_from_supplier
return compressor_quantity_warehouse
.
.
return warehouseUpdateSupplier
updateBiosWarehouseInventory()
Input: Enter Supplier name: tab
The id of the part: abs01
How many orders from supplier: 100
Output: NameError: name 'warehouse_initial_quantity_aircondSec' is not defined
How can I add the value warehouse_initial_quantity_aircondSec in the first function with the warehouse_initial_quantity_aircondSec in the second function
Newbie here, sorry ><
You are trying to use a variable in the second function, which is defined in the first as a local variable, you should return that value to use it:
def warehouseInventoryCreationBios():
bios = []
warehouseName = ["\nWarehouse: WBS"]
bios.append(warehouseName)
warehouse_initial_quantity_aircondSec = 1000
aircondSec = ["Section: AS", "Parts: compressor", "Part ID: ABS01", "Initial Quantity in the warehouse:", warehouse_initial_quantity_aircondSec, '\n']
bios.append(aircondSec)
.
.
# return multiple values (as tuple)
return bios, warehouse_initial_quantity_aircondSec
warehouseInventoryCreationBios() # this line is unnecessary, only calculations with no results used after it
def updateBiosWarehouseInventory():
# receive multiple values
bios, warehouse_initial_quantity_aircondSec = warehouseInventoryCreationBios()
warehouseUpdateSupplier = []
name = input('Enter Supplier name: ')
name = name.lower()
id_parts = input('The id of the part: ')
id_parts = id_parts.upper()
order_from_supplier = int(input('How many orders from supplier: '))
warehouseUpdateSupplier.append(name)
warehouseUpdateSupplier.append(id_parts)
warehouseUpdateSupplier.append(str(order_from_supplier))
if name == 'tab':
if id_parts == "ABS01" or id_parts == "TBS05" or id_parts == "BBS02":
if id_parts == "ABS01":
compressor_quantity_warehouse = warehouse_initial_quantity_aircondSec + order_from_supplier
return compressor_quantity_warehouse
.
.
return warehouseUpdateSupplier
updateBiosWarehouseInventory()
Alright so what I am trying to do is to get objects to save in list form when a user creates a NoteSet. It appends the objects to the list db properly when I input NoteSet('ex','example',True). I made a function called makeNewNoteSet() and it seems to be working correctly but it doesnt append to the db list. I can not figure out why.
import sys
import datetime
import pickle
notesets = []
db = []
def save():
global db
filename = "notesets.dat"
file = open(filename, "wb")
if file == None:
print("There was an error creating your file")
return
pickle.dump(db, file)
file.close()
print("Saved words to ",filename)
def load():
global db
filename = "notesets.dat"
file = open(filename, "rb")
db = pickle.load(file)
print("There are ",len(db)," Note Sets")
file.close()
class NoteSet:
nextseqNum = len(db)+2
def __init__(self,name,description,hidden):
global db
self.seqNum = NoteSet.nextseqNum
self.name = name
self.description = description
self.dateCreated = datetime.date.today()
self.hidden = hidden
self.notes = list()
NoteSet.nextseqNum += 1
print(self)
notesets.append(self)
notelist = [self.seqNum,self.name,self.description,self.dateCreated,self.hidden,self.notes]
print(notelist)
db.append(notelist)
NoteSet.nextseqNum += 1
def __str__(self):
printstr = str(self.seqNum),self.name,self.description,str(self.dateCreated)
printstr = str(printstr)
return printstr
class Note:
nextseqNum = 0
def __init__(self,text,dateCreated,description,category,priority,hidden):
self.text = text
self.dateCreated = str
self.dateRead = str
self.description = str
self.category = str
self.priority = int
self.hidden = bool
self.seqNum = Note.nextseqNum
Note.nextseqNum += 1
def main():
while True:
load()
printMainMenu()
selection = int(input("? "))
if selection == 1:
listNoteSets()
elif selection == 2:
listAllNoteSets()
elif selection == 3:
makeNewNoteSet()
elif selection == 4:
selectNoteSet() # this makes the working note set
elif selection == 5:
deleteNoteSet()
elif selection == 6:
sys.exit()
else:
print("Invalid choice")
def printMainMenu():
print("1. List note sets")
print("2. List all note sets (including hidden sets)")
print("3. Make a new note set")
print("4. Select a working note set")
print("5. Delete a note set")
print("6. Quit")
def listNoteSets():
num = 0
for row in db:
if db[num][4] == False:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def listAllNoteSets():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def makeNewNoteSet():
num = 0
name = input("What would you like to name your note set? --- ")
for row in db:
if name == db[num][1]:
print("That note set has already been created")
makeNewNoteSet()
description = input("Describe your note set briefly --- ")
hidden = input("Would you like this note set to be hidden? --- ")
if hidden == 'y' or 'yes':
hidden = True
else:
hidden = False
NoteSet(name, description, hidden)
print("noteset created you can now access it through the menu")
input("[Press enter to return to menu]")
main()
def selectNoteSet():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
response = input("Enter the number assosciated with the noteset you would like to access")
print("Note set #",response," was selected")
main()
After you add a new note in makeNewNoteSet(), you call main() which calls load() which overwrites the in-memory copy of the database you just changed. You probably want to call save() somewhere in there.