I have a text file as following:
1, Max Mustermann, Male, 1000.0
2, Nora Mustermann, Female, 790.0
3, Tomas Mustermann, Male, 400.0
i want to read the last value from the fourth column if i type the persons number and the number 1 to show the value. Unfortunately, I can't get any further from here. How can i do this?
data_next = []
for data in open("my_data.txt"):
liste = data.split(",")
number = int(liste[0])
name = liste[1]
sex = liste[2]
value = liste[3]
data_next.append(number)
print(f" [{number}] {name} {sex} {value}")
which_person = int(input("WHICH PERSON?: "))
if which_person in data_next:
print("Do you want to know the value? Press 1 for YES or 2 for NO")
next_input = int(input("YOUR INPUT: "))
if next_input == 1:
print(value)
elif next_input == 2:
print("THX")
You need to save the values as well in the structure, a dict is very well suited for that : number as key, values as value
data_next = {}
with open("my_data.txt") as fic:
for data in fic:
liste = data.split(",")
number = int(liste[0])
data_next[number] = liste[1:]
print(f" [{number}] {liste[1:]}")
Then use the dict, to access the values
if which_person in data_next:
print("Do you want to know the value? Press 1 for YES or 2 for NO")
next_input = int(input("YOUR INPUT: "))
if next_input == 1:
print(data_next[which_person][2])
elif next_input == 2:
print("THX")
With regex you can handle nicely the comma+space delimiter
data_next = {}
with open("my_data.txt") as fic:
for data in fic:
nb, *others = re.fullmatch(r"(\d+),\s*([^,]+),\s*(\w+),\s*(\d+.?\d*)", data).groups()
data_next[nb] = others
print(f" [{nb}] {' '.join(others)}")
which_person = input("WHICH PERSON?: ")
The for-loop at the beginning of your code succeeds in placing all of the 'values' from the text file into one list.
data_next = ["1000.0", "790.0", "400.0"]
However, that list isn't useful for what you are trying to do below, which is to take input for one of the names from the data file and print the corresponding number. What you want for this is a dictionary, which links from one value to another. To achieve this, use the following code:
# set data_next to an empty dictionary
data_next = {}
for data in open("my_data.txt"):
liste = data.split(",")
number = int(liste[0])
name = liste[1]
sex = liste[2]
value = liste[3]
# set the current number equal to the current value in the dictionary
data_next[number] = value
print(f" [{number}] {name} {sex} {value}")
which_person = int(input("WHICH PERSON?: "))
# data_next.keys() will return an iterable of all of the id numbers in the dictionary
if which_person in data_next.keys():
print("Do you want to know the value? Press 1 for YES or 2 for NO")
next_input = int(input("YOUR INPUT: "))
if next_input == 1:
# data_next[which_person] will return the value in the dictionary assigned to the number which_person
print(data_next[which_person])
elif next_input == 2:
print("THX")
Another thing:
This code will perform slightly differently than you expect because of how the file is formatted When you split each line by ",".
"1, Max Mustermann, Male, 1000.0".split(",") == ["1", " Max Mustermann", " Male", " 1000.0"]
As you can see, the spaces after each comma are included with the next value. To fix this, change the split statement to split(", ") instead of split(",") OR remove the spaces after the commas in the file.
maybe the easyst way is
from csv import reader
from sys import exit
def get_person_row(number:int)->list or None:
with open('my_data.txt','r') as file:
table= reader(file)
for row in table:
if int(row[0]) == number:
return row
try:
which_person = int(input("WHICH PERSON?: "))
except ValueError:
print('just numbers are valid for Id')
exit(1)
line = get_person_row(which_person)
if line is None:
print('invalid id')
else:
print(str(line))
Related
When user adding details to a dictionary, I want check those details are already there or not,
When name, age, team and car have same values in another record ignore those inputs and tell the user "It's already there" otherwise "add" details to the dictionary. Also, this duplication check should happen before appending to the List.
I don't how to do this I tried but it doesn't work
driver_list = []
name = str(input("Enter player name : "))
try:
age = int(input("Enter the age : "))
except ValueError:
print("Input an integer",)
age = int(input("Enter the age : "))
team = str(input("Enter team name : "))
car = str(input("Enter name of the car : "))
try:
current_points = int(input("Enter the current points of the player : "))
except ValueError:
print("Input an integer")
current_points = int(input("Enter the current points of the player : "))
driver_details={"Name":name ,"Age": age,"Team": team ,"Car": car, "Current_points": current_points}
driver_list.append(driver_details)
# check all values in the driver_det is found in any of the
# dictionaries in the list driver_list
def checkAllInList(driver_det):
# define the keys we are interested in
Interest = ['name', 'age', 'team', 'car']
# get corresponding values from the driver_det
b = set([value for key, value in driver_det.items() if key in Interest])
# iterate over all driver_list dictionaries
for d in driver_list:
# get all values corresponding to the interest keys for the d driver
a = set([value for key, value in d.items() if key in Interest])
# if both have the same values, return true
if a == b:
return True; # if found equal, return true
return False; #otherwise, return false if non of the dictionaries have these details
# you can use it like that
if checkAllInList(driver_details): # check a duplicate is found
print("this is a duplicate value")
else: # no duplicate found
driver_list.append(driver_details)
Is it possible to have questions and answers exported to a text file such as result.txt?
I answer all the questions and at the end - all the information is saved in a txt file as a list, that can be viewed later.
Example:
Question 1
Answer 1
Question 2
Answer 2
...
I was wondering about file=open, but would that be right?
And how do I export input questions with file open?
I hope you can help.
from datetime import date
today = date.today()
date = today.strftime("%d.may, %Y.year\n")
print("Today is:", date)
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
while True:
name = input("Let's see!\nWhat is your name? ")
description = input("Enter a description of the environmental pollution: ")
city = input("In which city is environmental pollution observed? ")
address = input("Enter your residential address: ")
try:
question = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n" ))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if question == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif question == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
As you wanted the file content as a key-value pair, initialize a dictionary and add the corresponding values, instead of using separate variables for names, descriptions, etc. use them as dictionary keys.
First, initialize a global dictionary
global mydict
Initialize it in Vide() function. (use of global keyword because mydict is being modified in a function)
global mydict
mydict = {}
Store question and answer as a key-value pair
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
In try block:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
Now the if-else statements:
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
After calling the function Vide(), write your dictionary to a file
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
Whole code
global mydict
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
global mydict
mydict = {}
while True:
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
try:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
This can be done by writing or appending to a text file. You are correct, we can use the file = open structure to achieve this. I suggest writing something like the following:
file = open('results.txt', 'w')
Then use the following to write to the file once it has been opened.
file.write("Use your variables and questions from before to print user entered data")
Don't forget to close the file once you're done!
file.close()
So i have this college python project that asks me to make a program to manage an inventory, my question basically is that whenever I try to convert the price and the quantity again to floats this exception rase, so how can I convert them so I can make further process on them?
note that I tried to use .strip but it didn't work
this is the error:
float_price = float(i)
ValueError: could not convert string to float: '.'
this is the code that I have issues with:
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
float_price = float(i)
price += float_price
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
this is the code to add data to the file:
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n' + make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to import the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+ '\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
as error message indicates '.' is string and it cannot be converted to float so raises error.. it depends what you want to do with such situation you can use try except as.
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
try:
float_price = float(i)
price += float_price
except ValueError as e:
print('Value Error')
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
I am writing a python program that requests a name and age. Store that data in a List. After the user has entered data, request that the user enters 'y' or 'n' to continue. If they enter 'n', print the list of names and ages figures to the screen. If they enter 'y', repeat the first step.
This is what I have done.
keepAsking = True
# Keep looping for as long as keepAsking is equal to true
while(keepAsking == True):
stdName = input(" Name: ")
ageRecord = int(input("Age: "))
name_array = list()
age_array = list()
name_array.append(stdName)
age_array.append(ageRecord)
# Create and set checkContinue
checkContinue = True
# Keep looping for as long as checkContinue is equal to true
while (checkContinue == True):
# Ask the user if they wish to continue, and store it in doContinue
doContinue = input("Continue? ")
# Did they enter yes?
if (doContinue.lower() == "yes") :
# If so, stop asking if they want to continue, but keep asking
# everything else. Thus checkContinue is made false, but keepAsking
# remains true
checkContinue = False
# Did they enter no?
elif (doContinue.lower() == "no") :
# If so, stop asking if they want to continue ...
checkContinue = False
print (name_array)
print (age_array)
This is what its meant to show
Name: Faith Wisdom
Age: 28
Continue? [y/n] y
Name: Mitchell Train
Sales: 15
Continue? [y/n] n
Faith Wisdom 28
Mitchell Train 15
but with what I wrote, it's showing
Name: Faith Wisdom
Age: 28
Continue? [y/n] y
Name: Mitchell Train
Sales: 15
Continue? [y/n] n
Mitchell Train 15
The first entry is not saving in the list
You initialize your arrays in each step here:
while(keepAsking == True):
name_array = list()
age_array = list()
This will write over everything you saved at each step. Try taking the definitions out of your while loop:
name_array = list()
age_array = list()
while(keepAsking == True):
# do other stuff as usual
Some issues in your code.
You are redefining name_array and end_array for every while loop, but you want to define the list outside the loop, and update it inside the while loop
You have two while true loops, but you can just have one while loop and update keepAsking accordingly
keepAsking = True
name_array = list()
age_array = list()
while(keepAsking):
#Get nane and input
stdName = input("Name: ")
ageRecord = int(input("Age: "))
#Update name and age array
name_array.append(stdName)
age_array.append(ageRecord)
#Get input from user
doContinue = input("Continue? [y/n] ")
#Based on user input, keep asking or stop
if (doContinue.lower() == "y") :
keepAsking = True
elif (doContinue.lower() == "n") :
keepAsking = False
So the output now will look like.
Name: Faith Wisdom
Age: 28
Continue? [y/n] y
Name: Mitchell Train
Age: 15
Continue? [y/n] n
['Faith Wisdom', 'Mitchell Train']
[28, 15]
As pointed by Hoog's answer name_array and age_array should be defined before and outside the while loop.
Disclaimer: I've modified the names of the variables according to the PEP8 style guide.
Option 1: keeping 2 lists
If you refactor check_option into a function you can call it recursively when the option selected by the user is not among the correct. Also, as the name and age lists have always the same length, you can zip them just before iterating over them and printing its contents together every iteration in the for loop.
name_array = list()
age_array = list()
def check_continue():
response = input('Continue? [y/n] ')
if response == 'n':
return False
elif response == 'y':
return True
else:
print('Please select a correct answer [y/n]')
return check_continue()
while(True):
std_name = input('Name: ')
age_record = input('age: ')
name_array.append(std_name)
age_array.append(age_record)
if not check_continue():
break
else:
continue
for name, age in zip(name_array, age_array):
print(name, '\t', age)
Option 2: merging the lists
By using a tuple to pack both std_name and age_record variables, you suppress the need of ziping two lists by keeping all the n th iteration data in the n th index of a single list.
users = list()
def check_continue():
response = input('Continue? [y/n] ')
if response == 'n':
return False
elif response == 'y':
return True
else:
print('Please select a correct answer [y/n]')
return check_continue()
while(True):
std_name = input('Name: ')
age_record = input('age: ')
user = (std_name, age_record)
users.append(user)
if not check_continue():
break
else:
continue
for name, age in users:
print(name, '\t', user)
Note: In Python there is a built-in module called array which provides the array object type. Because you might not want to include 'array' in the list's names. You might better want to think on a plural name describing the elements inside the list as the list are aimed to contain the same type of elements in contrast with tuples (although you are not forced to).
Initialize your arrays outside the while loop because every time you will loop you will rewrite your array and you will save only the last answers.
name_array = list()
age_array = list()
# now you write your loop
I think you are over thinking this problem. Also, you need to append to your list properly, which is your main issue.
name_age = []
while 1:
stdName = input(" Name: ")
ageRecord = int(input("Age: "))
name_age.append([stdName,ageRecord])
doContinue = input("Continue? ")
if doContinue[0].lower() == "n":
for name, age in name_age:
print(name, age)
break
Hello everyone so I have an issue trying to find the user input in a dictionary.
My function is getting data from a website and writing it to a text file. Then transferred into a dictionary, from there I will ask the user to input a country name and it will return the key and the value of that key or the capita income. The issue i am having is that i have to search the dictionary to find the input and if it matches the key then it will print that and the capita income. Im not 100 percent sure what to use if i should use a for function or if my code is correct at the end.
def main():
import requests
webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile) #connects to the file and gest a response object
with open("capital.txt",'wb') as f:
f.write(data.content) #write the data out to a file – wb used since thecontent from the response object is returned as abinary object.
f.close()
countryName = {}
with open('capital.txt','r') as infile:
for line in infile:
num,*key,value = line.split()
key = ' '.join(key)
countryName[key] = value.upper()
userInput = input("Enter a country name: ")
userInput.upper()
while(userInput != 'stop'):
#for loop to see if key is in dictionary
if userInput in countryName:
#if(userInput == countryName[key]):
print("The per capita income in",key, "is",countryName[key])
userInput = input("Enter a country name: ")
main()
while(userInput != 'stop'):
#for loop to see if key is in dictionary
if userInput in countryName:
#if(userInput == countryName[key]):
print("The per capita income in",key, "is",countryName[key])
userInput = input("Enter a country name: ")
main()
Here is where the issue is, tying to find the if the userInput is the same as the country name key . What would i have to do search the dictionary to match the key to the input, or if there is any uneccesary things in my code.
Update 2
Ah, there was a small issue when comparing the keys. Actually, you were doing upper() on the value (a number) which doesn't make sense.
Have a look at this update:
import requests
webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile)
with open("capital.txt",'wb') as f:
f.write(data.content)
countryName = {}
with open('capital.txt','r') as infile:
for line in infile:
num, *key, value = line.split()
key = ' '.join(key)
countryName[key.upper()] = value #key.upper() instead of value.upper()
userInput = input("Enter a country name: ").upper()
counter = 0
while not userInput == "STOP": #'STOP' because it's uppercase
if userInput in countryName:
print("The per capita income in", userInput, "is", countryName[userInput])
userInput = input("Enter a country name: ").upper()
counter += 1
if counter >= len(countryName): #It couldn't find the country
userInput = input("Not found. Enter a new country: ").upper()
counter = 0 #Let's try again
And a small improvement: the counter will prevent the infinite loop when the user input doesn't satisfy the if userInput in countryName and it's not "stop". Besides that, the "stop" condition must be "STOP", once it'll be in upper case.
Hope it helps
Update
As pointed out by #Barmar, another possibility is:
countryName = {
"countryA": "valueA",
"countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
if userInput in countryName:
print ("The country is", userInput, "and the value is", countryName[userInput])
Just a good advice: I think the file part has nothing to do with your question itself, so, next time try to reduce your problem to, you know, something more direct :)
Anyway, you can loop over the keys of countryName and then compare with the user input. In other words:
countryName = {
"countryA": "valueA",
"countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
for key in countryName.keys():
if userInput == key: #Got it
print ("The country is", key, "and the value is", countryName[key])
Hope it helps