Writing to a file using a users input in Python - python

I'm trying to write a user input to a word file for my troubleshooting system. However it doesn't write to the file and ends the code. I am trying to make it so that if the user inputs 'no' twice, then it should follow the following code:
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)
Instead the code ends.
Here's the code:
count = 0
while count != 2:
a = input("Is your phone broken?")
if a == "no":
count = count + 1
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)
But the code doesn't open the file and write to the file, the program just ends after the user inputs no. I don't understand what I'm doing wrong? Could anyone help me please.

If you are using Python 2.x, use raw_input.
count = 0
while count != 2:
a = raw_input("Is your phone broken?")
print a
if a == "no":
count = count + 1
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)

Related

Python code randomly stops, why? (This is for a quiz game)

The following code randomly stops where mentioned in the code.
def playSaved(choiceSaved):
y = open(choiceSaved,'r')
for line in y.readlines():
qna = line.split(" : ")
randQues.append(qna[0])
randAns.append(qna[1])
print("Processing game.....")
time.sleep(2)
savedChoice = input("\nOk! Are you ready to play? (Y/N) ")
# the code stops here, after getting the input
if savedChoice.lower() == 'y':
for num in range(len(y.readlines())):
count = 1
if "?" in randQues[num]:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
else:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
if ansForSaved == randAns[num]:
print("Correct!")
else:
print("Wrong!")
I tried looking online, but didn't find anything. I figured i could ask here
it reads the line from a text file and the first part is a question the second part is the answer i want to check if the answer input by user matches the answer based on the txt file
some sample data:
name : jd
country : finland
age : 23
colour: red
The for loop:
for num in range(len(y.readlines()))
...will never be entered because the file contents have already been consumed.
Change to:
for num in range(len(randQues))

I'm Having Trouble checking two values are equal in python

finishgame = "n"
counter = 0
#the song randomizer
num = random.randint(0,50)
f = open("songs.txt","r")
lines = f.readlines()
#first letter only system
song = str(lines[num])
firstl = song[0]
print(firstl)
#the artist generator
g = open("artists.txt","r")
line = g.readlines()
print(line[num])
#guess system
while finishgame == "n":
guess = str(input("Enter your guess"))
if guess == song:
counter = counter+5
print("Correct!")
finishgame = "y"
elif counter == 2:
print("Out of guesses, sorry :(")
print("The Correct Answer was:",song)
finishgame = "y"
else:
counter = counter+1
print("Try Again")
First time asking so apologizes for any errors. I have create a song guessing game where it takes a song from an external file, and displays the first letter of the title. It then takes the artist from a separate file (where it is in the same line as the song in the other file) and displays that too. Then you should guess the song. However, my code is having trouble recognizing when a 'guess' is correct, please can anyone tell me why? I've tried using different methods of identification such as the id() function but so far have not got any results. I'm probably missing something simple but any help would be much appreciated.

Python password system with lock after certain number of attempts

So I am trying to create a password system in Python, whereby after a certain number of incorrect attempts, the user will be blocked from accessing it for, say, 5 minutes. I am currently unsure how the values of the variables can be kept after rerunning the same file and then used in this manner. Could someone help me with this, as I am currently still new to Python?
Update:
After experimenting for a while with the code Jonas Wolff provided me I finalised my code to the following:
def password():
count = 0
currentTime = float(time.time())
passwordList = ["something", "password", "qwerty", "m42?Cd", "no"]
passwordNum = random.randint(0, 4)
password = passwordList[passwordNum]
with open("password.txt", "r") as file:
check = file.readline()
initialTime = file.readline()
if initialTime=="":
initialTime==0
if int(check)==1 and (currentTime-float(initialTime))<300:
print("You are still locked")
print("Please try again in", int(300-(currentTime-float(initialTime))), "seconds.")
quit()
print("The randomised password is No.", passwordNum+1) #Prints a string to let the user know which password was randomly selected
while count<5:
inp = input("Enter the Password: ")
if inp==password:
print("Access Granted")
print()
f = open("password.txt", "w")
f.write("0\n0")
f.close()
select()
elif (count+1)==5:
print("You have been locked")
print("Please try again in 5 minutes")
f = open("password.txt", "w")
f.write("1\n")
f.write(str(currentTime))
f.close()
quit()
else:
count+=1
print("Incorrect Password")
print("You have", 5-count, "tries left.")
continue
Thanks a lot for the help you have provided and the patience with which you answered my questions.
import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line
import time
pswd = "something"
count = 0
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
numa = file_info.count("1")
count = numa
while True:
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
tima = file.readline()
inp = input("What is the password:")
if inp == pswd:
if tima == "":
tima = "0" # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed
if str(file_info[:5]) != "11111" or time.time() > float(tima):
YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program.
f = open("PhysxInit.txt", "w")
f.write("\n")
f.close()
break
else:
count += 1
f = open("PhysxInit.txt", "w")
f.write(("1"*count)+"\n"+str(tima))
if count == 5:
f.write(str(time.time()+60*5))
f.close()
#f = open("PhysxInit.txt", "w")
#f.write("\n")
#f.close()
does this work?
just make sure you have a text file called PhysxInit.txt
after running the program, and having guessed wrong a few times my txt file look like this.
11111
1536328469.9134998
it should look something like mine though the numbers may be diffrent.
To read a specific line as you requested you need to do:
with open("PhysxInit.txt", "r") as f:
for w,i in enumerate(f):
if w == #the number line you want:
# i is now the the line you want, this saves memory space if you open a big file

