Adding and checking values within a list of tuples - python-3.x

So i am trying to make a menu that will present the user with a function based on their choice, the purpose of the one below is to add words and the description of that word in a list of tuples (criteria of schoolwork) but i feel like i have hit a wall with what i currently have.
##Lägger in nya ord i ordboken
def menu2_val1(lista):
lista_ord = input("Input word ")
##Looping trough the list to look for duplicate words
for dup in lista[0]:
if dup in lista_ord:
print("The word already exists")
return menu2()
else:
lista_definition = input("Input definition ")
lista_ord = (lista_ord, lista_definition)
ny_lista = list(lista)
ny_lista.append(lista_ord)
lista = tuple(ny_lista)
If the word already exists in the list it should inform the user and go back to the menu
def menu2():
programm = 1
lista = [("word", "description")]
while programm > 0:
print("""
1.Insert
2.Lookup
3.Delete Word
4.Exit program
""")
menu2=input("(Tupel Meny)What would you like to do? ")
## Calls on functions based on input
if menu2=="1":
menu2_val1(lista)
elif menu2=="2":
menu2_val2(lista)
elif menu2=="3":
menu2_val3(lista)

Your code has the line for dup in lista[0]:, which will only loop through the first element of lista instead of the whole list.
Try out for dup in lista: instead and see if that helps.

Just for closure i did manage to solve it in the end with the following code
def menu2_val1(lista):
lista_ord = input("Input Word ")
dup = [x[0] for x in lista]
## Storing the first value of each in tuple in dup
if lista_ord in dup:
## Looks for the new word in dup
print("The word already exists")
return
else:
lista_definition = input("Input definition ")
nytt_ord = lista_ord, lista_definition
lista.append (nytt_ord)
Potato's suggestion would end up comparing string values to tuple values which wouldn't work

Related

How do i obtain the value of an item in a conditional statement?

How do I obtain the value of a dictionary item in a conditional statement for instance
names = {"one":"john", "two":"justin"}
prompt = input("enter option: ")
if prompt == names["one"]:
print("hey, I am here")
What will you suggest I go about it with a solution similar to line 3 so that I if the user inputs a key for instance "one" it prints "john"
in
In Python exists a keyword called in, which is used in several ways.
For example:
>>> 'i' in "in"
True
.keys() and .values()
The dict built-in class has two methods: keys() and values().
They're used like this:
>>> Dictionary = {"one":"john", "two":"justin"}
>>> Dictionary.keys()
["one", "two"]
>>> Dictionary.values()
["john", "justin"]
And they're also subscriptable, because they returns lists.
Answer
You can do like this:
names = {"one":"john", "two":"justin"}
prompt = input("enter name: ")
if prompt in names.values():
print("Hey, I'm here")
Edit
This should work:
# According to PEP-8 you should always leave a space after ':' in a dict
names = {"one": "john", "two": "justin"}
prompt = input("enter number: ")
if prompt in names.keys():
print(f"Hey, {names[prompt]} is here!")
you could try in
names = {"one":"john", "two":"justin"}
prompt = input("enter name: ")
if prompt in names.values():
print("hey, I am here")

checking a word in the text and print() a command once

Using these commands I get the three sentences.
AnyText = driver.find_elements_by_xpath('AnyXpath')
for AnyText1 in AnyText:
print(AnyText1.text)
In the console, I get something like that:
**
1) Hello my name is John
**
2) Hello my name is Mark
**
3) Hello my name is Alex..
How can I check that all three sentences have the word "name"
and print("OK") if the word is in the sentence (element) and print("ERROR") if not.
Im try:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1 for two in AnyText1):
print('OK')
else:
print('ERROR')
but this method only checks the first element (first sentence). I also tried something like this
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
for AnyText1 in AnyText:
if all(Text in AnyText1):
print('OK')
else:
print('ERROR')
but I get many times OK or ERROR
UPD:
With a question on the text, I figured out with your help. Now I want to understand the numbers)
I have a loop that checks the next number more or less. If more, writes ERROR, if less, writes OK
sort_month=driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div[1]/div/div[13]/table/thead/tr/th[3]/a[4]').click()
month2=driver.find_element_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
month2=month2.text.replace("'", "").replace(" ", "")
buffer = 0
if int(month2) > buffer:
print()
buffer = int(month2)
month1=driver.find_elements_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
print('ERROR')
elif int(spisok_month) < buffer:
print('OK')
else:
print('==')
buffer = int(spisok_month)
here I would also like to see OK or ERROR only once.
Any ideas?
The problem seems to be with the short form for loop in your first snippet. Basically it should look like the below:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
UPDATE:
On the updated part of your question, this is a different implementation as you have to update the condition in each iteration. For readability, it probably makes sense to keep this expanded:
outcome = 'OK'
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
outcome = 'ERROR'
elif outcome == 'OK' and int(spisok_month) == buffer:
outcome = '=='
buffer = int(spisok_month)
print(outcome)
Note: The update is almost a separate question. this means that either your first question was not representative of the actual problem or you should ask in a separate post
In you code AnyText1 is a WebElement, not a text. You should use AnyText1.text to get text and then it will work:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
# AnyText1 is a WebElement and you should get text
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
Please check coding conventions to improve code style.

Nested while loop, why this loop isnn't looping back to top?

