This question already has answers here:
How do I re-run code in Python?
(9 answers)
Closed 6 years ago.
I want the code below to automatically rerun itself any ideas hwo to do this? Btw I am new to stack overflow and python itself so If I am doing anything wrong on either please let me know, Thanks
import sys
import os
import random
answer_correct_message = random.choice(['Well done', 'Correct answer','Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
def question_asker_and_answerer():
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
print(answer_wrong_message)
print question_asker_and_answerer()
This is not a situation where you are need a program to rerun itself. That sort of requirement is when you want a script to run as a daemon. This is simply a matter of creating a loop
while True:
print question_asker_and_answerer()
There are two problems here:
how to iterate;
how to make sure that the various randomly-chosen variables are different each pass through.
Just looping over the existing function, or getting it to recurse (as in a couple of other answers) solves the first of these problems (actually, recursing really doesn't, since Python doesn't have tail-call elimination, so it will run out of stack eventually).
To solve both of them you need to make the randomly-chosen variables local to the function, and then loop. I have also modified it so it returns the string to print rather than printing it, in the case of a wrong answer (last line of function).
import sys
import os
import random
def question_asker_and_answerer():
answer_correct_message = random.choice(['Well done', 'Correct answer',
'Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
while True:
print question_asker_and_answerer()
Related
I'm trying to use the input function but every time, without fail, the word "None" appears at the end of my question/string (well running), it's capitalized just like that but has no overall effect on the code, it just ruins the project I'm working on.
Here's my code:
import time
import sys
def dp(s):
for c in s:
if c != " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.22)
elif c == " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0)
name = input(dp("Hello, whats your name? "))
Every function in python will return something, and if that something isn't defined it will be None (you can also explicitly return None in a function). So, your dp() function returns None, and so you are effectively calling input(None), which gives the same prompt of None.
Instead, try putting in input() call within the function itself.
def dp(s):
for c in s:
if c != " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.22)
elif c == " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0)
return input()
name = dp("Hello, whats your name? ")
I'm making a curency converter, time converter and weather app for an year 12 computer sciences project. Im unable to interrupt the loop that is being used for the main menu/location selector.
Can anyone help?
The code is below.
##This program is intended to help travellers with date and currency conversions ##
##Changelog----->##
##V1 - Include code for Forex Converter, code modified from - https://www.w3schools.in/python/examples/real-time-currency-converter##
##V2 - Implement GUI##
##V2.1 - Implement Multiple Screens GUI##
##V3 - Remove all GUI aspects##
##V3.1 - Create initial loop##
##Import Modules##
from forex_python.converter import CurrencyRates
import time
import datetime
import python_weather
import asyncio
##Opening info##
##V3.1##
global enter
enter = 'GO'
while enter == 'GO':
print("========================================================================================================================================================================================")
print("")
print("Welcome to the Traveller Assisstant. This program is able to help you with currency conversions, date and time conversions and viewing weather details of your destination.")
print("")
print("========================================================================================================================================================================================")
time.sleep(2.5)
ori = str(input("Please enter your current country: "))
dest = str(input("Please enter your destination country: "))
time.sleep(5)
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
if check == 'YES':
enter = 'STOP'
elif check == 'NO':
print("Returning to Location Selector")
enter = 'GO'
##V1##
##Change Currency##
#cr = CurrencyRates()
#output = cr.convert(entry1, entry2, entry3)
#final = round(output, 2)
#print("THE FINAL AMOUNT IS:", final, c2)
A simple typo, that's all that was wrong.
In this line of code:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
You are attempting to use the method
.upper()
But your fatal flaw is that you forgot the parentheses.
I changed this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
To this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
And the code worked perfectly for me
EXPLANATION
In the original code, check could never be equal to 'YES' or 'NO', because of the typo;
.upper was never recognized as a strings' function and returned with this value:
<built-in method upper of str object at 0x105fec130>
.upper() on the other IS in fact a valid function for a string and returned with this value when it was supplied with the input of 'yes':
YES
If you need to exit from the loop when a condition is met you can achieve that easily by using break. So when your condition is met:
either add bellow enter = "STOP" the statement break or just replace enter = "STOP" for break
if check == 'YES':
enter = "STOP"
break
or
if check == 'YES':
break
both should work, I guess you could go with the first answer if you need to keep the state of the variable enter otherwise you could just use the second.
The problem with your original code is that you are missing a parenthesis on the declaration of the upper method in this line:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
instead it should be:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
if you don't add the parenthesis to upper() it means you are declaring the object method itself not triggering instead what the method actually does. (In this case making the string uppercase)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
TypeError: ‘module’ object is not callable
This is my very first Python attempt, just trying to regain basic programming knowledge after a 10 year silence in a, for me, new language, Python. The basic idea is a tiny battly engine which decides the better hit. The bugging code is next.
self.__power = self.__att*random(2,4)/dier.__defn
As my python knowledge is extremely basic, I'm rather scared of saying the right things so Im gonna put my code down below (47 lines), you..ll notice it is really transparant so I dont suspect this will give any problem. The errorline is 16. I tried renaming the att variable to atta as well as some repositionings though new bugs come, I solve them and in the end its always the same error on the same line.
class Character:
def __init__(self,name="", att=0,defn=0,lvl=0,leven=0,exp=0, power=0):
self.__att = att
self.__defn = defn
self.__lvl = lvl
self.__leven = leven
self.__name = name
self.__xp = exp
self.__power = power
def batl(self):
import random
while self.__lvl <= 3:
dier = Character("Anaconda",1,1,50,1,0,0)
print "You encountered an " + dier.__name + " and fight it."
**self.__power = self.__att*random(2,4)/dier.__defn**
dier.__power = (dier.__att*random(1,4))/self.__defn
if self.power > dier.power:
growth = dier.__lvl*dier.__atta
groei()
else:
dmg = dier.lvl*dier.att
leven = leven-dmg
if leven < 0:
print "Alas, you're done for."
exit()
else:
print "You took " + dmg + "damage and have " + leven + "life left."
def groei(self):
if (growth+exp) > 100:
lvl += 1
exp = growth-100
print "You won and gained " + str(growth) + " and grew from level " + str(lvl-1) + " to level " + str(lvl) + "."
else:
exp = growth + exp
print "You won and gained " + str(growth) + "."
def main():
hero = Character("Nevery",2,1,2,100,0,0)
hero.batl()
if name == 'main':
main()
As you can see ive got my character class, in which i have defined the battle() method and the groei() method, very basic. Can anyone point me what I'm missing out on, been looking at it for hours. Thanks in Advance
random is the module, not the function. You need to call random.random. You could also from random import random, but I'd go with the first option in this case.
Use random.random() instead of random?
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).
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Python Application does nothing
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv("HOSTNAME")
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
The input() is supposed to execute and it stopped working after changing something I dont remember
It's coded under Python 3.1.2 with Windows 7, I know the Unix Hostname global variable is wrong
I know userinput does nothing, I want to get this part working before I continue on
Thanks
It outputs nothing
You define a class and two functions, but you don't seem to call any of them anywhere. Are you missing a call to MainShellLoop() in the end?
I think you need a call to MainShellLoop.