Quiz from external text file Python

I am trying to create a quiz where I have questions and answers from an external text file to import into Python so that the user can input a selection.
The problem is that my code only prints "Correct" at the end of the quiz once, and doesn't say after each question answered if the user got the question correct or incorrect.
The first column (detail[0]) is where the question is and the correct answer is in the fourth column (detail[4]))
Thanks
Here is what is in the text file:
What is 1+1,1,2,2
What is 2+2,4,2,4
Here is the source code below:
def quiz():
file = open("quiz.txt","r")
right = False
for line in file:
detail = line.split(",")
print(detail[0])
select = input("Select 1 or 2: ")
if select == detail[3]:
right = True
break
if right == True:
print("Correct")
else:
print("Incorrect")
Just modify the main for-loop to print the result there and then:
for line in file:
detail = line.split(",")
print(detail[0])
select = input("Select 1 or 2: ")
if select == detail[3]:
print("correct!")
else:
print("incorrect :(")

How to make data entered by user to appear below headers

This is my code for entering student details. Once the user has entered the details and inputs yes, the details are exported to StudentDetails.csv (Microsoft Excel) where it should go below the headers but ends up going somewhere else.
def EnterStudent():
uchoice_loop = False
ask_loop = False
while uchoice_loop == False:
surname = raw_input("What is the surname?")
forename = raw_input("What is the forname?")
date = raw_input("What is the date of birth? {Put it in the format D/M/Y}")
home_address = raw_input("What is the home address?")
home_phone = raw_input("What is the home phone?")
gender = raw_input("What is their gender?")
tutor_group = raw_input("What is their tutor group?")
email = (forename.lower() + surname.lower() + ("#school.com"))
print(surname+" "+forename+" "+date+" "+home_address+" "+home_phone+" "+gender+" "+tutor_group+" "+email)
ask = raw_input("Are these details correct?"+"\n"+"Press b to go back, or yes to add entered data on your student.").lower()
if ask == "yes":
f = open("StudentDetails.csv","rt")
lines = f.readlines()
f.close()
lines.append(surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email+"\n")
f = open("StudentDetails.csv", "w")
f.writelines(lines)
f.close()
uchoice_loop = True
printMenu()
elif ask == "b":
uchoice_loop = False
else:
print("Plesase enter 'b' to go back or 'yes' to continue")
This is my csv file.
enter image description here
There's a few things you can do to make this work. You dont need to open the StudentDetails.csv and read all of the lines. Instead you can make a lines string variable and append it the the StudentDetails.csv like in the example below
#f = open("StudentDetails.csv","rt")
#lines = f.readlines()
#f.close()
lines = surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email
# the "a" appends the lines variable to the csv file instead of writing over it like the "w" does
f = open("StudentDetails.csv", "a")
f.writelines(lines)
f.close()
uchoice_loop = True
Eric is right in that you best open the file in append-mode (see https://docs.python.org/3.6/library/functions.html#open) instead of cumbersomely reading and rewriting your file over and over again.
I want to add to this that you probably will enjoy using the standard library's csv module as well (see https://docs.python.org/3.6/library/csv.html), especially if you want to use your output file in Excel afterwards.
Then, I'd also advise you to not use variables for while loop conditionals, but learning about the continue and break statements. If you want to break out of the outer loop in the example, research try, except and raise.
Finally, unless you really have to use Python 2.x, I recommend you to start using Python 3. The code below is written in Python 3 and will not work in Python 2.
#!/usr/bin/env python
# -*- codig: utf-8 -*-
import csv
def enterStudent():
b_or_yes = 'Press b to go back, or yes to save the entered data: '
while True:
surname = input('What is the surname? ')
forename = input('What is the first name? ')
date = input(
'What is the date of birth? {Put it in the format D/M/Y} ')
home_address = input('What is the home address? ')
home_phone = input('What is the home phone? ')
gender = input('What is the gender? ')
tutor_group = input('What is the tutor group? ')
email = forename.lower() + surname.lower() + '#school.com'
studentdata = (
surname,
forename,
date,
home_address,
home_phone,
gender,
tutor_group,
email)
print(studentdata)
while True:
reply = input('Are these details correct?\n' + b_or_yes).lower()
if reply == 'yes':
with open('studentdetails.csv', 'a', newline='') as csvfile:
studentwriter = csv.writer(csvfile, dialect='excel')
studentwriter.writerow(studentdata)
break
elif reply == 'b':
break
if __name__ == '__main__':
enterStudent()
Best of luck!

Categories

Resources