How to call an item from a dictionary in python? - python

So I have a dictionary which consists of a number and its definition is the corresponding element on the periodic table.
I have built up the dictionary like this:
for line in open("periodic_table.txt"):
temp.append(line.rstrip())
for t in temp:
if t[1] != " ":
elements[x] = t[3:]
else:
elements[x] = t[2:]
x += 1
I know that every element is in table because I ask the program to print the dictionary.
The point of this is that the user enters a number or element name and the number and name are both printed like this:
while count == 0:
check = 0
line = input("Enter element number or element name: ")
if line == "":
count = count + 1
break
for key,value in elements.items():
if line == value:
print ("Element number for",line,"is",key)
check = 1
break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
break
if check == 0:
print ("That's not an element!")
This works for every element except the last one, Ununoctium, in the dictionary. When the user enters 118 this element is printed, but if they enter 'ununoctium' then the program says "That is not an element!". Why is this and how do I fix it?
Thanks in advance

It is much easier to have python do the lookup for you. Ignoring empty lines for now:
elements = []
for line in open("periodic_table.txt"):
elements.append(line[3:])
You can then do a lookup like this:
if answer.isdigit():
print elements[int(answer)]
else:
print elements.index(answer)

I suspect this is a case sensitive issue.
Changing
if line == value:
to
if line.lower() == value.lower():
would solve that problem.
While you are there, why have the if inside the for loop?
You could check that first, and then don't need the break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
#<-------- break no longer required
else:
#for loop as above

Related

Need help understanding while-loops and what it is doing

I am learning Python, and currently I am learning about sentinel loops. I have this piece of code that I need help understanding. What exactly is the while-loop doing? I did some research and I know it is looping through the if-statement (correct me if I am wrong); but is it looping through a specific equation until the user stops inputting their integers? Thank you in advanced.
(Please no hate comments I am still learning as a developer. & this is my first post Thanks)
even = 0 odd = 0
string_value = input("Please enter an int. value: ")
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
if even + odd == 0:
print("No values were found. Try again...") else:
print("Number of evens is: ", str(even)+".")
print("Number of odd is: ", str(odd)+".")
---Updated Code:
def main():
print("Process a series of ints enter at console \n")
count_even = 0
count_odd = 0
num_str = input("Please enter an int. value or press <Enter> to stop: ")
#Process with loop
while num_str !="":
num_int = int(num_str)
if num_int % 2 == 0:
count_even += 1
else:
count_odd += 1
num_str = input("Please enter an int. value: ")
if count_even + count_odd == 0:
print("No values were found. Try again...")
else:
print("Number of evens is: ", str(count_even)+".")
print("Number of odd is: ", str(count_odd)+".")
main()
First thing the while loop does is check if the user input is emptywhile string_value !="", if it is not empty than it will start the loop. The != means not equals and the "" is empty so not equals empty. Next it sets the variable int_value as the integer of the user input(will error if user inputs anything other than whole number). Next it checks if the variable int_value % 2(remainder of division by 2) is 0, so pretty much it checks if the number is divisible by 2, if it is divisible by two it will add 1 to the even variable. Otherwise it will add 1 to the odd variable
It will be very helpful if you go through python doc https://docs.python.org/3/tutorial/index.html
even = 0 odd = 0
The above line even and odd are variables keeping count of even number and odd number.
string_value = input("Please enter an int. value: ")
The above line prompt the user to input an integer
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
The above while loop check firstly, if the input is not empty, int() Return an integer object constructed from a number or string x, or return 0 if no arguments are given https://docs.python.org/3/library/functions.html#int. The if statement takes the modulus of the integer value, and then increases the counter for either odd or even.
Finally, the count of odd and even are printed.
the input() function waits until the user enters a string so unless the user enters an empty string the while loop will keep asking the user for strings in this line:
string_value = input("Please enter an int. value: ")
and check if its an empty string in this line:
while string_value !="":

how do I redo the input if data is in incorrect format?

so here is the question. I have 'for in range' for me to input value to the list
however, if I input value which is not numbers, it could only tells me I enter the wrong input but I can't re-enter the right value, it just keeps asking me to move forward to enter the next one.
How could I redo the input if I entered the wrong value(ex:english characters)so I could have a right value in certain position ?
Thanks a lot for any help ! rookie for python
the code I wrote is :
count=15
student=list()
print('please insert student score:')
for item in range(count):
line = input('enter score for student:'+str(item+1))
if line.isdecimal() and 0<=int(line)<=100:
data=int(line)
student.append(data)
else:
print(f"what you entered:Num{item+1:3d}is not a score")
total=0
for line in student:
total += line
totalF = total/15
print('Student Average Score is:','%.2f' % totalF)
print('Finish Input\n')
print("student:",student)
print('You have', end='--> ')
for item in student:
print(f'{item:d}', end=' ')
Extract the part of code getting the score into it's own function, and in this function put it in a while loop that will keep on asking for value until the value is valid:
def get_score(num):
while True:
value = input(f'enter score for student {num}:')
try:
# int(value) will raise a ValueError if value
# is not a proper representation of an int
value = int(value)
# now we have an int, test it's value,
# and raise a ValueError if it doesn't match
if not 0 <= value <= 100:
raise ValueError("value should be between 0 and 100")
# value is ok, done
return value
except ValueError as e:
# either it's not an int or it's not in the right range
print(f"Invalid value '{value}': {e}")
# naming tip: use a plural for collections
students = []
# tip: avoid those useless "item+1" things ;-)
for num in range(1, count+1):
score = get_score(num)
students.append(score)
You have to do your check in a loop and finish it when the score is correct.
Here with a simple boolean variable:
for item in range(count):
correct_score = False
while not correct_score:
line = input('enter score for student:'+str(item+1))
if line.isdecimal() and 0<=int(line)<=100:
data=int(line)
student.append(data)
correct_score = True # to get out of the loop
else:
print(f"what you entered:Num{item+1:3d}is not a score")
# we don't change `correct_score` here, so the loop will be executed again

