Looping and saving multiple inputs - python

I'm trying to loop through a set of inputs where I ask for a user's course grade, course hours and course code. The loop keeps on repeating until the user enters "done". Once the user has entered done I want it to print out the entered courses with grade and hours.
For Example:
course_count = False
#LOOP through Inputs
while not course_count:
#GET course code
course_code = input( "Please Enter the Course Code (or done if finished): " )
#IF course code is not equal to done (convert to lowercase)
if course_code.lower() != "done":
#GET course hours
course_hours = int( input( "How many credit hours was " + course_code + "? " ) )
#GET grade earned
course_grade = float( input( "What grade did you earn in " + course_code + "? " ) )
#ELSE END LOOP
else:
course_count = True
print("Course: " + course_code + " Weight: " + str( course_hours ) + " hours " + "Grade: " + str( course_grade ) + "%")
The problem is it will always print out only one inputted course, hour and grade. How would I save more than one answer using only accumulative strings?
The output I'm looking to make is:
# Please Enter the Course Code (or done if finished): COMP 10001
# How many credit hours was COMP 10001? 5
# What grade did you earn in COMP 10001? 75
# Please Enter the Course Code (or done if finished): COMP 20002
# How many credit hours was COMP 10001? 8
# What grade did you earn in COMP 10001? 95
# Please Enter the Course Code (or done if finished): done
# Course: COMP 10001 Weight: 5 Grade: 75%
# Course: COMP 20002 Weight: 8 Grade: 95%
It's for a school practice problem and were not allowed to use lists, arrays or dictionaries if that makes sense

You may find it useful to keep your information in a dictionary structure where the key is stored as the course code. Then it is as simple as iterating over each course saved in your dictionary to get the details.
Example:
course_count = False
course_info = {}
#LOOP through Inputs
while not course_count:
#GET course code
course_code = input( "Please Enter the Course Code (or done if finished): " )
course_info[course_code] = {};
#IF course code is not equal to done (convert to lowercase)
if course_code.lower() != "done":
#GET course hours
course_hours = int( input( "How many credit hours was " + course_code + "? " ) )
course_info[course_code]['hours'] = course_hours;
#GET grade earned
course_grade = float( input( "What grade did you earn in " + course_code + "? " ) )
course_info[course_code]['grade'] = course_grade
#ELSE END LOOP
else:
course_count = True
For course_code in course_info :
course_hours = course_info[course_code]['hours']
course_grade = course_info[course_code]['grade']
print("Course: " + course_code + " Weight: " + str( course_hours ) + " hours " + "Grade: " + str( course_grade ) + "%")

See if you can relate this simplified example to your code. To get the output you describe, you need to store the output text somehow and access it later:
output_lines = []
for i in range(10):
input_string = input("Enter some input")
output_lines.append(input_string)
for output_line in output_lines:
print(output_line)
From the comments, using only string "accumulation" (warning: quadratically bad):
output_text
for i in range(10):
input_string = input("Enter some input")
output_text = output_text + '\n' + input_string
print(output_text)
Note that the preferred way to build up a long string is to append to a list and use 'separator'.join(list_of_strings) or print one-by-one as above.

