I am trying to make a quiz but my answers are in an external file, so but everytime I run it with my correct answers they say they are incorrect.
Here is my code:
randNum = int(random.randint(0, 4))
song = open("songList.csv","rt")
with open("songList.csv", "rt") as f:
songn = str(song.readlines()[randNum])
reader= csv.reader(f)
for row in reader:
print (songn[0])
guess = input("What is the song called?")
score = 0
correct_guess = False
while True:
if guess == songn:
correct_guess = True
break
score += 1
if score>=total:
break
song_guess = input("Incorrect! Try again:\n> ")
if correct_guess:
print("Answer correct!")
else:
print("game over")
As pointed out in the comments, you have trailing newline characters in one of the strings. Hence they aren't equal.
However I wouldn't just remove the newline. It is always good practice, if your logic allows it, to normalize strings before you test for equality. There are lots of things you can do to normalize:
def normalize(string):
string = string.strip() # Remove any leading or trailing whitespaces
string = string.lower() # Make all letters lowercase
string = " ".join(string.split()) # If the user hit spacebar twice, for example, will remove the double space. Note can have side effects.
return string
Then check
if normalize(string1) == normalize(string2):
do_something()
In fact, if you are dealing with user input, even this might not be sufficient. For example, if the user makes a typo, it won't match.
So I recommend also looking at the fuzzywuzzy library
from fuzzywuzzy import fuzz
def similar(string1, string2):
ratio = fuzz.ratio(string1, string2)
return ratio >= 85 # number between 0 and 100. Higher means fewer differences are allowed
Fuzzywuzzy is very powerful and easy to use. For more info: https://github.com/seatgeek/fuzzywuzzy
Related
Start by setting t to be the local time 1, 500, 000, 000 seconds from the start of January 1, 1970 UTC:
import time
t = time.localtime(1500000000)
Construct the next strings by using the string time format function strftime(): (a) 'Thursday, July 13 2017'
(b) '09:40 PM Central Daylight Time on 07/13/2017'
(c) 'I will meet you on Thu July 13 at 09:40 PM.'
A couple things, Stack Overflow is not the place for code reviews, for that: try this.
Regardless, you have indentation problems, Python is based off of indents, you need to have the code in your function indented one ahead of your def, like so:
def filesStringSearch():
infile = open('example.txt')
a = input('Search for a word: ')
result = infile.read().find(a)
#result = a.find:
#for a in infile:
if a.find:
print("True")
elif a < 3:
print("-1")
else:
print("False")
return
Second, you're not taking an input with the function, and hard-coding the file to open; this is a simple fix however,
def filesStringSearch(filename):
infile = open(filename)
Third, you're not going to accomplish your goal with your if statements, if the length of the input is less than 3, you shouldn't even try to search for anything, so you need to reorder and change your boolean expressions a bit; to this:
if len(a) < 3:
print("-1")
elif a.find:
print("True")
else:
print("False")
Finally, a.find will not work, rather you can check to see the value of result, so you can replace elif: a.find with:
elif result != -1:
print("True")
Since result will be -1 if it cannot find anything.
Also, the return is useless at the end.
According to your questions the right implementation is:
def filesStringSearch(filename, pattern):
with open(filename, 'r') as f:
text = f.read()
if len(pattern) >= 3:
return text.find(pattern) > -1 or False
else:
return -1
filename = 'example.txt'
pattern_to_find = input('Search for a word: ')
out = filesStringSearch(filename, pattern_to_find)
print(out)
If you are asked to write a function that accepts two arguments, then your function must accept two arguments as here:
def filesStringSearch(filename, pattern):
Then you must read the file, I did it using with statement. with statement will close our file for us, so you don't have to do it manually (and yes, you forgot to close an opened file, it is not a big problem for now, but avoid such things in big projects). You can read more about with statement there: Reading and writing files
What about find method. It is a string method, that will return index of found substring in your string, for instance my_string.find('h') is going to return the index of first substring (which is 'h') in my_string string. If find method can't find your substring it will return -1, that's why we do this:
return text.find(pattern) > -1 or False
As if we will find our pattern in text, then the index certainly is going to be greater that -1. Otherwise we return False or -1 if pattern string's length is less than 3, according to your question
And at the end we take input from user and pass that input to our function with the name of file example.txt. We store the return value of our function in out variable and then print it
I have a text file with 2000 words, one word on each line. I'm trying to create a code that prints out two random words from the textfile on the same line every 10 seconds. The beginning part of my text file is shown below:
slip
melt
true
therapeutic
scarce
visitor
wild
tickle
.
.
.
The code that I've written is:
from time import sleep
import random
my_file = open("words.txt", "r")
i = 1
while i > 0:
number_1 = random.randint(0, 2000)
number_2 = random.randint(0, 2000)
word_1 = my_file.readline(number_1)
word_2 = my_file.readline(number_2)
print(word_1.rstrip() + " " + word_2.rstrip())
i += 1
sleep(10)
When I execute the code instead of printing two random words it starts printing all the words in order from the top of the text. I'm not sure why this is happening since number_1 and number_2 are inside the loop so every time two words print number_1 and number_2 should be changed to two other random numbers. I don't think replacing number_1 and number_2 outside of the loop will work either since they'll be fixed to two values and the code will just keep on printing the same two words. Does anyone know what I can do to fix the code?
readline() doesn't take any parameters and just returns the next line in your file input*. Instead, try to create a list using readlines(), then choose randomly from that list. So here, you'd make word_list = my_file.readlines(), then choose random elements from word_list.
*Correction: readline() does take a parameter of the number of bytes to read. The documentation for the function doesn't seem to explicitly state this. Thanks E. Ducateme!
my_file.readline(number_1) does not do what you want. The argument for readline is the max size in bytes of a line you can read rather than the position of the line in the file.
As the other answer mentioned, a better approach is to first read the lines into a list and then randomly select words from it:
from time import sleep
import random
my_file = open("words.txt", "r")
words = my_file.readlines()
i = 1
while i > 0:
number_1 = random.randint(0, 2000)
number_2 = random.randint(0, 2000)
word_1 = words[number_1]
word_2 = words[number_2]
print(word_1.rstrip() + " " + word_2.rstrip())
i += 1
sleep(10)
Okay, so I've been doing a lot of research and I couldn't find any answers so I came here to ask for some help.
My problem that I have encountered is I am having trouble taking a variable, then in the background of my code converting each individual string of that variable back to its ascii form and manipulating it using math, such as +, -, * and /. Here is my code..
Note: I had one theory, which is using a for loop to say for each character in this variable, do... blah blah. Here's my code anyways.
import random
import sys
import time
invalid_input = True
def start():
print("Welcome to the Encryption / Decryption Program!")
menuAnswer = input("Please select the number corresponding to the option you would like (1 - 3)\n---------------------------------\n[1] Encrypt\n[2] Decrypt\n[3] Exit the program\n---------------------------------\n")
if menuAnswer == '1':
print("You have chosen to Encrypt!")
invalid_input = False
message = open("sample.txt","r")
msgName = input("What is the name of the text document you would like to Encrypt?\n")
msgName = msgName.upper()
if msgName == 'SAMPLE':
key = '' #This variable will have the encryption key stored inside of it.
for i in range(0,8):
random_number = (random.randint(33,162)) #Generate a random ascii number from the range 33 to 162
key +=str(chr(random_number)) #Convert and store this ascii number as a character to the variable 'Key'
print(key)
print("Remember this key, as you will need it to decrypt your file!")
#\\ Offset //# #Finding the offset, must be able to convert each individual character of the key variable and return it to its usual form to manipulate using math.
else:
print("Invalid Filename")
elif menuAnswer == '2':
print("You have chosen to Decrypt!")
invalid_input = False
elif menuAnswer == '3':
print("You have chosen to exit!")
invalid_input = False
time.sleep(1)
print("Exiting...")
time.sleep(1.5)
exit()
else:
print("Invalid Input, Please try again!")
while invalid_input:
start()
Sorry if this question was difficult to understand, I am really confused myself and have been stuck on this for a week straight.
If I understand correctly you want to convert each character of your string to its ascii number and then do some sort of math operation on it and then convert it back to a string which you can do using ord() like so
s = 'Sample'
tmp = ''
for i in s:
tmp += chr(ord(i)+1)
print tmp
Tbnqmf
Although with the code you have you don't need to convert it to a string and then back to characters to manipulate it you can just manipulate it as soon as you pick a random number like so
import random
def start():
key = ''
for i in range(0,8):
random_number = (random.randint(33,162))
key +=chr(random_number+1)
print(key)
start()
Note you need to be careful when manipulating your characters since you could manipulate it to a number that is not an ascii character
I am writing a program that will allow a user to decode a word (an encoded football team) that has been imported from a text file. Another text file contains the decoded football team. The user will be allowed to take a guess at decoding the word and selecting letters to replace in the word until he guesses them all correctly (then game over).
Thanks to some help I received here I was able to adapt some code that allowed me to record each character swap the user made by appending both the old and new letters through enumeration to an indices list.
I need the user to be able to choose to delete a previous character swap and that is where I am falling down at the minute. I know how to undo the previous change (thanks to some help here) but I want the user to be able to see the previous swaps listed in one go and then choose a letter to restore to its original place in the decoded letter. Here is the main function of the code so far:
def play():
global encoded
global plaintext
x = 40
for i in range(x):#give the user 40 goes maxiumum
print("\nThe encoded team is {0}\n".format("".join(encoded)))
choose = input("What character would you like to replace?")
indices = []
for i, j in enumerate(encoded):
if j == choose:
indices.append(i)
replace = input("What character would you like to replace it with")
for i in indices:
encoded[i] = replace
changes.append((choose, replace, indices))
for choose, replace, indices in changes:
print("Replaced '{0}' with '{1}'".format(choose, replace))
undo = input("Would you like to undo any changes - type 'undo'? ").lower()
if undo == "undo":
print("Here are the previous letters you have swapped ")
for i , j in enumerate (changes):
for c in changes:
for i in indices:
print(choose, replace)
Here are my text file calls and list definitions:
with open("football.txt","r") as file_one:
Encoded_Team = file_one.read()
with open("football_Solved.txt","r") as file_two:
Team = file_two.read()
encoded = list(Encoded_Team)
plaintext = list(Team)
changes = []
print("\nThe encoded team is {0}\n".format("".join(encoded)))
print("You will have 15 goes maxium")
menu()
Here is the menu:
def menu():
play_game = print("1. Play the game")
instruc = print("2. Instructions")
question = input("Enter choice")
if question == "2":
print("You will given a list of coded words, you have to replace the symbols to letters to get the word")
print("\n")
menu()
else:
play()
I am trying to develop the following piece of code from the main function so it allows the user to choose a previous character swap to undo - I know I need to enumerate but I am just not able to piece it together. Any ideas?
undo = input("Would you like to undo any changes - type 'undo'? ").lower()
if undo == "undo":
print("Here are the previous letters you have swapped ")
for i , j in enumerate (changes):
for c in changes:
for i in indices:
print(choose, replace)
I have added the following code to display the previous pairings chosen:
if undo == "undo":
for index, change in enumerate(changes):
chosen, replaced, indices = change
pairs.append(change)
for change in pairs:
print(chosen, replaced)
But instead of displaying the two last pairing, it will display the last pairing twice
What character would you like to replace?M
What character would you like to replace it withL
Replaced 'M' with 'L'
Would you like to undo any changes - type 'undo'?
The encoded team is Ljwfsqppm
What character would you like to replace?j
What character would you like to replace it withi
Replaced 'M' with 'L'
Would you like to undo any changes - type 'undo'? undo
j i
j i
Replaced 'j' with 'i'
Would you like to undo any changes - type 'undo'?
Any idea?
I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.