a program to store information about a single user. The program should include a function that asks the user for their name, age, course, and home town and stores this in memory. It should also have a function that will write the information entered in a file. Use exception handling to protect the data entry and the file operations
really stuck on this any help would be great
name=raw_input("Enter name :")
surname=raw_input("Enter surname :")
n=None
while n is None:
age=raw_input("Enter age :")
try:
n = int(age)
except ValueError:
print "Not a number."
course=raw_input("Enter course :")
hometown=raw_input("Enter hometown :")
with open("workfile","w") as f:
f.write('Name : ' + name + '\n')
f.write('Surname : ' + surname + '\n')
f.write('Age : ' + str(age) + '\n')
f.write('Course : ' + course + '\n')
f.write('Hometown : ' + hometown + '\n')
f.close()
for exception handling in file I/O see What is a good way to handle exceptions when trying to read a file in python?
Related
Here is my code:
name = ' '
Nameval = name("Enter the victims IP address: ")
print("Hello, " + name)
I want this code to take the input from Nameval, store it in the "name" variable and then print the name variable. However, it wont work. How can I do this?
You need to use input([prompt]).
name = input("Enter the victims IP address: ")
print("Hello, " + name)
Your code is wrong. You are not asking for an input, try this.
name = input('Enter IP address: ')
print(f'Hello {name}')
F string are better than concatination
I'm learning Python and I'm wondering how you would insert a name into a list and for it to be held in that variable so the script can identify if it's seen you before.
Any help would be much appreciated
# Default People Already In List at program start
list = ['Bob','Jim',]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again" + Name)
else:
list.insert(0, Name)
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(list)
Your should rename your variables - here a short correction of your code, although it is looking good already! I changed the insert to append as well!
But it will obviously forget since the list is always initialized with Bob and Jim in it, and then you ask for the name - if is not Bob or Jim, it is new and therefore appended. But then your program ends, so when you start it new, your list is only populated with Bob & Jim again. You could put the whole construct in a "while True" construct to make the same question multiple times until you dont want to anymore!
EDIT: included the while (you can enter it numerous times if you just press "Enter" for the question! and put the list in the beginning, so it will not be initialized every time you run a new name! and important: if you see someone for the first time, include the print in the else-clause, otherwise it will be printed everytime, even if you saw the name before!
name_list = ['Bob','Jim']
while True:
print("Hello, What\'s your name? ")
input_name = input("Enter your Name: ")
if str(input_name) in name_list:
print("Nice to meet you again, " + input_name)
else:
name_list.append(input_name)
print("Hi " + input_name + ", Nice too meet you for the first time.")
# Troubleshoot
print(name_list)
if str(input("Another name? ")) == '':
continue
else:
break
This is what I did. This works with a CSV file.
# Load from file
list = []
listfile = open('list.csv', 'r+')
for name in listfile:
list.append(name[:-1])
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again " + Name)
else:
print("Hi " + Name + ", Nice too meet you for the first time.")
listfile.write(Name + "\n") #adding to file
# Troubleshoot
print(list)
This will store it to a file, also its not a good practice to use built in functions and utilities as variable names. so I modified the name as lists
try:
with open("listofnames.txt","r") as fd:
lists=eval(fd.read())
except:
lists=[['Bob','Jim',]]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in lists:
print("Nice to meet you again", Name)
else:
lists.insert(0, Name)
with open("listofnames.txt","w") as f:
f.write(str(lists))
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(lists)
I've got a simple question but I can't really find a right solution for that.
I have a csv file that contains students' names and subjects for which they are registered:
name,subject1,subject2,subject3
Student1,MN1,MN2,MN3
Student2,BN1,BN2,BN3
Student3,MN4,MN5,MN6
Student needs to enter his name and subject name in order to check whether he is registered or not for this subject
My code:
import csv
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
with open('students.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (row['name'] == Name and row['subject1'] == Subject or
row['subject2'] == Subject or row['subject3'] == Subject):
print ("You are registered. It won't take long to run your VM")
else:
print ("You are not registered")
My problem is that it gives multiple outputs to me
Output:
Please provide your name: Student3
Please provide your Subject: MN4
You are not registered
You are not registered
You are registered. It won't take long to run your VM
Obviously, it should be just:
You are registered. It won't take long to run your VM
Could you please help me to solve this problem?
Thank you
Note that for loops in Python have an optional else clause that will execute when the loop ends without a break statement...
Your code prints each iteration of the loop. What you want is to print only at the end of the loop...
with open('students.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (row['name'] == Name and (row['subject1'] == Subject or row['subject2'] == Subject or row['subject3'] == Subject)):
print("You are registered. It won't take long to run your VM")
break
else:
print("You are not registered")
I believe a dictionary will work best for you:
import csv
data = {i[0]:i[1:] for i in csv.reader(open('filename.csv'))}
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
if Subject in data[Name]:
print("you are registered")
else:
print("you are not registered")
A dataframe will be a good structure to store you csv file. Please give it a read here, anyway coming to your code. Please refer the below code.
Please install pandas and numpy for this
pip install pandas
pip install numpy
Code:
import pandas as pd
import numpy as np
df = pd.read_csv("testing.csv")
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
query = '(name == '+ '\'' + Name + '\'' + ') and (subject1 == '+ '\'' \
+ Subject + '\'' + ' or subject2 == ' + '\'' + Subject + '\'' \
+ ' or subject2 == ' + '\'' + Subject + '\')'
if df.query(query).empty:
print ("You are registered. It won't take long to run your VM")
else:
print ("You are not registered")
Reference:
pandas query
The below def is working perfectly in cmd, but when writing to the file, it is only writing the second data.write statement. The first statement is definitely working, it is just not writing. Given the code is identical i can't figure out for the life of me what is wrong.
def follower_count(list1):
for name in list1:
name = '#' + name
try:
user = api.get_user(name)
if user.followers_count < 5000:
print ""
print "FAILED TEST"
print name
print user.followers_count
data.write(name + ": " + user.followers_count + "\n")
else:
print ""
print name
print user.followers_count
except:
print ""
print "Error grabbing " + name
data.write("Error Grabbing: " + name + "\n")
return()
data.write(name + ": " + user.followers_count + "\n")
This line will crash with TypeError: Can't convert 'int' object to str implicitly if user.followers_count is an integer.
Try using str.format to interpolate your strings.
data.write("{}: {}\n".format(name, user.followers_count))
Furthermore, you're making debugging much harder for yourself by not displaying any diagnostic information in your except. You know that an error occurred, but don't know anything about that error specifically. At the very least, you could do:
except Exception as e:
print ""
print "Error grabbing " + name
data.write("Error Grabbing: " + name + "\n")
data.write(e.message + "\n")
Which will at least tell you what the error message is.
I am making a Recipe book, at the moment I have the ability to create a recipe, but now I am starting to build the module of searching and displaying stored recipes.
At the moment I have a .txt document with the contents along the lines of:
Williams Special Recipe
Ingredients:
bread: 120 grams
butter: 1234 grams
Recipe Serves: 12
I then ask the user how many they are serving and based on how many the recipe serves, I need to multiply all the ingredients quantity by that number. I then need to print that off with the full recipe again.
I was wondering how I would go about achieving this result, not asking specifically for a coded response as an answer, but I would greatly appreciate how I would approach this task and any specific functions required.
I have also included my code so far, I appreciate the fact it is incredibly un-organised at the moment, and probably hard to understand, but I included it for any reference.
(I have also created a .txt file of all the created recipes which will be implemented later on as a way of displaying to the user all recipes, but at the moment it is just set up for searching.)
#Recipe Task
import os.path
def file_(n):
if n == "listR" :
list_f = open("list_recipes.txt", "a+")
list_f.write(new_name + "\n")
if n == "oar": #open append read
f=open(new_name + ".txt","a+")
elif n == "c": #closes file
f.close()
def print_line(x): #ease of printing multiple lines to break up text
for c in range(x):
print ""
def new_ingredients(): #adding new ingredients
f.write("Ingredients:" + "\n" + "\n")
fin_ingredient = False
while fin_ingredient != True :
input_ingredient = raw_input("New ingredient:" + "\n").lower()
split_ingred = input_ingredient.split()
if input_ingredient == "stop": #stops asking questions when user types 'stop'
fin_ingredient = True
else :
f.write(split_ingred[0] + ":" + " " + split_ingred[1] + " " + split_ingred[2] + "\n")
def search_recipe(n): #searching for recipes
n = n + ".txt"
if os.path.isfile('/Users/wjpreston/Desktop/' + n) == True :
print "Recipe Found..."
found_recipe = open(n)
print found_recipe.read()
append_serving = raw_input("Would you like to change the number of people you are serving?" + "\n").lower()
if append_serving == "yes" :
appended_serving = input("How many would you like to serve?" + "\n")
with open(n) as f: #here is my issue - not sure where to go with this!!
list_recipe = f.readlines()
found_recipe.close()
else :
print "fail"
else:
print "No existing recipes under that name have been found."
print "Welcome to your Recipe Book"
print_line(3)
recipe_phase = raw_input("Are you 'creating' a recipe or 'viewing' an existing one?" + "\n").lower()
if recipe_phase == "creating":
new_name = raw_input("Name of Recipe: " + "\n")
file_("listR")
file_("oar")
f.write("------------" + "\n" + new_name + "\n" + "\n")
print "Ingrediants required in the format 'ingredient quantity unit' - type 'stop' to end process"
new_ingredients()
new_num = input("Number serving: ")
f.write("\n" + "Recipe Serves: " + str(new_num) + "\n" "\n" + "\n")
file_("c")
elif recipe_phase == "viewing":
search = raw_input("Search for recipe: ")
search_recipe(search)
I'm not the specialist in processing strings, but I'd approach your problem following way:
Save each ingredient on a new line.
Split the loaded string by "\n".
Then process the list with some for-loops while creating two dicts, one for the actual data
e.g. {"bread": 4, "butter": 7}
and one for the types of each ingredient:
e.g. {"bread": grams, "butter": grams}
The you should also save how many serves the recipe is written for, and maybe the order of the ingredients (dicts get stored in a random order):
e.g. ["bread", "butter"]
After that, you can ask your costumer how many serves he has and then finally calculate and print the final results.
for ing in ing_order:
print ing+":", ing_amount[ing]*requested_serves/default_seves, ing_types[ing]
...hopyfully you still have enough challange, and hopefully I understood your question correctly.