Use an output string output_string
Add each new line to the output string
...
output_string += "Course: {} Weight: {} hours Grade: {}\n".format(course_code, course_hours, course_grade"
#ELSE END LOOP
...
This accumulates the information into a string, using standard string formatting to insert the data from each pass through the loop.
At the end of the program, print the output string.
As others have noted, this is a pretty silly way of storing data, since accessing it, except to print out, will be difficult. Lists/dictionaries would be a lot better.

Related

Why is wikipedia.summary(string) removing letters from my string?

I am working on a program that can search wikipedia given an input like: "Who is Elon Musk" - however, with his specific example (and others), when the variable is placed into wikipedia.summary(string), it removes the "l" in "Elon Musk". Attached is my function:
import wikipedia
import spacy
def search_wiki(self, search):
nlp = spacy.load('en_core_web_sm')
doc = nlp(search)
subject_phrase = get_subject_phrase(doc)
try:
results = wikipedia.page(str(subject_phrase)) #removes here
final = results
print(wikipedia.summary(final, sentences=1))
except wikipedia.exceptions.PageError:
results = wikipedia.search(str(subject_phrase))
print("\nDid you mean " + results[0] + "?\n")
possible = results[0]
if input() == "yes":
final = possible
print(final) #prints "Elon Musk"
print(wikipedia.summary(final, sentences=1)) #removes here too
else:
print("\nThese are the other searches that came up for " + str(subject_phrase) + ":\n")
for r in results:
print(r)
print("\nPlease type the result you want me to search for:\n")
final = input()
print(wikipedia.summary(final, sentences=1))
except wikipedia.exceptions.DisambiguationError as e:
print("I couldn't find anything for " + str(subject_phrase) + ". Here are some related results:")
for o in e.options:
print(o)
print("\nWhich of these did you mean?")
final = input()
print(wikipedia.summary(final, sentences=2))
print("\nWould you like to hear more about " + final + "?\n")
if input() == "yes":
print("\nYou can read more about " + final + " at " + wikipedia.page(final).url + "\n")
entry = wikipedia.summary(final, sentences=3)
return lambda: entry, True
else:
entry = wikipedia.summary(final, sentences=1)
return lambda: entry, False`
I am pretty stuck, I have the variable printing right before the call to wikipedia.summary(string), so I know that the variable is not changing on my end (or at least I think).

How can I take another variable from a def function and add it to another def function to get a new sum?

def room1(phone_charge):
phone_charge = 5
import random
randNum = random.randint(1,5)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
return(positve)
I need to add positive to another function
def room5(phone_charge):
import random
randomNUM = random.randint(1,30)
positve2= str(phone_charge + randomNUM)
print("Your phone is now " + positve2 + " % charged\n")
return(positve2)
I need to add postive to the room5 variable postive2
I tried returning variables and putting them in the next function but then my code that was written behind where I entered the returning variable it was no longer highlighted
Since the two functions return their values, you can add them together after calling.
p1 = room1(phone_charge)
p5 = room5(phone_charge)
print(f"Total is {p1 + p5}")
Since the two functions have the same functionality use one function with an extra parameter.
import random
def room(phone_charge, rand_range):
randNum = random.randint(1,rand_range)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
return positve
room1 = room(5, 5)
room5 = room(10, 30)
total = room1 + room5

Python Loop Unable to interrupt

I'm making a curency converter, time converter and weather app for an year 12 computer sciences project. Im unable to interrupt the loop that is being used for the main menu/location selector.
Can anyone help?
The code is below.
##This program is intended to help travellers with date and currency conversions ##
##Changelog----->##
##V1 - Include code for Forex Converter, code modified from - https://www.w3schools.in/python/examples/real-time-currency-converter##
##V2 - Implement GUI##
##V2.1 - Implement Multiple Screens GUI##
##V3 - Remove all GUI aspects##
##V3.1 - Create initial loop##
##Import Modules##
from forex_python.converter import CurrencyRates
import time
import datetime
import python_weather
import asyncio
##Opening info##
##V3.1##
global enter
enter = 'GO'
while enter == 'GO':
print("========================================================================================================================================================================================")
print("")
print("Welcome to the Traveller Assisstant. This program is able to help you with currency conversions, date and time conversions and viewing weather details of your destination.")
print("")
print("========================================================================================================================================================================================")
time.sleep(2.5)
ori = str(input("Please enter your current country: "))
dest = str(input("Please enter your destination country: "))
time.sleep(5)
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
if check == 'YES':
enter = 'STOP'
elif check == 'NO':
print("Returning to Location Selector")
enter = 'GO'
##V1##
##Change Currency##
#cr = CurrencyRates()
#output = cr.convert(entry1, entry2, entry3)
#final = round(output, 2)
#print("THE FINAL AMOUNT IS:", final, c2)
A simple typo, that's all that was wrong.
In this line of code:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
You are attempting to use the method
.upper()
But your fatal flaw is that you forgot the parentheses.
I changed this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
To this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
And the code worked perfectly for me
EXPLANATION
In the original code, check could never be equal to 'YES' or 'NO', because of the typo;
.upper was never recognized as a strings' function and returned with this value:
<built-in method upper of str object at 0x105fec130>
.upper() on the other IS in fact a valid function for a string and returned with this value when it was supplied with the input of 'yes':
YES
If you need to exit from the loop when a condition is met you can achieve that easily by using break. So when your condition is met:
either add bellow enter = "STOP" the statement break or just replace enter = "STOP" for break
if check == 'YES':
enter = "STOP"
break
or
if check == 'YES':
break
both should work, I guess you could go with the first answer if you need to keep the state of the variable enter otherwise you could just use the second.
The problem with your original code is that you are missing a parenthesis on the declaration of the upper method in this line:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
instead it should be:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
if you don't add the parenthesis to upper() it means you are declaring the object method itself not triggering instead what the method actually does. (In this case making the string uppercase)

How to Access a list of titles(elements) from an array by inputting a single word?

I wrote a program that reads in a file. The name of the file was passed into my program as a command-line parameter. Each line of the file contained 3 fields, separated by a vertical bar, or pipe ("|").
The file contained information about books so each line contains a title(ex. Les Miserables), an author, and a genre which I put into three arrays:
title = []
author = []
genre = []
I am trying to input a word like "Les" and get the specific elements from the arrays and print it like "(Fiction), Les Miserables by Victor Hugo".
This is my code so far:
for word in myArray:
fields = word.split(|)
title.append(fields[0])
author.append(fields[1])
genre.append(fields[2])
entry = raw_input()
if entry == T or t:
titlEntry = raw_input("Please enter title:")
n = len(title)
for i in range(0,n):
if titlEntry == i:
print "(" + genre[i] + ") " + title[i] + " by " + author[i]
Please help
First of all, this is not the way to do it; a dictionary would be better and I would ask you look into other structures as well. Also, think about sanitizing the input you read from the command line. However, to get you going, you are close. Try:
titlEntry = raw_input("Please enter title:")
n = len(title)
for i in range(0,n):
if titlEntry == title[i]:
print "(" + genre[i] + ") " + title[i] + " by " + author[i]

How do I access the array using the for loop in the while loop

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.

Categories