I am trying to create a loop, that will rotate among users and get valid inputs. Inputs are dictionary words checked with external two files one containing allowed words and another restricted. It's a game where users have to say a word that starts with ending letter of their opponents' last word. You get up to 3 passes when you are out of words. When all three passes are takes, you lose the game. I have revised the code many times but it is not looping for some reason:
def game_logic(players_data):
"""takes in players data and initiates the game logic.
:param players_data: contains Player objects with name, word_list and pass_taken as attributes.
:type players_data: list containing dictionaries as items.
"""
# Initialise allowed and prohibited words from external file read.
with open("docs/wordDict.txt", "r") as wordDict:
allowed_words = wordDict.read()
with open("docs/excludeWords.txt", "r") as excludeWords:
prohibited_words = excludeWords.read()
game_switch = True
valid_word = False
player_turn = ""
start_letter = ""
while game_switch:
player_turn = players_data[0].name
if not players_data: # iff empty list
print("Something went wrong. I could not find players! Please restart the game.")
break
elif len(players_data) == 1: # when one person is left
print(f"{players_data[0].name} wins.\nCongratulations!\n°°*°°*°°*°°*°°*°°*° ")
print(f"beat all opponents in: {playtime - datetime.datetime.now()}")
break
else:
print(f"\nIt is {player_turn.upper()}'s turn")
# add a copy of first element to the end
players_data.append(players_data[0])
# remove the first element. so that next turn is next ones'.
players_data.remove(players_data[0])
# start the game
while not valid_word:
if not start_letter:
input_word = input(f"please enter a valid word to begin: ")
if input_word.lower() in allowed_words and input_word.lower() not in prohibited_words:
players_data[-1].word_list.append(input_word)
start_letter = input_word[-1].upper()
print(f"\nStarting letter for next player is: {start_letter}")
valid_word = True
return start_letter
else:
players_data[-1].pass_taken += 1
print(f"FOUL!\nThe word was not recognised as a valid word.\nPenalty: 1 pass({3 - players_data[-1].pass_taken})")
print("Turn goes to your opponent.")
valid_word = False
if players_data[-1].pass_taken >= 3:
print(f"LOST!\n{players_data[-1].name} is out of the game")
players_data.pop()
else:
input_word = input(f"please enter a valid word begining with letter {start_letter}: ")
if input_word.lower() in allowed_words and input_word.lower() not in prohibited_words and input_word[0].upper() == start_letter:
players_data[-1].word_list.append(input_word)
start_letter = input_word[-1].upper()
print(f"\nStarting letter for next player is: {start_letter}")
valid_word = True
return start_letter
else:
players_data[-1].pass_taken += 1
print(f"FOUL!\nThe word was not recognised as a valid word.\nPenalty: 1 pass({3 - players_data[-1].pass_taken})")
print("Turn goes to your opponent.")
valid_word = False
if players_data[-1].pass_taken >= 3:
print(f"LOST!\n{players_data[-1].name} is out of the game")
players_data.pop()
continue
´´´´
As Nico238 said in the comments, you break your loop with return statements inside every if/else statement. As this game relies on a logical progression (Whether a player has entered the correct first letter, and if it's in the dictionary) you need to handle loops carefully, preferably making them as flat (not nested) as possible, and of course not breaking out of them if you need to stay in the game loop.
My suggestion would be to remove those return start_letter statements as you already set it to be something other than empty, and this should continue your loop.

How can I print the required row when reading a csv file in python

I am a beginner of python, I have an assignment that wants me to read a csv file and print out the related information.
I have an excel file which includes student's ID, school and hobby.
now I want to write a program to show the detail of the student by entering the ID.
requirements are:
print the entire row when ID is correctly input
print "Empty, try again" when ID input is space
print "No record" when the input is invalid or there is no matching record
I manage to fulfill the first 2 requirements but have no idea how to get the third. Seems like my code is always looping through each of the data and print "No record" every time, i.e. if there are 3 records, 3 "No record" will be printed. Could someone help me with it? Much thanks! Below will be my code.
import csv
file = "a.csv"
sID = input("Enter ID: ")
while (sID == " "):
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row[id],row[school],row[hobby])
else:
print("No record")
You need a few changes:
You should use the str.strip() method to test if a string is empty so that it accounts for any number of spaces.
You should quote the column names to make them string literals when using them as indices to access the value of a column in the current row.
You should use the optional else block for your for loop to determine that there is no matching record found, and break the loop if there is one found.
You are missing a right parenthesis for the print call that outputs a row.
With the above changes, your code should look like:
import csv
file = "a.csv"
sID = input("Enter ID: ")
while not sID.strip():
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row['id'],row['school'],row['hobby']))
break
else:
print("No record")

Creating a autocorrect and word suggestion program in python

def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
while (user_input == ""):
user_input = input("key in word you wish to enter: ")
user_word = autocorrect(user_input).replace(' ', '')
with open('big.txt') as myFile:
for word in myFile:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
Basically when I had a dictionary of correctly spelled word in "big.txt", if I get the similar from the user input and the dictionary, I will print out a line
I am comparing between two string, after I sort it out
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
When I try hard code with other string like
if ("a" == "a"):
print("The word",user_input,"exist in the dictionary")
it worked. What wrong with my code? How can I compared two string from the file?
What does this mean? Does it throw an exception? Then if so, post that...
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
because I can run a version of your program and the results are as expected.
def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
#while (user_input == ""):
user_input = raw_input("key in word you wish to enter: ").lower()
user_word = autocorrect(user_input).replace(' ', '')
print ("user word '{0}'".format(user_word))
for word in ["mike", "matt", "bob", "philanderer"]:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
key in word you wish to enter: druge
user word 'degru'
The word druge doesn't exist in the dictionary
key in word you wish to enter: Mike
user word 'eikm'
('The word','mike', 'exist in the dictionary')
Moreover I don't know what all this "autocorrect" stuff is doing. All you appear to need to do is search a list of words for an instance of your search word. The "sorting" the characters inside the search word achieves nothing.

Resources