I'm trying to convert input from the user into a tuple that goes into a list. I'm using the split method, but it seems to take the input and creates a tuple inside the list, but also creates another itself in the list also...I hope that made sense...anyways, I ran it in the visualizer, and saw that it was going to both each with an index of 0 and 1, so I figured I have one small detail outta whack.
In short:
Enter an employee's name. (Last, First)
and that last name, first name gets converted into the tuple and sent to the
list.
I figured a list of employees with two values would be better as a tuple in a list, correct? Let me know if I'm just off and it's better as a plain list.
Anyways, here's the code:
empList = []
empName = input("Please enter employee name. (Last name, First name):\n")
nameSplit = tuple(empName.split(","))
empList += nameSplit
salary = float(input("Please enter salary for " +str(empList[0:]) + ":\n" ))
grossSalary = salary
if (grossSalary > 100000):
fedTax = (grossSalary * .2)
else:
fedTax = (grossSalary * .15)
stateTax = (grossSalary * .05)
netSalary = (grossSalary - (fedTax + stateTax))
print('''\nGross Salary: {0:>5.2f} \n
Federal Tax: {minus:>2}{1:>6.2f} \n
State Tax: {minus:>4}{2:>4.2f} \n
Net Salary: {3:>10.2f}'''.format(grossSalary, fedTax, stateTax, netSalary,
minus = "-"))
empList = []
empName = input("Please enter employee name. (Last name, First name):\n")
nameSplit = tuple(empName.split(","))
empList += nameSplit
The last line empList += nameSplit adds/concatentates each item from the tuple to the list. It does not add the tuple itself:
>>> l = [1, 2, 3]
>>> l += (4, 5)
>>> l
[1, 2, 3, 4, 5]
You should use list.append() instead:
empList.append(nameSplit)
Now it will append the tuple:
>>> empList = []
>>> empName = 'Lastname, Firstname'
>>> nameSplit = tuple(empName.split(","))
>>> empList.append(nameSplit)
>>> empList
[('Lastname', ' Firstname')]
>>> empName = 'Else, Someone'
>>> nameSplit = tuple(empName.split(","))
>>> empList.append(nameSplit)
>>> empList
[('Lastname', ' Firstname'), ('Else', ' Someone')]
One other thing. Whitespace is left in the strings that you split with ,. You should strip each string prior to adding it to the list, and you don't really need the intermediate variable:
empList.append(tuple(s.strip() for s in empName.split(",")))
Here is an example session with your actual code (python3)
Please enter employee name. (Last name, First name):
Payne,Max
Please enter salary for ['Payne', 'Max']:
100000
Gross Salary: 100000.00
Federal Tax: -15000.00
State Tax: -5000.00
Net Salary: 80000.00
Therefore, the only modification I would do is
salary = float(input("Please enter salary for " + empList[1] + " " + empList[0] + ":\n" ))
Unless from your comment input = (Payne, Max), are you expecting the user to enter the parentheses? This will not produce a tuple in a list. Anyway, in your program empList can be a tuple or a list, it doesn't matter.
Related
I have a list which looks like this: [1 H 1.0079, 2 He 4.0026, 3 Li 6.941, 4 Be 9.01218, ...]
I want to ask the user of the program for the corresponding atomic number to the atom. So the program will take a random atomic symbol and ask the user what's the atoms atomic number.
Code so far:
class Atom:
def __init__(self, number, weight, atom):
self.number = nummer
self.atom = atom
self.weight = weight
def __str__(self):
return self.atom + " " + str(self.weight)
def __repr__(self):
return str(self.number) + " " + self.atom + " " + str(self.weight)
def atom_listan():
atom_file = open('atomer2.txt', 'r')
atom_lista = []
number = 1
for line in atom_fil:
data = line
weight = float(data.split()[1])
atom = data.split()[0]
new_atom1 = Atom(number, weight, atom)
atom_lista.append(new_atom1)
atom_lista.sort(key=lambda x: x.vikt)
atom_lista[17], atom_lista[18] = atom_lista[18], atom_lista[17]
atom_lista[26], atom_lista[27] = atom_lista[27], atom_lista[26]
atom_lista[51], atom_lista[52] = atom_lista[52], atom_lista[51]
atom_lista[89], atom_lista[90] = atom_lista[90], atom_lista[89]
atom_lista[91], atom_lista[92] = atom_lista[92], atom_lista[91]
atom_fil.close()
for i in range(len(atom_lista)):
atom_lista[i].number = i + 1
return atom_lista
Code so far where I create a list consisting of the elements information. I have tried using the random.choice module but I don't really know how to get only the atomic symbol from the list with random.choice and also have the corresponding atomic number to the random atom be the correct answer.
You can get the atomic symbol like this if you have the list of elements as you mentioned in the question.
import random
a=["1 H 1.0079", "2 He 4.0026", "3 Li 6.941", "4 Be 9.01218"]
random_choice = random.choice(a)
random_atom = random_choice.split(" ")[1]
print(random_atom)
Try this. Clearly you could put it into a loop. I just used a part of your List.
import random
elements = ['1 H 1.0079', '2 He 4.0026', '3 Li 6.941', '4 Be 9.01218']
choose = random.choice(elements)
splitted = choose.split(' ')
print('The element symbol is : ', splitted[1])
attempt = input('Enter the Atomic Number ')
if (attempt == splitted[0]):
print('Correct')
else:
print('Wrong')
I have a problem adding scores to an object with a for loop.
what I'm trying to achieve is this:
enter test num: 1
enter test score: 58
enter test num: 2
etc...
and then print out the three test numbers and the average, but I can't seem to get it to set the test num nor the score.
this is the error I get after tring to add test 1 and test 1 score:
Traceback (most recent call last):
File "d:\pyproj\Lecture 5\Main.py", line 27, in <module>
studentArray()
File "d:\pyproj\Lecture 5\Main.py", line 25, in studentArray s = student.setTestScore(test,score)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: student.setTestScore() missing 1 required positional argument: 'result'
Main.py
from student import student
def studentArray():
classSize = int(input("how big is the class? "))
classList = []
num=0
while not(num == classSize):
firstName = input("\nWhat's the students first name? ");
lastName = input("\nWhat's the students last name? ");
homeAddress = input("\nWhat's the students home address? ");
schoolAddress = input("\nWhat's the students school address? ");
courseName = input("\nWhat course is the students taking? ");
courseCode = input("\nWhat's the course code? ");
classList.append(student(firstName,lastName,homeAddress,schoolAddress,courseName,courseCode));
num+=1
for s in classList:
for i in range(len(classList)):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
print("\n",s)
studentArray()
studentclass.py:
from Course import Course
class student:
def __init__(self,first, last, home, school,courseName,courseCode):
self.firstName = first
self.lastName = last
self.homeAddress = home
self.schoolAddress = school
self.courseName = courseName
self.courseCode = courseCode
Course(courseName,courseCode)
self.testResults = []
def setTestScore(self,test,result):
if test < 1 | result < 0 | test > 100:
print("Error: Wrong test results.")
else:
self.testResults.append(result)
def average(self):
average = 0;
total = 0;
for result in self.testResults:
total += result
average = total / 3.0;
return average;
def __str__(self):
testAString = ""
for testResult in self.testResults:
testAString += str(testResult) + " "
result = "Student name:\n"+self.firstName + " " + self.lastName+"\n";
result += "Course name:\n"+self.courseName+"\n";
result += "Course Code: "+ self.courseCode+"\n";
result += "Test results:\n"+testAString+"\n";
result += "Average:\n", str(self.average()), "\n";
result += "Home Address:\n"+self.homeAddress+"\n";
result += "School Address:\n"+ self.schoolAddress;
return result;
Courseclass.py:
class Course:
def __init__(self,course,code):
self.course = course
self.code = code
def setCourseName(self,name):
self.course = name
def setCourseCode(self, code):
self.course = code
Issue is you are trying to run setTestScore function without instantiating the class. Either make it a staticmethod or call it from an object
for s in classList:
for i in range(len(classList)):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
print("\n"+s)
PS: Line
classList = [classSize]
creates a new list and adds classSize to the list as the first element. I assume you want to create a list with size of classSize. You do not need to specify length when creating lists in python.
Also,
testResults = []
this initalization is outside of init, which makes testResults a class variable, means it will be shared within all classes. I would advise you to move it inside init function
Editing upon your edit, you are trying to concat string with a tuple
result += "Average:\n", str(self.average()), "\n";
What you should do is:
result += "Average:\n" + str(self.average()) + "\n";
In python you don't need to end lines with ;
also you need to create an instance of the class and on that instance you can use the class methods
look in the code I added comments on every change
Main.py
from student import student
def studentArray():
classSize = int(input("how big is the class? "))
classList = []
num = 0
while num != classSize:
firstName = input("\nWhat's the students first name? ")
lastName = input("\nWhat's the students last name? ")
homeAddress = input("\nWhat's the students home address? ")
schoolAddress = input("\nWhat's the students school address? ")
courseName = input("\nWhat course is the students taking? ")
courseCode = input("\nWhat's the course code? ")
new_student = student(firstName, lastName, homeAddress, schoolAddress, courseName, courseCode)
classList.append(new_student)
number_of_test = int(input("\nHow many tests did the student had? "))
for i in range(number_of_test):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
new_student.setTestScore(test, score)
num += 1
for s in classList:
print("\n" + str(s))
studentArray()
studentclass.py
from Course import Course
class student:
def __init__(self, first, last, home, school, courseName, courseCode):
self.firstName = first
self.lastName = last
self.homeAddress = home
self.schoolAddress = school
self.courseName = courseName
self.courseCode = courseCode
self.testResults = []
Course(courseName, courseCode)
def setTestScore(self, test, result):
if test < 0 or result < 0 or result > 100:
print("Error: Wrong test results.")
else:
self.testResults.append(result) # append to the list
def average(self):
average = 0
total = 0
for result in self.testResults:
total += result
average = total / 3.0
return str(average) # str the average
def __str__(self):
testAString = ""
for testResult in self.testResults:
testAString += str(testResult) + " " # str the testResult
result = "Student name:\n" + self.firstName + " " + self.lastName + "\n"
result += "Course name:\n" + self.courseName + "\n"
result += "Course Code: " + self.courseCode + "\n"
result += "Test results:\n" + testAString + "\n"
result += "Average:\n" + self.average() + "\n"
result += "Home Address:\n" + self.homeAddress + "\n"
result += "School Address:\n" + self.schoolAddress
return result
There are several issues with your code, most of them involve try to concatenate strings and non string types, as well as a few type errors along the way. You are also using the bitwise | instead of or which are not the same thing.
Starting with your student class:
use the actual or keyword instead of using bitwise |, it may be providing accurate results for some answers but it is not operating in the way you think it is.
in your __str__ method there are a few instances where you are trying to contatenate a string and an int.
in your setTestScores function you want to append the result to the testResults list.
Here is an example fix for those problems:
class student:
testResults = []
def __init__(self,first, last, home, school,courseName,courseCode):
self.firstName = first
self.lastName = last
self.homeAddress = home
self.schoolAddress = school
self.courseName = courseName
self.courseCode = courseCode
Course(courseName,courseCode)
def setTestScore(self,test,result):
if test < 1 or result < 0 or test > 100:
print("Error: Wrong test results.")
else:
self.testResults.append(result)
def average(self):
average = 0
total = 0
for result in self.testResults:
total += result
average = total / 3.0
return average
def __str__(self):
testAString = ""
for testResult in self.testResults:
testAString += str(testResult) + " "
result = "Student name:\n"+self.firstName + " " + self.lastName+"\n"
result += "Course name:\n"+self.courseName+"\n"
result += "Course Code: "+ self.courseCode+"\n"
result += "Test results:\n"+testAString+"\n"
result += "Average:\n" + str(self.average()) +"\n"
result += "Home Address:\n"+self.homeAddress+"\n"
result += "School Address:\n"+ self.schoolAddress
return result
Next you have the studentArray function.
you don't need to specify the size of the classList since lists can be dynamically appended to.
you need to convert your instance to a string before concatenating it with the new line character.
Here is an example fix for that.
def studentArray():
classSize = int(input("how big is the class? "))
classList = []
num=0
while not(num == classSize):
firstName = input("\nWhat's the students first name? ")
lastName = input("\nWhat's the students last name? ")
homeAddress = input("\nWhat's the students home address? ")
schoolAddress = input("\nWhat's the students school address? ")
courseName = input("\nWhat course is the students taking? ")
courseCode = input("\nWhat's the course code? ")
s = student(firstName,lastName,homeAddress,schoolAddress,courseName,courseCode)
classList.append(s)
num+=1
for s in classList:
for i in range(len(classList)):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
print("\n"+str(s))
Making these adjustments this was the output of your code.
how big is the class? 1
What's the students first name? a
What's the students last name? b
What's the students home address? 10
What's the students school address? 12
What course is the students taking? art
What's the course code? 1
enter test number: 1
enter test score: 88
Student name:
a b
Course name:
art
Course Code: 1
Test results:
88
Average:
29.333333333333332
Home Address:
10
School Address:
12
finally if you want to add more test scores you need add another question that asks how many tests were taken in the class and then iterate based on the response.
num_tests = int(input('how many tests'))
for s in classList:
for i in range(num_tests):
test = int(input("enter test number: "))
score = int(input("enter test score: "))
s.setTestScore(test,score)
i'm trying to convert user input into only alphabets, and convert each alphabet into a number(ex. a=1, b=2), then the numbers together. I've been able to complete the first part, but not sure how to do the second part.
import re
name = input("Name: ")
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
for al in range(len(cleaned_name)):
print(numbers,sep='+')
#if input is jay1joe2, cleaned name will be jayjoe
#after the 'numerology', will print the following below
#10+1+25+10+15+5 = 66
Something like this should work for what you're trying to do.
Note: I'm hardcoding the name here rather than using the user input, so it's easier to test it out if needed.
import string
# name = input("Name: ")
name = 'jay1joe2'
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {char: i for i, char in enumerate(string.ascii_lowercase, start=1)}
result = list(map(numbers.get, cleaned_name))
print(*result, sep='+', end=' ')
print('=', sum(result))
Where the second part (after numbers) could also be written alternatively as follows, using f-strings in 3.6+:
result = [numbers[c] for c in cleaned_name]
print(f"{'+'.join(map(str, result))} = {sum(result)}")
Result:
Your 'cleaned up' name is: jayjoe
10+1+25+10+15+5 = 66
name = input("Name: ")
name = name.lower()
name1 = list(name)
Addition: int = 0
for k in name1:
if ord(k)-96 < 1 or ord(k)-96 > 26:
pass
else:
Addition = Addition + ord(k) - 96
print(Addition)
We can use ascii codes for Numbers and Characters :)
I'm having trouble entering data I keep getting the error "invalid literal for int() with base 10"
def strings_to_ints(linelist):
outputlist = []
for item in linelist:
outputlist.append(int(item))
return outputlist
def process_line(line):
global box_count, ship_class
linestrings = line.split()
name = linestrings[0]
linevalues = strings_to_ints(linestrings[:1])
quantity = linevalues [0]
ship_class = linevalues [1]
box_count = box_count + quantity
order_price = compute_price(quantity)
discounted_price = compute_discounted_price()
tax = compute_tax(discounted_price)
ship_cost = compute_ship_cost(quantity)
billed_amount = discounted_price + tax + ship_cost
outlist = [quantity, order_price, compute_discount(), tax, ship_cost, billed_amount]
return name, outlist
def enter_data():
global order_count
line = input('Enter Name, Quantity, and Ship Class: >>> ')
name, outlist = process_line(line)
order_count = order_count + 1
print(name, outlist))
I know I that the name should somehow be separate from the numbers but I can't figure out where to do this.
I added the most of code, all of the relevant parts I think. Hopefully, it's easier to understand
linevalues = strings_to_ints(linestrings[:1])
should be:
linevalues = strings_to_ints(linestrings[1:])
Assuming that both Quantity and ship class are integers, and are space separated
i.e.
Test 1 2
Whithout understanding all of your code, I think that the problem is that linestrings[:1] is an array containing at most the first element of linestrings. If you want all but the first, use linestrings[1:] instead.
I have to create a program that asks user to input the number of items to purchase. the program then asks the user to enter the item and price of each, give a total and provide the amount of change.
I am stuck on the part where I need to combine the lists and output the item and cost in currency format
#Checkout program
print "Welcome to the checkout counter! How many items will you be purchasing?"
number = int (raw_input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = raw_input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = float(raw_input ("What is the cost of %s ?" % groceryitem))
costs.append(itemcost)
order = {}
for index in range (min(len(grocerylist), len(costs))):
order[grocerylist[index]] = costs[index]
print ("This is your purchase") + str(order)
# the simple way
for index in range (min(len(grocerylist), len(costs))):
print("Item: %s Cost: $%5.2f " % (grocerylist[index], costs[index]))
or you can use the locale currency() function.. see Currency formatting in Python or https://docs.python.org/2/library/locale.html
In addition to the above approaches, you can also iterate over order.keys(). And to format use the in-built string methods. Here's an example.
>>> order = {1 : 10.23, 2 : 1.0, 3 : 3.99}
>>> for key, val in order.items():
... print "Item " + key + ": ", "$" + "{0:.2f}".format(val)
...
Item 1: $10.23
Item 2: $1.00
Item 3: $3.99
you can directly store it in dictionary:
#Checkout program
print "Welcome to the checkout counter! How many items will you be purchasing?"
number = int(raw_input ())
order = {}
for i in range(number):
groceryitem = raw_input("Please enter the name of product %s:" % (i+1))
itemcost = float(raw_input("What is the cost of %s ?" % groceryitem))
order[groceryitem] = itemcost
print("your Purchase")
for x,y in order.items():
print (str(x), "$"+str(y))
note: order.values() will give you price list
order.keys() will give you item list
Read about dictionary here :Dictionary
demo:
>>> order = {'cake':100.00,'Coke':15.00}
>>> for x,y in order.items():
... print(x,"$"+str(y))
...
cake $100.0
Coke $15.0
better using format:
>>> for x,y in enumerate(order.items()):
... print("Item {}: {:<10} Cost ${:.2f}".format(x+1,y[0],y[1]))
...
Item 1: cake Cost $100.00
Item 2: Coke Cost $15.00
Make it tabular:
print("{:<5}{:<10}{}".format("Num","Item","Cost"))
for x,y in enumerate(order.items()):
print("{:<5}{:<10}${:.2f}".format(x+1,y[0],y[1]))
print("{:>10}{:>6}{:.2f}".format("Total","$",sum(order.values())))
Num Item Cost
1 cake $100.00
2 Coke $15.00
Total $115.00