I have this assignment I have been working on
temperatures = []
def decision():
answer = input("Do you want to enter a temperature?" +
"\"y\" for yes. \"n\" for no: ")
getTemp(answer)
def getTemp(answer):
while answer == "y" or answer == "Y":
temp = int(input("Enter a temperature: "))
temperatures.append(temp)
print("\nTemperature Entered!\n")
answer = " "
decision()
print("Temperatures entered: ", temperatures)
def main():
decision()
main()
The problem is when I enter a temperature then press n to exit the while loop, the final output is more than one print statement. For example if I input:(y's == yes)
y
3
y
5
n
the output is
Temperatures entered: [3,5]
Temperatures entered: [3,5]
Temperatures entered: [3,5]
Any help would be great...Thanks
The issue is that getTemp is being called multiple times, due to it calling decision, which in turn calls getTemp. Instead, you should only print the temperatures after you exit the above chain, so you should move the print to after you call decision in main, so main should be:
def main():
decision()
print("Temperatures entered: ", temperatures)
and getTemp should be
def getTemp(answer):
while answer == "y" or answer == "Y":
temp = int(input("Enter a temperature: "))
temperatures.append(temp)
print("\nTemperature Entered!\n")
answer = " "
decision()
You are recursing. If you ended up wanting to enter, say, 500000000 temperatures, you would definitely cause a stack overflow.
Your print executes at the end of each decision() execution. I suggest restructuring your code to not recurse (to save yourself from allocating forever) or at the very least put your print statement in your main.
For example, you could do this
temperatures = []
def decision():
while input("Do you want to enter a temperature?\n" +
"\"y\" for yes. \"n\" for no: ") in "yY":
getTemp()
def getTemp():
temp = int(input("Enter a temperature: "))
temperatures.append(temp)
print("\nTemperature Entered!\n")
def main():
decision()
print("Temperatures entered: ", temperatures)
main()
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last year.
I am fairly new to programming and I scrapped some code together to make a sequence calculator using python.
I'm trying to restart it at the "user_continue = input ("Would you like restart [y/n]? ")" part whenever the user would input an invalid answer, but I don't know how to do that, help?
import time
from time import sleep
while True:
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")
???
import time
from time import sleep
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
def takeInputs():
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
takeInputs()
while True:
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
takeInputs()
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")
This is what happens exactly in Mac Terminal:
Enter command to calculate:
+,-,* or/:
after typing the command it asks me for num1 and num2:
type first number: 5
type second number: 5
then it asks me:
do you want to continue?
I type 'yes', the program starts all over again. Now the problem is,
the second time I do a calculation, it doesnt ask me if I want to continue, but it jumps straight to:
Enter command to calculate:
+,-,* or/:
or sometimes:
type first number: 5
type second number: 5
Why does that happen? and how can I make the program ask me every time if I want to continue after each calculation?
loop = True
while loop:
def func():
usr = input('''Enter command to calculate:
+,-,* or/:
''')
if usr not in ("+,-,*,/"):
print("Error! command not allowed. Try again")
func()
num1 = float(input("type first number: "))
num2 = float(input("type second number: "))
if usr == "+":
print("{0} + {1} = {r:0.2f}".format(num1,num2,r=num1+num2))
elif usr == "-":
print("{0} - {1} = {r:0.2f}".format(num1,num2,r=num1-num2))
elif usr == "*":
print("{0} * {1} = {r:0.2f}".format(num1,num2,r=num1*num2))
elif usr == "/":
print("{0} / {1} = {r:0.2f}".format(num1,num2,r=num1/num2))
def func2():
x = input("do you want to continue? ")
if x == "yes":
func()
elif x == "no":
exit()
else:
print("That was not clear. Try again: ")
func2()
func()
func2()
Do you know what I should do in this case?
Depends on what you aim at and what exactly you want to make.
Here's the easiest way to make a powerful console calculator, but at the same time the most insecure:
import os
import sys
import math
def main(argv = sys.argv):
print("EVAL Calculator\nType 'exit' to exit\n")
while True:
exp = input("Type a mathematical expression and press ENTER: ")
if exp.lower() == "exit": return
else: print(eval(exp))
if __name__ == "__main__":
main()
Input: 2 + 2 * 2
Output: 6
If this doesn't work for you, you can just split a string or use regular expressions.
If you just want to get your code to work well, move while True to the end of the code and tabulate the code itself.
It is not recommended to use the above code for those projects that are intended to be used by other people.
So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()
I'm trying to write a dice roller as practice. I've tried to look into try, except, while, but neither works as I intend it - before asking if the user wants to continue, I'd want to check if the user input is valid, and if not, return to user_number1. Am I looking at this from the wrong angle? What can I do with this?
Sorry for the possibly stupid question, I'm pretty new to this.
import random
print("Welcome to the dice roller!")
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
if num1 == 1:
result1 = random.randint(num1, num1*num2)
print("Your roll is: " + str(result1) + " (" + str(num1) + "d" + str(num2) + ")" )
else:
dice_number = 1
list_of_results = []
while dice_number <= num1:
result2 = random.randint(num1, num2)
list_of_results.append(result2)
dice_number += 1
print("Your roll is: " + str(sum(list_of_results)) + " (" + str(num1) + "d" + str(num2) + ", " + str(list_of_results)+ ")")
def shouldi():
roller()
usercont = input("Do you want to continue? y/n > ")
while usercont in ["Y", "y"]:
roller()
usercont = input("Do you want to continue? y/n > ")
if usercont in ["N", "n"]:
print("Thank you for using the dice roller. Bye!")
quit()
else:
print("That is not a valid input.")
usercont
Something like below is an alternate approach to using regex. If you're comfortable with regex then I would prefer using that instead of this. This is only an alternate approach.
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
if("d" in user_number1):
if(len(user_number1) == 3):
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
else:
print("Your input not in valid format. Use the format XdX")
You can use regular expressions and write a function that does exactly what you need then you can use it within your roller() function:
import re
def get_number():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = re.match("^(\\d*)d(\\d+)$",user_number1,re.I)
if not user_number_fin: get_number()
if user_number_fin.group(1) =='': num1 = 1
else: num1 = int(user_number_fin.group(1))
num2 = int(user_number_fin.group(2))
if num1>num2:
print("\n\tSorry--side to roll must be less than the number of sides!!")
get_number()
return {'num1':num1,'num2':num2}
This can accept d4 ie taking the default side if not given to be 1, and cannot accept 4d3 ie the side to be rolled must be less than the number of sides present in the dice.
I know the line "goto Start" is wrong just put it there, that's where I want the code to loop back to the start of the code but cannot figure out how to do it at all. Please help....
dsides = int(input("how many sides do your dice have?"))
print("Your dice has " + str(dsides) +" sides")
dint = int(input("How many dice do you want to roll?"))
print("You are rolling " + str(dint) + " dice")
import os
answer=0
import random
y=0
while( y < dint ):
out = random.randint(1, int(dsides))
print(str(out))
y=y+1
while (True):
answer = raw_input('Run again? (y/n): ')
if(answer in ("y", "n")):
if(answer == "y" ):
goto start
else:
print("GoodBye")
break
else:
print ("Invalid input.")
break
wrap the code in a function and call the function:
def my_function(output=''): # <-- change 1
dsides = int(input("how many sides do your dice have?"))
print("Your dice has " + str(dsides) +" sides")
dint = int(input("How many dice do you want to roll?"))
import random
y = 0
while y < dint:
out = random.randint(1, int(dsides))
output += "{} ".format(out) # <-- change 2
# print(str(output)) # <-- change 3
y=y+1
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ("y", "n"):
if answer == "y":
my_function(output) # <-- recursive call
else:
print(output) # <-- change 4
print("GoodBye")
return
else:
print ("Invalid input.")
break
Example output:
how many sides do your dice have?6
Your dice has 6 sides
How many dice do you want to roll?6
Run again? (y/n): n
2 1 3 4 6 5
GoodBye