I am attempting to make some code that will take a persons height, convert it into feet and store it in a txt file.
def rollercoaster():
name = input("what is your name?: ")
heightCM = int(input("enter your height in cm: "))
ft = (heightCM / 30.48)
print(f"you are {ft} foot tall.")
if ft < 5.5:
booklist = open("booklist.txt", "a")
booklist.write(name)
booklist.write(" ")
booklist.write("NOT TALL ENOUGH.")
booklist.close()
if ft > 5.5:
booklist = open("booklist.txt", "a")
booklist.write(name)
booklist.write(" ")
booklist.write("TALL ENOUGH.")
booklist.close()
I would like to make it so if your name that you input is already in the txt file, it will see if you're tall enough for the rollercoaster.
Open your file and scan it for the names. Otherwise, append.
def rollercoaster():
name = input("what is your name?: ")
heightCM = int(input("enter your height in cm: "))
ft = (heightCM / 30.48)
print(f"you are {ft} foot tall.")
found = None
with open("booklist.txt") as f:
for line in f:
if line.startswith(name):
found = line
break
if found is not None:
print(found)
else:
with open("booklist.txt", "a") as booklist:
if ft < 5.5:
booklist.write(f'{name} NOT TALL ENOUGH\n')
else:
booklist.write(f'{name} TALL ENOUGH\n')
However, as mentioned in the comments, JSON would make more sense than scanning lines.
For example, mapping names to heights (in cm)
{
"alice": 158,
"bob": 172
}
Then read that, and perform the conversion and check if they are tall enough or not (there is no need to store whether or not they are tall enough in the file itself).
Related
In Python, This can not loop many times and cannot find ID number in def.
Every time I try to run the program I get the error
"NameError: name 'askname' is not defined"
and in textfile Keep only the latest data
I expect the output of #def new_booking to be Keep data in files continuously but the actual output is kept data in files just one sentence
I expect the output of #def pre_booked to be Extract data from a file but the actual output is
"NameError: name 'askname' is not defined"
import random
# total=0
# people=0
total1 = 0
total2 = 0
# mini bar
def mini_bar():
mini_bar_total = 0
print("£50 for the Bar")
askbar = input("Would you like a mini bar? Y/N")
if askbar.upper() == "Y":
mini_bar_total = mini_bar_total + 50
return mini_bar_total
# breakfast
def breakfast(people, asknights):
breakfast_total = 0
print("£25 for breakfast")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
breakfast_total = (people * 25) * asknights
print("total: £", breakfast_total)
return breakfast_total
# dinner
def dinner(people, asknights):
dinner_total = 0
print("£25 for Dinner")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
dinner_total = (people * 25) * asknights
return dinner_total
# number customers
def num_customers():
customer_total = 0
print("£50 an Adult")
askadult = int(input("How many adults? "))
customer_total = askadult * 50
print("total: £", customer_total)
print("£25 a Child")
askchild = int(input("How many children? "))
customer_total = (askchild * 25) + customer_total
print("total: £", customer_total)
return customer_total, askadult, askchild
# number of nights (multiplier)
def num_nights(customer_total):
nights_total = 0
waiting = True
while waiting == True:
try:
asknights = int(input("How many nights are you staying for? "))
nights_total = customer_total * asknights
print("total: £", nights_total)
break
except ValueError:
print("invalid input!")
return nights_total, asknights
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
for i in detailslist:
f = open('newbooking.txt', 'w')
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
# Pre booking ***** is not defind
def pre_booked():
name = input("enter your name or ID number: ")
if name == (askname) or (idnumber):
detailslist = [idnumber, askname, askadult, askchild, asknights, askbar, askbreakfast, askdinner]
for i in detailslist:
print(i)
print("total: £", total)
# main menu, start of program.
def main_menu():
print("##################### WELCOME TO BAY HOTEL ###########################")
print('''Please see what is available at the Hotel,\nAdult Prices per night: £50pp,\nChild price: £25pp,\nMiniBar price: £50 per room,\nBreakfast: £20pp,\nDinner: £25pp''')
while True:
prebook = input("Have you booked? Y/N")
if prebook.upper() == "N":
new_booking()
elif prebook.upper() == "Y":
pre_booked()
main_menu()
- I expect the output of #def new_booking to be Keep data in files continuously but the actual output is keep data in files just one sentence
- I expect the output of #def pre_booked to be Extract data from file but the actual output is "NameError: name 'askname' is not defined"
I think it's because your way to writing data in files.
Working with files has 3 step:
1) Opening file
2) Read [from] / Write [to] file
3) Closing file
third step is what you don't handled it.
You want to write a list in file and you are opening that file in each iteration. It's not a good idea (opening and closing files have their overhead) when you can do it once.
I changed some of your new_booking function and wrote it here:
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
# I handled opening and closing file with [python with statement]
# It close files automatically at the end
with open('newbooking.txt', 'w') as f:
for i in detailslist:
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
The problem here is that you havent actually defined askname in your pre_booked() function so you cant compare against it. In new_booking() you are asking for the username with askname = str(input("Please enter your name? ")) however in the pre_booked() case you dont so you cant use it there without first getting the values from somewhere.
Seeing that you save the new_booking() to a file you probably want to load the data from your file like this:
accounts = []
with open(r"<FILEPATH", "r") as booking_file:
for line in booking_file:
accounts.append(line)
In your new_booking function it might be better to put all the related data in line by line or maybe even use dicts so you can later be sure which values belong together instead of writing all the values into their own line. So you might want to do this instead:
with open('newbooking.txt', 'w') as booking_file:
f.write(detailslist)
Then you can read line by line and possibly use ´eval()´ to get a list or dictionary right from your string or atleast you know the values in one line belong together later on.
You might also want to consider using "a" for append instead of w for write in your bookings file depending if you want to have multiple booking values in your file or just the one.
I'm aiming to display records of employees with a salary between 2 user inputted values (in a format specified in my function printTuple(data)). So far I use the function choice2() to open the file, read line by line in a for loop, convert the line (which is a string) to an int, then grab the index of the salary so I can compare it to the 2 inputted values (. After that I take the line as a variable in "record" and go to makeTuple to turn it into a tuple, and then finally print it in my desired format inside printTuple.
When I attempt to run the choice2 function I get an error: "local variable 'myTuple' referenced before assignment". However I need to change the myTuple value to an int before I can compare it with the values the user inputted, so I'm not sure how to fix this.
Here is my program:
def makeTuple (employee):
myTuple = employee.split(" ")
(payroll, salary, job_title, *othernames, surname) = myTuple
return(myTuple)
def printTuple (data):
employee_str = "{:<15} {:20} {:<10} {:<15} £{:>1}"
print(employee_str.format(data[-1]+ ",", " ".join(data[3:-1]), data[0], data[2], data[1]))
def choice1():
op_1 = str(input("Please enter a Pay Roll number: "))
file = open(path)
lines = file.readlines()
for line in lines:
if op_1 in line:
record = line.strip()
myTuple = makeTuple(record)
printTuple(myTuple)
def choice2():
op_2a = int(input("Please enter a lower bound for the Salary :"))
op_2b = int(input("Please enter a higher bound for the Salary :"))
file = open(path)
lines = file.readlines()
for line in lines:
myTuple[0] = int(myTuple[0])
if myTuple[0] >= op_2a and myTuple[0] <= op_2b:
myTuple[0] = myTuple[0]
record = line.strip()
myTuple = makeTuple(record)
print(myTuple)
get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"
try:
f = open(path)
except IOError:
print('The file could not be opened.')
exit()
for line in iter(f):
record = line.strip()
myTuple = makeTuple(record)
printTuple(myTuple)
print("\n\nDisplay full details of an Employee with a given payroll number enter: '1'")
print("Display all employees with a salary within a specified range, enter: '2'")
print("Display the first and last name of all employees with a job title, enter: '3'")
print("Quit Program: '4'")
choice = int(input("Choose an option from 1-4: "))
while choice != 1 and choice != 2 and choice != 3 and choice != 4:
print("Incorrect Value, please choose a number from 1-4")
print("\n\nDisplay full details of an Employee with a given payroll number enter: '1'")
print("Display all employees with a salary within a specified range, enter: '2'")
print("Display the first and last name of all employees with a job title, enter: '3'")
print("Quit Program: '4'")
choice = int(input("Choose an option from 1-4: "))
if choice == 1:
choice1()
if choice == 2:
choice2()
if choice == 3:
choice3()
if choice == 4:
exit()
This is the text file I am reading from:
12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
12349 30000 Wizard Harry Potter
12350 15000 Entertainer Herschel Shmoikel Krustofski
13123 75000 Consultant Zlatan Ibrahimovic
13124 150000 Manager Gareth Southgate
13125 75000 Manager Juergen Klopp
13126 35000 Lecturer Mike T Sanderson
13127 200000 Entertainer Adele Laurie Blue Adkins
13128 50 Timelord Peter Capaldi
13129 250000 Entertainer Edward Christopher Sheeran
13130 32000 Secretary Wilma Flintstone
Any help is appreciated, thanks in advance.
Your error message (local variable myTuple referenced before assignment) points out the required solution. I have:
reordered (record = line.strip() and myTuple = makeTuple(record) to top of loop)
renamed some variables (myTuple is not very descriptive, and is actually a list anyway, better naming makes code much easier to read and reason about)
heavily commenting (I would not normally comment my own code this much, more as indications of what I have done and why)
Here is the updated code for choice2
def choice2():
lower_bound = int(input("Please enter a lower bound for the Salary :")) # Renamed for clarity
upper_bound = int(input("Please enter a higher bound for the Salary :")) # Renamed for clarity
# The following two lines are repeated multiple times, you should probably read
# the file once and store into a list (or better yet a dictionary
# keyed with pay roll number) and pass it into the function.
file = open(path)
lines = file.readlines()
for line in lines:
record = line.strip()
employee_details = makeTuple(record) # Rename muTuple to employee_details
# OR MORE SIMPLY employee_details = makeTuple(line.strip())
# Now we have the variable we can work with it
salary = int(employee_details[0]) # The only thing we do with the tuple is print it, so no need to modify it
if salary >= lower_bound and salary <= upper_bound:
# This does nothing, so deleted - myTuple[0] = myTuple[0]
print(employee_details) # Or more likely you want to use your custom print function printTuple(employee_details)
I am working with an external file which has data in the form of:
-12345 CSEE 35000 Bart Simpson
-12346 CSEE 25000 Harry Potter
-12350 Economics 30000 Krusty The Clown
-13123 Economics 55000 David Cameron
With the first item being the ID, the second the subject, the third the salary, and the rest being the name of the person.
In part of my program I am trying to print the information of the people who have salaries between values submitted by the user. I have put all the data in a list called lecturers then I put all the salaries in a separate list called lecturers salary and tried to make them integers because at first I thought the reason the for loop wasn't working was because when trying to access them from the lectures loop I thought they might still be part of a string at this point.
I have already used a loop in my program to print all the people who teach a specific subject. This subject is submitted by the user. I tried to use a for loop again for the salaries but its not working.
print""
# To God be the Glory
lecturer = []
lecturer_salary = []
x = 0
a = " "
print ""
String = raw_input("Please enter the lecturers details: ")
print ""
def printFormat(String):
String = String.split()
lastname = String[-1]
firstnames = " ".join(String[3:-1])
name = ", ".join([lastname, firstnames])
ID_Subject = " ".join(String[0:2])
money = String[2]
print "%s,%s %s %s" % (lastname,firstnames,ID_Subject,money)
printFormat(String)
while x < len(lecturer):
lecturer_salary.append(int(lecturer [x][2]))
x = x + 1
print ""
try:
fname = input("Enter filename within " ": ")
with open(fname) as f:
for line in f:
data = line.split()
printFormat(line)
line = line.split()
lecturer.append(line)
except IOError as e :
print("Problem opening file")
print ""
print ""
answer = raw_input("Would you like to display the details of lectureers from a particular department please enter YES or NO: ")
if answer == "YES" :
print ""
department = raw_input("Please enter the department: ")
print ""
while x < len(lecturer) :
for line in lecturer:
if lecturer[x][1] == department:
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
**elif answer == "NO" :
print ""
answer2 = raw_input ("Would you like to know all the lecturers within a particular salary range: ")
print ""
if answer2 == "YES":
lower_bound = int(input("Please enter the lower bound of the salary range: "))
upper_bound = int(input("Please enter the upper bound of the salary range: "))
print ""
while x < len(lecturer) :
for line in lecturer_salary:
if lower_bound < lecturer_salary[x] < upper_bound :
print lecturer_salary[x]
x = x + 1**
else:
print ""
print "Please enter a valid input"
So, you have an array of lecturer and one of lecturer salary. the
for line in lecturer_salary:
is not needed - just the while followed by the if. Note that this will only print out the salary, not the lecturer details. Since x is the index to both arrays you can access lecturer[x] for the rest. In truth you don't need the lecturer_salary at all, just walk through lecturer and check:
while x < len(lecturer) :
if lower_bound < lecturer[x][2] < upper_bound :
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
For starters, you shouldn't name your variable with a capital letter like String or Id_Subject.
It is simpler to break code into functions and try using a dictionary or class to improve readability and extensibility.
Here is a minimal code using class:
lecturers = [] # To store Lecturer instances, which isn't necessary
class Lecturer():
def __init__(self, id, subject, salary, name):
self.id = id
self.subject = subject
self.salary = salary
self.name = name
def readfile(filename):
"""read each line in a file and yield a list of fields"""
with open(filename, "r") as f:
for line in f.readlines():
# return a list of fields
yield line.replace("\n", "").split()
def new_lecturer(detail):
"""Return a new lecturer instance from a list of fields"""
return Lecturer(detail[0],
detail[1],
detail[2],
{"firstname": detail[3],
"lastname": detail[4]
})
def print_lecturer_detail(lecturer):
"""Accept a lecturer instance and print out information"""
print "{0},{1} {2} {3}".format(lecturer.name["lastname"],
lecturer.name["firstname"],
lecturer.id,
lecturer.salary)
def main():
"""This is where all the main user interaction should be"""
fname = raw_input("Enter filename: ")
for lecturer in (readfile(fname)):
lecturers.append(new_lecturer(lecturer))
print ""
answer = raw_input("Would you like to display lecturers by department(Y/N)?: ")
if answer == "Y":
print ""
department = raw_input("Please enter the department: ")
print ""
for lecturer in lecturers:
if lecturer.subject == department:
print_lecturer_detail(lecturer)
elif answer == "N":
# implement salary code here
pass
if __name__ == '__main__':
main()
This may be an overkill now, but it's better than dealing with lists in a long run. You'll see that dealing with properties become much simpler. You may want to improve each function further and make it more modular and reusable.
#Paul Morrington has the straight answer on the while part.
def perd():
Personaldetails_file = open("Personaldetails_file.txt", "w")
Personaldetails_file = open("Personaldetails_file.txt", "a")
pd = input("Are you a new user?")
if pd == "yes":
print ("Add your details")
####################################
age = int(input("how old are you?"))
DOB = input("Date of birth:")
gender = input("Gender:")
weight = int(input("weight in kg:"))
height = int(input("height in cm:"))
Personaldetails = (age, DOB, gender, weight, height)
Personaldetails_file.write(str(Personaldetails))
Personaldetails_file.close()
#######################################
def td():
choice = input("which trainning event would you like to access?\n1.swimming\n2.cycling\n3.running\nplease type in the number before the event of which you want to choose\n")
if choice == "1":
Swimming_file= open("Swimming_file.txt", "w")
totaldistance = input("what was the total distance you swam in meters?")
totaltime = input("how long did you swim for in minutes?")
speed = totaldistance/totaltime
print ("on average you where running at a speed of", speed, "mps\nyou can look at the tables to see how many calouries you have burnt")
total = (totaldistance, totaltime, speed)
Swimming_file.write(str(total))
Swimming_file.close()
elif choice == "3":
Running_file= open("Running_file.txt", "w")
totaldistanceR = int(input("what was the total distance you ran in KM?"))
totaltimeR = int(input("how long did you run for in minutes?"))
totaltimeR1 = 60/totaltimeR
speedR1 = totaldistanceR/totaltimeR1
calburn = (speedR1 * 95)/(60/totaltimeR1)
print ("\nThe records have been saved")
print ("\non average you where running at a speed of", speedR1, "KMph\nyou burnt",calburn," calouries\n")
totalR = (totaldistanceR, totaltimeR, speedR1, calburn)
Running_file.write(str(totalR))
Running_file.close()
##############################################################
elif choice == "2":
Cycling_file= open("Cycling_file.txt", "w")
with open("Personaldetails_file.txt", "r") as f:
content = [x.strip('\n') for x in f.readlines()]
lines = f.readlines()
for line in lines:
words = line.split(",")
age = (line.split)(0)
weight = (line.split)(3)
height = (line.split)(4)
################################################################
totaldistancec = int(input("what was the total distance you cycled in KM?"))
totaltimec = int(input("how long did you cycle for in minutes?"))
calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)
speedc = totaldistancec/totaltimec
print ("on average you where running at a speed of", speedc, "KMph\nyou burnt", calburn1, " calouries")
totalc = (totaldistancec, totaltimec, speedc)
Cycling_file.write(str(totalc))
Cycling_file.close()
Personaldetails_file.close()
when I un the program an error appears.
line 84, in td
calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)
UnboundLocalError: local variable 'weight' referenced before assignment
does anyone know how I can fix this error?
the code which is relevant to the question surrounded by '#'
You declare weight here
def perd():
...
gender = input("Gender:")
weight = int(input("weight in kg:"))
height = int(input("height in cm:"))
...
but you try to use it here in this other function:
def tr():
....
calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)
....
this is a separate function that does not know about the variables within the perd() function, and why should it? It does not need any of them to operate as functions should isolate pieces of code and be able to be used by themselves. In other words once perd() runs its local variables go out of scope. Take a look at this question, Short Description of the Scoping Rules?. To solve this you either need to make the input taken in perd() global, not advisable because it is not very pythonic. Or you can pass the value in as a function parameter like this:
td(weight, height, age):
#code here
Now you have access to the value passed in as weight within the td function. But you need to realize that these are not the same variables, they may share the same name but they are NOT the same. You will need to pass in all values that you want to use from the perd function. This is preferable because you are designing your functions in a way that they can be used modularity, so one can handle getting input from the user while the other can perform calculations on data that it already knows are valid, this allows for easier to read code, which is what python is all about
I am writing a program that will open a specified file then "wrap" all lines that are longer than a given line length and print the result on the screen.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wr.width = lLength
wr.expand_tabs = True
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
print(wraped)
main()
When I do this instead of wrapping it prints everything in the file as a list with commas and brackets, instead of wrapping them.
textwrap.TextWrapper.wrap "returns a list of output lines, without final newlines."
You could either join them together with a linebreak
print('\n'.join(wrapped))
or iterate through and print them one at a time
for line in wrapped:
print(line)