Using Try and Except to allow bad input still stores the bad input

I am trying to get user input to store some numbers and print out the largest and smallest number. I need to have an except in my code that will print an error message then continue to print my numbers. The problem I am having is if I type a word like cat to get the error message, it also makes the word my largest number. I just want my error message followed by my 2 numbers
l = None
s = None
while True:
num = input('Enter your number')
if num == 'done':
break
try:
num=float(num)
except:
print('Invalid input')
if l is None:
l = num
elif num > l:
l = num
if s is None:
s = num
if num < s:
s = num
print('Maximum is ',l)
print('Minimum is ',s)
any help will be great thanks alot
I would add a continue right after your print('invalid input'). That will make it start the loop again and ask for another number from the user.

checking next and previous indexes

I'm trying to go through each index and check if it's greater than the next index or not, but I could not come up with any idea about how to do it. I tried using range and enumerate functions, but did not work so help would be much appreciated. This is my current code:
user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
test = []
for the_index, the_item in enumerate(arrayList):
Here is what I tried earlier than this
user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
first_numbers = []
second_numbers = []
finalList = []
for i in arrayList:
the_index = arrayList.index(i)
if the_index % 2 != 0:
first_numbers.append(i)
if the_index % 2 == 0:
second_numbers.append(i)
first_numbers.append(second_numbers)
Not sure i got this clear but if you want to know if user's input was bigger / smaller than the previous choice, you can do this:
This may not be the shortest way to do it, but this is a dynamic snippet where you can decide ask as much as inputs you want the user to answer:
user_choice = input('Choose some numbers: ')
user_choice_listed = user_choice.split(',')
marked_choice = None # Uninitialized integer that would be assigned in the future
for t in user_choice_listed:
converted_t = int(t)
if marked_choice != None and marked_choice < converted_t:
print('{0} is Bigger than your previous choice, it was {1}'.format(t,marked_choice))
elif marked_choice != None and marked_choice > converted_t:
print('{0} is Smaller than your previous choice, it was {1}'.format(t,marked_choice))
elif marked_choice == None:
print('This is your first Choice, nothing to compare with!')
marked_choice = converted_t # this is marking the previous answer of the user
NOTE: You can add a line to handle where the previous is equal to the current choice.
OUTPUT:
Choose some numbers: 1,3,5 # My Input
This is your first Choice, nothing to compare with!
3 is Bigger than your previous choice, it was 1
5 is Bigger than your previous choice, it was 3
Loop it through the indexes?
for i in range(len(arrayList)):
if arrayList[i] > arrayList[i + 1]:
//enter code here

list index out of range for while loop

def main():
infile = open('charge_accounts.txt', 'r')
chargeAccounts = infile.readlines()
index = 0
while index < len(chargeAccounts):
chargeAccounts[index] = chargeAccounts[index].rstrip('\n')
index += 1
userAccount = input("Please enter a charge account number: ")
count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
count += 1
if chargeAccounts[index] == userAccount:
print("The account number", userAccount, "is in the list.")
else:
print("The account number", userAccount, "in not in the list.")
main()
I'm trying to make a code in python that has the user input a number and checks to see if that number is in a list. When I try to run this code, I get an error that says that the list index is out of range in the while loop. There are only 18 items in the list, and I have the while loop set to terminate at 17(which should be 18 in the list).
Edit: It also doesn't work if the while loop is set to chargeAccounts[count] != chargeAccounts[17]:
Here's the exact error code:
Traceback (most recent call last):
File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 23, in <module>
main()
File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 13, in main
while userAccount != chargeAccounts[count] or chargeAccounts[count] != chargeAccounts[17]:
IndexError: list index out of range
Here's the content of the original text file:
5658845
4520125
7895122
8777541
8451277
1302850
8080152
4562555
5552012
5050552
7825877
1250255
1005231
6545231
3852085
7576651
7881200
4581002
A while loop will keep looping as long as its condition is True.
count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
count += 1
If I enter an invalid userAccount to your program, the first part of the condition userAccount != chargeAccounts[count] is always going to be True. That makes the entire condition True, since you're using or logic.
Furthermore, if you want to check to see if you've reached the end of a list, you don't have to check the contents of the last list element (chargeAccounts[count] == chargeAccounts[17]). Check the length instead (count == len(chargeAccounts)).
To fix this, change that loop condition to something like
while count < len(chargeAccounts) and userAccount != chargeAccounts[count]:
(I'm not sure if this is exactly what you need, because I don't really follow the logic of your program. This should get you past the current error, though.)
You get the error at the string if chargeAccounts[index] == userAccount: because index is already bigger than the index of the last element of the list (because you left the loop with this index above).
I would recommend you to follow a few rules to work with lists that could save you from similar errors with indices.
Use for-loop instead of while-loop, if you lineary go through each element.
Use break if you want to leave the loop and keep the index
So you code may look like this:
with open('charge_accounts.txt', 'r') as infile:
chargeAccounts = infile.readlines()
for index in range(len(chargeAccounts)):
chargeAccounts[index] = chargeAccounts[index].strip()
userAccount = input("Please enter a charge account number: ")
found = False
for chargeAccount in chargeAccounts:
if chargeAccount = userAccount:
found = True
break
if found:
print("The account number", userAccount, "is in the list.")
else:
print("The account number", userAccount, "in not in the list.")

Categories

Resources