Jump to content

Help with my python code

Go to solution Solved by BlueChinchillaEatingDorito,

For one thing, your access to the teacher name and the rank number both lead to the exact same index:

print(staffRanks[staff+1], "was ranked", staffRanks[staff+1], "please enter new rank:")

Remove the +1 in the first staffRanks and you should get the name. Also, you're missing any sort of code to update the rank for current teacher. When it asks for new rank, all you're doing it taking input and printing that input. There's no code to perform an updates to the list. 

 

On a side note... I personally wouldn't use a list like that. I would've used Dictionaries and create a Dictionary for each Teacher with their name and rank, then add those to a list. 

https://www.w3schools.com/python/python_dictionaries_add.asp

 

Take for example: 

mylist = []
thisdict = {
	"name": "John",
	"rank": 1
}

# Add new dictionary to the list
mylist.append(thisdict)
print (mylist)

# Modify the rank for the first item (teacher in this context) in the list
mylist[0].update({"rank": 2})
print (mylist)

# Accessing individual items based on the key
print("Name:", mylist[0].get("name")) 
print("Rank:", mylist[0].get("rank"))

 

Results:

[{'name': 'John', 'rank': 1}]
[{'name': 'John', 'rank': 2}]
Name: John
Rank: 2

 

This way you don't need to do any gymnastics with indexes as they're a common cause of out of bounds errors when you have stuff like index + 1. You can simply iterate through the list using:

for i in mylist:
	# Code to ask for new rank and update rank here

 

And another side note, please use code tags instead of screenshots of your code.

Hello everyone, currently in class and cant seem to fix my code, the teacher is really busy and I'm starting to get angry, wondering if anyone can help? It's meant to have a list of ranks, then display the teachers name and ask for a new rank and replace it and continue to the next teacher after input is entered and then print the list after all of them are entered. Thanks

 

program1.PNG

program2.PNG

Link to comment
https://linustechtips.com/topic/1429943-help-with-my-python-code/
Share on other sites

Link to post
Share on other sites

For one thing, your access to the teacher name and the rank number both lead to the exact same index:

print(staffRanks[staff+1], "was ranked", staffRanks[staff+1], "please enter new rank:")

Remove the +1 in the first staffRanks and you should get the name. Also, you're missing any sort of code to update the rank for current teacher. When it asks for new rank, all you're doing it taking input and printing that input. There's no code to perform an updates to the list. 

 

On a side note... I personally wouldn't use a list like that. I would've used Dictionaries and create a Dictionary for each Teacher with their name and rank, then add those to a list. 

https://www.w3schools.com/python/python_dictionaries_add.asp

 

Take for example: 

mylist = []
thisdict = {
	"name": "John",
	"rank": 1
}

# Add new dictionary to the list
mylist.append(thisdict)
print (mylist)

# Modify the rank for the first item (teacher in this context) in the list
mylist[0].update({"rank": 2})
print (mylist)

# Accessing individual items based on the key
print("Name:", mylist[0].get("name")) 
print("Rank:", mylist[0].get("rank"))

 

Results:

[{'name': 'John', 'rank': 1}]
[{'name': 'John', 'rank': 2}]
Name: John
Rank: 2

 

This way you don't need to do any gymnastics with indexes as they're a common cause of out of bounds errors when you have stuff like index + 1. You can simply iterate through the list using:

for i in mylist:
	# Code to ask for new rank and update rank here

 

And another side note, please use code tags instead of screenshots of your code.

Edited by BlueChinchillaEatingDorito
Examples added.

Intel® Core™ i7-12700 | GIGABYTE B660 AORUS MASTER DDR4 | Gigabyte Radeon™ RX 6650 XT Gaming OC | 32GB Corsair Vengeance® RGB Pro SL DDR4 | Samsung 990 Pro 1TB | WD Green 1.5TB | Windows 11 Pro | NZXT H510 Flow White
Sony MDR-V250 | GNT-500 | Logitech G610 Orion Brown | Logitech G402 | Samsung C27JG5 | ASUS ProArt PA238QR
iPhone 12 Mini (iOS 18.3) | iPhone 15 (iOS 18.3.1) | KZ AZ09 Pro x KZ ZSN Pro X | Sennheiser HD450bt
Intel® Core™ i7-1265U | Kioxia KBG50ZNV512G | 16GB DDR4 | Windows 11 Enterprise | HP EliteBook 650 G9
Intel® Core™ i5-8520U | WD Blue M.2 250GB | 1TB Seagate FireCuda | 16GB DDR4 | Windows 11 Home | ASUS Vivobook 15 
Intel® Core™ i7-3520M | GT 630M | 16 GB Corsair Vengeance® DDR3 |
Samsung 850 EVO 250GB | macOS Catalina | Lenovo IdeaPad P580

