I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using python 3.2
from random import choice
print("Welcome , let's get started")
input()
def word():
print('Humiliate')
a = input(':')
while a == 'abasement':
break
else:
word()
# --------------------------------------------------------- #
def word1():
print('Swelling')
a = input(':')
while a == 'billowing':
break
else:
word()
# ------------------------------------------------------------ #
wooo = [word(),word1()]
while 1==1:
print(choice(wooo))
is there any faster way of doing this and get real random? I tried classes but it seems harder than this. Also, is there any way I can make python not care about weather the input is capital letter or not?
To answer one part of your question ("is there any way I can make python not care about weather the input is capital letter or not?"): use some_string.lower():
>>> "foo".lower() == "foo"
True
>>> "FOO".lower() == "foo"
True
An this is to help you how you could improve the structure of your code:
import sys
from random import choice
WORDPAIRS = [('Humiliate', 'abasement'), ('Swelling', 'billowing')]
def ask():
pair = choice(WORDPAIRS)
while True:
answer = raw_input("%s: " % pair[0]).lower()
if answer == pair[1]:
print "well done!"
return
def main():
try:
while True:
ask()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == "__main__":
main()
It works like that:
$ python lulu.py
Swelling: lol
Swelling: rofl
Swelling: billowing
well done!
Humiliate: rofl
Humiliate: Abasement
well done!
Swelling: BILLOWING
well done!
Humiliate: ^C
$
wooo = [word, word1]
while 1:
print(choice(wooo)())
But in any case it will print you None, cause both of your functions return nothing (None).
Related
I'm making an unoriginal game for a first project that just runs in my python terminal. The user is randomly given a set of 2-3 letters and the user has to come up with a real word (checked by the Webster dictionary) that contains the given set of letters within 5 seconds. For example, if the game generates "le" the user can input "elephant" within 5 seconds as a correct word and gives them a point.
The problem is that I can't seem to implement the 5 second timer function to run in the back for every time a prompt is given without messing up some other part or running into another problem. I've looked into threading and can't seem to make use of it.
Here is the code for the main game:
from letters import letter_sets_list
fhand = open("words_dictionary.json")
data = fhand.read()
global score
score = int(0)
game_over = False
while game_over is False:
import random
random_letters = random.choice(letter_sets_list)
print('Word that contains:', random_letters)
answer = input("Type a word:")
if answer in data and random_letters in answer:
score += 1
print("nice one")
else:
game_over = True
print("Game Over \n Score:", score)
fhand.close()
exit()
Here is the timer function I found off YouTube and tried to implement:
def countdown():
global my_timer
my_timer = int(5)
for x in range(5):
my_timer -= 1
sleep(1)
countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()
Take a look at that. Especially check if that will work for you:
import time
from threading import Thread
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow")
Thread(target = check).start()
answer = input("Input something: ")
Edit: I tried to implement code from my previous answer to your code but with a little different approach:
import time, threading
#from letters import letter_sets_list
#import random
#fhand = open("words_dictionary.json")
#data = fhand.read()
data = ["answer"]
answer = [None]
random_letters = [None]
global score
score = int(0)
game_over = False
x = 0
def game(answer, random_letters):
#random_letters = random.choice(letter_sets_list)
print('Word that contains:', random_letters)
while True:
answer[0] = input("Type a word: ")
mythread = threading.Thread(target=game, args=(answer, random_letters))
mythread.daemon = True
mythread.start()
for increment in range(5):
time.sleep(1)
if answer[0] in data: # and random_letters in answer
score += 1
print("Good answer")
x = 1
break
if x != 1:
print("\nTime is up")
else:
x = 0
game_over = True
In this approach I didnt use time.sleep() inside threaded function but outside of it which helps with killing it. Also i assumed that if your answer is incorrect you would like to have another chance to answer untill time is up or answer is correct so I just used while loop in threaded function. The code is quite simple so I think if you spend a little time analysing your parts of the code you will figure it out.
Some parts of the code I didn't use as I dont have access to your json files ect., but if I understand correctly what you're trying to do, it shoud work. Also check how will behave your kernel. In my case sometimes it shows some problems but my PC is not the best and so it might be only problem with RAM or other part of my computer as it happens quite often with my projects.
My aim:
To create a python Modules with 3 functions:
Sample input1: bob
output:
Yes it is a palindrome
No. of vowels:1
Frequency of letters:b-2,o-1
=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
ch = input("Enter a character: ")
if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
In a new file I am giving :
import test
def main():
while True:
word = input("enter a word")
test.isPalindrome(word))
test.count_the_vowels(word))
if __name__ == "__main__":
main()
If I call my module in another file, it automatically does all the functions. But I want to give input(name) in this new module and check the output for it.But this is asking input again since name is present before def function in the other file. How to overcome this?
I am new to coding.Please be as elaborate as possible.Thanks in advance.
If you're question is "how to ask for the name only once and pass it to both function", the answer is simple: in your main.py script (or test.py or however you named it), add this:
import yourmodule # where you defined your functions
def main():
while True:
word = input("enter a word (ctrl+C to quit) > ")
yourmodule.isPalindrome(word)
yourmodule.count_the_vowels(word)
# etc
if __name__ == "__main__":
main()
Now note that your assignment doesn't say you have to do this - it says:
Import the module in another python script and test the functions by passing appropriate inputs.
Here, "passing appropriate inputs" can also be understood as having a harcoded list of words and calling your functions with those names... IOW, a unit test.
After trying several times to explain in the comments here is a brief example. so make a file with your functions. then in your other file import your funcs file then ask user for name and pass it to the funcs. This is just an example of how to define functions in one file and then call them from another. you probably want to look at your funcs as they should probably return values rather then just print stuff otherwise your calling file wont be able to validate the function since it will receive nothing back.
MyFuncs.py
def hello(name):
print(f"hello {name}")
def goodbye(name):
print(f"goodbye {name}")
stackoverflow.py
import MyFuncs
name = input("Name: ")
MyFuncs.hello(name)
MyFuncs.goodbye(name)
**OUTPUT: **when running the stackoverflow.py script
Name: Chris
hello Chris
goodbye Chris
The program asked is:
"besides testing if the length of the given string is more than ten characters, it also tests if there is the character "X" (capital X) in the given string. If the string is longer than 10 characters and it has X in it, the tester subfunction returns a value True to the main function, otherwise False.
If the subfunction returns True to the main function, the program prints "X spotted!". As earlier, if the user inputs "quit", the program terminates."
This is what I tried, but the part of checking the x character does not work at all
def check(st,res="Too short"):
if len(st)>=10:
if checkX(st):
st=st+"\nX spotted!"
return st
else:
return res
def checkX(st):
for i in st:
if i=="X":
return True
return False
def main():
while True:
st=input("Write something (quit ends): ")
if st=="quit":
break
print(check(st))
It only checks if introduced string length is equal or higher than 10 characters.
The code works.
What should you change in your code:
You can use the in operator:
if "blah" not in somestring:
continue
Does Python have a string 'contains' substring method?
Do a real "main":
if __name__ == '__main__':
What you can do if you want to keep the main() function:
A module can discover whether or not it is running in the main scope by checking its own name, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
main — Top-level script environment
Result (this code works, it is simplier, more pythonic and respect pep8):
def check_input(tested_sentence: str, result: str = "Too short"):
if len(tested_sentence) >= 10:
if "X" in tested_sentence:
result = tested_sentence + "\nX spotted!"
else:
result = tested_sentence
return result
def main():
while True:
sentence = input("Write something (quit ends): ")
if sentence == "quit":
break
print(check_input(sentence))
if __name__ == '__main__':
main()
Code Style — The Hitchhiker's Guide to Python
I'm writing my first program - it's an idiom generator, which combines individual elements from lists of random verbs, nouns, and pronouns (that I have entered) in Madlibs style and generates a humorous expression. This is a simplified version of my source code:
baseFunction = True
def mainFunction() :
import random
quest = input("Which language do you want it in? Type 'French' or 'English'. ")
if quest == "French" or "french":
verb =
#list of verbs I have manually entered
noun =
#list of nouns I have manually entered
pronoun =
#list of pronouns I have manually entered
morenouns =
#list of nouns I have manually entered
phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
print(phrase)
print("Now, give it some meaning and use in the world!")
elif quest == "English" or "english":
verb =
#another list of verbs I have manually entered
noun =
#another list of nouns I have manually entered
pronoun =
#another list of pronouns I have manually entered
morenouns =
#another list of nouns I have manually entered
phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
print(phrase)
print("Now, invent some meaning for it and use it in the world!")
f8 = input("Do you want to make another one? Say 'yes' if you do. ")
if f8 == "yes" or "Yes":
mainFunction()
else:
print("Thanks for playing!")
else:
print("Didn't quite catch that. Try again! (say yes!)")
mainFunction()
def malif() :
ques = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
if ques == "yes" or "Yes":
mainFunction()
elif ques == "no" or "No":
print("Wrong answer. Try again! (say yes)")
malif()
else:
print("Didn't quite catch that. Say 'yes' or 'no'.")
while baseFunction :
malif()
mainFunction()
Essentially, I am asking the user whether they want to make an idiom, offering them a choice of language, generating the expression for them, and then asking them if they want to repeat the process. When I run the script in PyCharm, it runs the two functions in order (meaning, malif() first and then mainFunction(), as I have it at the end) but it does not pay any attention to my input (ex. if I say 'no' it runs the mainFunction anyway and will always do it in French even if I say 'English').
I used some of the tips discussed in this entry (Python - How to make program go back to the top of the code instead of closing). I think the problem lies calling the functions in their own definitions (ex. calling malif() if I answer 'no' to input 'ques', which is defined in malif() ). Yet, I have followed the tips discussed in the question that I linked and it is still not working the way that I want it to. Am I doing something wrong in formatting the code (ex. in terms of indentation) or if it is not obvious what I am doing wrong, is there a way for me to loop functions back to the beginning that was not suggested in the original question?
Thanks!
First some tips when you work with strings as input. Python will make the difference between caps and non-caps letter, thus a good way to deal with strings is to lower() them first (or upper(), ...):
Example:
ques = input("Enter Yes or No: ")
ques = ques.lower()
if ques == "yes":
# do something
elif ques == "no":
# do something else
else:
# raise error
Now I feel like your code is build in a funny way. A good habit is to separate the import from the functions, from the main program. The 2 first will be imported if the module (file) is imported, while the last one will be played when the file is executed. To do so, you can use this:
# -*- coding: utf-8 -*-
"""
docstring of the module
"""
# Imports
import random
import os
# Functions
def f():
return "Hello world"
# Main program
if __name__ == '__main__':
# Calling the function, taking the inputs and so on
In the main program, it's rather useful to deal with the possibility that an exception is raised. Moreover, if you use the cmd to display your program, the cmd will close immediately when an error is raised. This syntax is quite useful:
if __name__ == '__main__':
try:
# Do stuff
except:
import sys
print (sys.exc_info()[0])
import traceback
print (traceback.format_exc())
os.system("pause") # for windows, else easy way is to have an empty input to freeze the cmd
Now your code. I would rework it this way:
# -*- coding: utf-8 -*-
"""
Docstring
"""
# Imports
import random
import os
# Functions
def build_a_phrase(language) :
if language == "french":
verb = ["vendre", "atterir", "attaquer", "jeter"]
#list of verbs I have manually entered
noun = ["arbre", "poisson", "chien"]
#list of nouns I have manually entered
pronoun = ["un", "les"]
#list of pronouns I have manually entered
morenouns = ["chat", "oiseau"]
#list of nouns I have manually entered
choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
phrase = " ".join(choices) # Add a space between the words
return phrase
elif language == "english":
verb = ["...", "...", "..."]
#another list of verbs I have manually entered
noun = ["...", "...", "..."]
#another list of nouns I have manually entered
pronoun = ["...", "...", "..."]
#another list of pronouns I have manually entered
morenouns = ["...", "...", "..."]
#another list of nouns I have manually entered
choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
phrase = " ".join(choices) # Add a space between the words
return phrase
if __name__ == '__main__':
try:
# Parameters
available_language = ["french", "english"]
available_answers = ["yes", "no"]
# Safety implementation of an input
quest = ""
i = 0
while quest.lower() not in available_answers:
quest = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
i += 1
if i == 2: # number of tries
break
if quest.lower() == "no":
print ("I'm sure you meant yes.")
language = ""
i = 0
while language.lower() not in available_language:
language = input("Which language do you want it in? Type 'French' or 'English'.\n")
i += 1
if i == 2: # number of tries
break
while True:
sentence = build_a_phrase(language)
print (sentence)
print ("Now, give it some meaning and use in the world!")
f8 = ""
i = 0
while f8.lower() not in available_answers:
f8 = input("Do you want to make another one? Say 'yes' if you do. ")
i += 1
if i == 2: # number of tries
break
if f8.lower() == "no":
print("Thanks for playing!")
break
except:
import sys
print (sys.exc_info()[0])
import traceback
print (traceback.format_exc())
os.system("pause")
Hope you'll get a few good tricks from this answer, and some good habits :)
Not complete yet, when the input is wrong, an Error should be raised rather than waiting for the error resulting in the wrong input (i.e. a raise statement should be placed instead of the breaks)
I am trying to write a few tests for a random input number game but not too sure how to proceed on.
I am following the Python Game from http://inventwithpython.com/chapter4.html
Started the tests with a file test_guess.py
from unittest import TestCase
import pexpect as pe
import guess as g
class GuessTest(TestCase):
def setUp(self):
self.intro = 'I have chosen a number from 1-10'
self.request = 'Guess a number: '
self.responseHigh = "That's too high."
self.responseLow = "That's too low."
self.responseCorrect = "That's right!"
self.goodbye = 'Goodbye and thanks for playing!'
def test_main(self):
#cannot execute main now because it will
#require user input
from guess import main
def test_guessing_hi_low_4(self):
# Conversation assuming number is 4
child = pe.spawn('python guess.py')
child.expect(self.intro,timeout=5)
child.expect(self.request,timeout=5)
child.sendline('5')
child.expect(self.responseHigh,timeout=5)
child.sendline('3')
child.expect(self.responseLow,timeout=5)
child.sendline('4')
child.expect(self.responseCorrect,timeout=5)
child.expect(self.goodbye,timeout=5)
def test_guessing_low_hi_4(self):
# Conversation assuming number is 4
child = pe.spawn('python guess.py')
child.expect(self.intro,timeout=5)
child.expect(self.request,timeout=5)
child.sendline('3')
child.expect(self.responseLow,timeout=5)
child.sendline('5')
child.expect(self.responseHigh,timeout=5)
child.sendline('4')
child.expect(self.responseCorrect,timeout=5)
child.expect(self.goodbye,timeout=5)
and the guess.py file with
intro = 'I have chosen a number from 1-10'
request = 'Guess a number: '
responseHigh = "That's too high."
responseLow = "That's too low."
responseCorrect = "That's right!"
goodbye = 'Goodbye and thanks for playing!'
def main():
print(intro)
user_input = raw_input(request)
print(responseHigh)
print(request)
user_input = raw_input(request)
print(responseLow)
user_input = raw_input(request)
print(responseCorrect)
print(goodbye)
if __name__ == '__main__':
main()
Not sure How to proceed on with writing a few more tests with if statement to test if the value is low or high. I was told to try a command line switch like optparse to pass the number but not sure how to do that either.
Somewhat of a new person with Python, any guidance or assistance would be appreciated.
In order to do command line parsing in nosetests, you'll have to do something similar to this (at least that's what I had to do), i.e. create a plugin that will give you access to the command line parameter in nosetests. Once you had the plugin added which gave you the command line parameter, it would be pretty easy to create a test that would take advantage of that passed in parameter.
from test_args import case_options
class GuessTest(TestCase):
...
def test_guessing(self):
# Conversation assuming number is 4
if case_options.number < 4:
# Do something
elif case_option.number > 4:
# Do some other test
else:
# Do the final test
Does that make sense? I might be misunderstanding what you are trying to do so if I am, just let me know and hopefully we can clear it up.