simple notepad data input program needs fixing - if-statement

Hi I recently had this program running fine but after fiddling round with it now it doesn't work because when i run it in the shell when the program asks "do you want to enter a user" and I type "yes" it doesn't ask for the user to input he/shes name, DOB in form 00/00/0000, run time, postcode. It just prints "do you want to see your records?" If anyone could help quick it would be much appreciated p.s im really new so I dont 100% understand some things at the moment.
def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)

def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)
Try this

Related

Print line if any of these words are matched

I have a text file with 1000+ lines, each one representing a news article about a topic that I'm researching. Several hundred lines/articles in this dataset are not about the topic, however, and I need to remove these.
I've used grep to remove many of them (grep -vwE "(wordA|wordB)" test8.txt > test9.txt), but I now need to go through the rest manually.
I have a working code that finds all lines that do not contain a certain word, prints this line to me, and asks if it should be removed or not. It works well, but I'd like to include several other words. E.g. let's say my research topic is meat eating trends. I hope to write a script that prints lines that do not contain 'chicken' or 'pork' or 'beef', so I can manually verify if the lines/articles are about the relevant topic.
I know I can do this with elif, but I wonder if there is a better and simpler way? E.g. I tried if "chicken" or "beef" not in line: but it did not work.
Here's the code I have:
orgfile = 'text9.txt'
newfile = 'test10.txt'
newFile = open(newfile, 'wb')
with open("test9.txt") as f:
for num, line in enumerate(f, 1):
if "chicken" not in line:
print "{} {}".format(line.split(',')[0], num)
testVar = raw_input("1 = delete, enter = skip.")
testVar = testVar.replace('', '0')
testVar = int(testVar)
if testVar == 10:
print ''
os.linesep
else:
f = open(newfile,'ab')
f.write(line)
f.close()
else:
f = open(newfile,'ab')
f.write(line)
f.close()
Edit: I tried Pieter's answer to this question but it does not work here, presumeably because I am not working with integers.
you can use any or all and a generator. For example
>>> key_word={"chicken","beef"}
>>> test_texts=["the price of beef is too high", "the chicken farm now open","tomorrow there is a lunar eclipse","bla"]
>>> for title in test_texts:
if any(key in title for key in key_words):
print title
the price of beef is too high
the chicken farm now open
>>>
>>> for title in test_texts:
if not any(key in title for key in key_words):
print title
tomorrow there is a lunar eclipse
bla
>>>

Python input/strings

(Python 2.7.10) So i am a beginner in python, just started learning about a week ago. I need some help with writing the code commented on lines 3 and 5.If the user enters a word instead of a numerical value then I need the program to tell them error and to restart. I commented the program to make it easier to understand. The program works just fine otherwise. Thank you.
## Ask user for age
age = input("Please enter your age.(numerical value)")
## If input is not a numerical value then tell the user "Error. Enter a numerical value"
## Restart program to let the user try again.
## If age is less than 18 then tell them they are too young
if age < 18:
print (" Access denied. Sorry, you are not old enough.")
## If the user is 18 then grant them access
elif age == 18:
print ("Acess granted. You are just old enough to use this program!")
## If user is any age above 18 then grant them access
else:
print ("Access granted.")
his is a way to make sure you get something that can be interpreted as integer from the user:
while True:
try:
# in python 3:
# age = int(input('Please enter your age.(numerical value)'))
# in python 2.7
age = int(raw_input('Please enter your age.(numerical value)'))
break
except ValueError:
print('that was not an integer; try again...')
the idea is to try to cast the string entered by the user to an integer and ask again as long as that fails. if it checks out, break from the (infinite) loop.
Change your age input part to this:
#keep asking for age until you get a numerical value
while True:
try:
age=int(raw_input("Please enter your age.(numerical value)"))
break
except ValueError:
print "Error. Enter a numerical value"

Why won't my program work in python?

Hi I am 11 yrs old and I am teaching myself how to code. I set myself a task to make a times table quiz that asks 10 questions and inputs random numbers. However, my code is not working and I do not know why. I am using python 2.7.5. This is my code:
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
import random
print random.randint(1,10)
print ("times")
import random
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"
I can not spot why it is not working but I have not put a for loop in yet so it only asks 1 question. When I run it else is highlighted in red but I do not know why.
Python works without brackets. It is replaced by "spaces or tabs". And we import ONCE, the beginning.
This should work
import random
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
print random.randint(1,10)
print ("times")
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"

How would you create a option to retry in Python?

I'm a little confused on how to allow the user to retry entering something in Python. I created an example code bellow. I want it so if the user types a invalid answer other than 1 or 2 it allows them to try again.
import sys
def start():
print "Hello whats your name?"
username = raw_input("> ")
print "Okay, welcome to the game %s" % username
print "Do you want to hear the background of the game?"
print "1. Yes"
print "2. No"
background = raw_input("> ")
if background == "1":
print "Background goes here."
elif background == "2":
print "Background skipped"
start()
How would I incorporate a try again option into this example? Thanks!
Use a while loop:
def start():
print "Hello whats your name?"
username = raw_input("> ")
print "Okay, welcome to the game %s" % username
print "Do you want to hear the background of the game?"
print "1. Yes"
print "2. No"
while True: # Repeat the following block of code infinitely
background = raw_input("> ")
if background == "1":
print "Background goes here."
break # Break out of loop if we get valid input
elif background == "2":
print "Background skipped"
break # Break out of loop if we get valid input
else:
print "Invalid input. Please enter either '1' or '2'" # From here, program jumps back to the beginning of the loop
start()

TypeError: expected a character buffer object (trying to write to a text file)

I am trying to code a simple program that writes the output of a function to a text file, and I had it working, but today I tried to run it and it gives me this error at line 54: TypeError: expected a character buffer object.
Here is that line:
f.write(spotify.getCurrentTrack())
Also, here is the rest of the code:
from pytify import Spotify
spotify = Spotify()
import time
var2exit = 1
print "This program was created by Drew Halverson. Do not claim as your own work."
time.sleep(2)
print "This program could not have been created without the help of pytify."
time.sleep(2)
print "Also, this program is not affiliated with Spotify at all and is not an official app."
time.sleep(2)
print "For information on how to use this program and what its use is, check readme.txt"
yes = set(["yes", "y", "YES"])
no = set(["no", "n", "NO"])
r = open("readme.txt", "r")
print "Would you like to read the readme now (type yes or no)?"
choice = raw_input()
if choice in yes: print r.read()
print " "
time.sleep(2)
if choice in no: print "Hi! I will now be checking what song is playing on spotify."
time.sleep(2)
print "Make sure spotify is playing (Only the downloaded application will work. The program is not compatible with the web player version of Spotify."
time.sleep(2)
print " "
time.sleep(1)
print "Have you downloaded Spotify on this computer already? Type yes or no..."
choice2 = raw_input()
if choice2 in yes: print "Alright! Let's go!"
if choice2 in no: var2exit = 2
if var2exit == 2:
print "Go install Spotify first, then try again."
time.sleep(5)
print "Goodbye!"
time.sleep(2)
sys.exit()
var = 1
while var == 1 :
spotify.getCurrentTrack()
spotify.getCurrentArtist()
f = open("current_track.txt", "w")
g = open("current_artist.txt", "w")
f.write(spotify.getCurrentTrack())
g.write(spotify.getCurrentArtist())
print "The current Track is:"
print spotify.getCurrentTrack()
print "The current Artist is:"
print spotify.getCurrentArtist()
time.sleep(10)
print" "
print "Checking again..."
I know there are similar questions to this but none that I found exactly answered my problem. Thanks.