Link to post
Share on other sites

simple dictionary makes more sense here. A dictionary has keys that can have values assigned to it. The key and value can be any object. In this example, the keys are strings of staff names while the values are integers of staff rank. Each key is unique, so if you add a value to an existing key, it will simply overwrite the value stored at the key

staff_ranks = {"Hagan": 10, "Hawkesworth": 8, "Robbins": 5, "Greenhill": 3, "Johnson-Meader": 3}

# adding another staff
staff_ranks["Hank"] = 9

# reading a value of a key
print(staff_ranks["Hagan"])

# keys() method returns a list of keys
print(staff_ranks.keys())

# values() method returns a list of values (but not the associated keys!)
print(staff_ranks.values())

# You can check whether a key exists in a dictionary using the 'in' keyword
print("Hank" in staff_ranks)  # True
print("Hagan" in staff_ranks)  # True
print("Hawking" in staff_ranks)  # False

# items() method returns the key and value pairs as a list of tuples
print(staff_ranks.items())

# overwriting values in a dictionary
for name, rank in staff_ranks.items():
    print(f"Name: {name}, Rank: {rank}")
    new_rank = input(f"Enter a new rank for {name}: ")  # input is a string
    staff_ranks[name] = int(new_rank)  # parse it as an integer

print(staff_ranks)

# sorting based on rank (advanced stuff)
print("Staff ranks in order:")
for name, rank in sorted(staff_ranks.items(), key=lambda item: item[1]):
    print(f"Rank #{rank}: {name}")


# Attempting to read a value that doesn't exist in the dictionary throws a KeyError
print(staff_ranks["foo"])

 

If you found my answer to your post helpful, be sure to react or mark it as solution 😄

Link to post
Share on other sites

10 hours ago, Sakuriru said:

I disagree, because it's possible that the instructor is requiring the use of an array. In any case, it's an academic setting.

 

staffRanks = ["Hagan", 10, "Hawkesworth", 8, "Robbins", 5, "Greenhill", 3, "Johnson-Meader", 1]

for i in range(0, len(staffRanks), 2):
    newRank = input(f"{staffRanks[i]} was ranked {staffRanks[i+1]}, please enter a new rank: ")
    staffRanks[i+1] = int(newRank)
    
print(staffRanks)

This will get you dangerous, OP. A note is that python 3.6 introduced string interpolation which is what the f before the quote is for. This permits the use of statements directly inline with the string by placing it between curly braces { }, which makes them cleaner and easier to understand and read.

 

If this makes you angry then that's a problem. Not understanding how to solve problems isn't going to stop in first year CS classes, it's going to continue throughout university and all of the way through your career.

Honestly if they require the use of an Array (not even 2D one) for this, then they're just setting up students to do some very messy stuff. I don't know the exact wording of the problem in question, but hopefully using two arrays is allowed. That way you can at least connect the two using the same index. Using odd indexes for one thing and even indexes for another is just not a wise idea. 

Intel® Core™ i7-12700 | GIGABYTE B660 AORUS MASTER DDR4 | Gigabyte Radeon™ RX 6650 XT Gaming OC | 32GB Corsair Vengeance® RGB Pro SL DDR4 | Samsung 990 Pro 1TB | WD Green 1.5TB | Windows 11 Pro | NZXT H510 Flow White
Sony MDR-V250 | GNT-500 | Logitech G610 Orion Brown | Logitech G402 | Samsung C27JG5 | ASUS ProArt PA238QR
iPhone 12 Mini (iOS 18.3) | iPhone 15 (iOS 18.3.1) | KZ AZ09 Pro x KZ ZSN Pro X | Sennheiser HD450bt
Intel® Core™ i7-1265U | Kioxia KBG50ZNV512G | 16GB DDR4 | Windows 11 Enterprise | HP EliteBook 650 G9
Intel® Core™ i5-8520U | WD Blue M.2 250GB | 1TB Seagate FireCuda | 16GB DDR4 | Windows 11 Home | ASUS Vivobook 15 
Intel® Core™ i7-3520M | GT 630M | 16 GB Corsair Vengeance® DDR3 |
Samsung 850 EVO 250GB | macOS Catalina | Lenovo IdeaPad P580

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×