I'm trying to build a standalone application like the dice roller on Roll20.net, starting off simple and as I get better I can add more features, including a GUI, but returning to this project after giving up months ago, I still cannot get even the most basic form to even output.
import random
from random import randint
d20 = randint(1,20)
str1 = "You rolled a "
str2 = "Congrats Critical Hit"
str3 = "Uh Oh, Critical Fail"
def roll(d20):
roll(d20)
print (str1 + roll(d20))
if (d20 == 1):
print (str3)
elif (d20 == 20):
print (str3)
else:
print ("")
I either get a completely blank output, implying that the program technically runs, or I'll get a "function roll at 0x02A3B078" or I'll get a response that something isn't defined.
How to solve this?
You're defining a function, but not calling it? Add this line at the bottom of your program:
roll(d20)
Don't call your function inside itself. This leads to infinite recursion.
What you need is something like this:
...
def roll(d20):
print(str1, d20)
if d20 == 1:
print(str3)
elif d20 == 20:
print(str3)
roll(d20)
Do you want to make your program interactive? You could initialise a while loop and repeat while as long as the user is interested in playing.
while True:
d20 = randint(1, 20)
roll(d20)
if input('Keep playing? ') not in {'y', 'Y'}:
break
Try that
import random
from random import randint
str1 = "You rolled a "
str2 = "Congrats Critical Hit"
str3 = "Uh Oh, Critical Fail"
def roll(d20):
print (str1 + str(d20))
if (d20 == 1):
print (str3)
elif (d20 == 20):
print (str3)
num_of_rolls = 10
while num_of_rolls:
d20 = randint(1,20)
roll(d20)
num_of_rolls -= 1
Some things that you may take into account in the future. You didn't call the function. It sometimes prints no output, because it has 18:20 chance to print(""). You shouldn't start with (1,20) range. Test (1,2) and put print statement everywhere you can. That's the only way to be sure what's happening inside your function. You don't need to print("") if you don't need it.
Related
Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1
My code will always take the first input despite the input. I have tried taking guess and making guess into an int but that leads to both if statements to trigger
x = 1
answer = 4
A=0
guess = 0
while A < 10:
for _ in range (5):
x = random.randint(1,5)
print ("Ralph holds up " + str(x) + " fingers what is the answer")
guess=input()
if guess != answer:
print("WRONG PROGRESS RESET")
A=0
answer = x
if guess == answer:
A += 1
print ("correct")
print ("You have " + str(A) + " out of 10 finished")
answer = x
print ("You win congrats")
First off your code never even import random to use randint. But I'll assume you did import it and you just never pasted it in.
input reads your input as a str, but you want it to read as an int. All you really need to do is wrap the input() call in an int invocation. Additionally, input takes an argument, which prompts that argument in the console.
Also #tobias_k has a good point, but instead of elif guess == answer:, just use else:.
I also changed some variable logic, and I changed A to a much more meaningful identifier, as well as fixing formatting, like a = b is more aesthetically pleasing than a=b.
Oh and indentation. Indentation is important, not only for readability, but in Python, it's required. Python is whitespace significant, meaning scope delimiters are whitespace.
import random
finished_count = 0
while finished_count < 10:
for _ in range(5):
answer = random.randint(1, 5)
guess = int(input("Ralph holds up %d finger%s. What is the answer?\n" % (answer, "" if answer == 1 else "s")))
if guess != answer: # incorrect answer
print("WRONG PROGRESS RESET")
finished_count = 0
else: # correct
finished_count += 1
print("Correct. You have %d out of 10 finished" % finished_count)
print("You win, congrats!")
I just used this code up until I got to 10 and it works fine
So I'm new to this programming thing... But this has me stumped. To the point that I'm wondering if the website I'm running Python on is wrong. (repl.it is the website).
So I did one of those guess the number games as a small fun challenge. This is the code that I came up with:
from random import randint
print ("Welcome to guess the number!")
answer = str(randint(0,100))
print (answer)
print ()
def something():
answerTwo = str(randint(0,100))
print (answerTwo)
idea(answerTwo)
def idea(x):
number = str(input("Guess a number between 0 and 100:"))
if number != x:
if (number > x):
print()
print(number + " is too high!")
print()
idea(x)
elif (number < x):
print()
print(number + " is too low!")
print()
idea(x)
else:
print()
print ("That is correct!")
again = input("Would you like to play again?:")
if again == "yes":
something()
else:
print ("Thanks for playing!")
idea(answer)
On the 4th and 8th line I print out the random number chosen so that I can quickly test to make sure everything works. Then I removed the print functions in the final product and tested again. Except when I removed the print functions it stopped working after some amount of time. For example, it'll say 39 is too low but 40 is too high, which is impossible since they're is no number in between them. If you put the print functions back in it works again, but remove them and it'll start acting up eventually.
I apologize if it's something really obvious but I just don't understand how this is possible.
Here is the github thingy for it
https://gist.github.com/anonymous/4a370664ae8ddb29aec5915eb20e686f
Thanks for your time!
There is no integer i such that 39 < i < 40.
There is however a numeric string s such that "39" < s < "40". Observe:
>>> "39" < "4" < "40"
True
In short: It has nothing to do with your print calls, instead, just work on actual numbers and cast your input to a number using int(). print() can handle numbers just fine.
so i have been working on a input based dungeon game in python that is fairly rudimentary. I wanted to put a dice roll condition in the game and decide if a player will die or live on a path. However my if statement will not properly respond to the roll in the number generator i have in the program, it will print the number and then carry on whether or not the condition was met. How can i fix this, and why is this happening?
if direction == 1:
import random
from random import *
num = 6
def d6(num):
rolls = []
for x in range(num):
rolls.append(randint(1,6))
return rolls
rolls = d6(1)
print rolls
if rolls is 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
elif rolls is not 3:
print "you are back at the start which way will you go?\n"
path3 =float(input("forward, or right?"))
is and is not are reserved for special comparisons in python. You need == and !=. Also you can change it to a simple if/else instead of if/elif with no else. Also, it looks like your d6 function returns a list instead of a single number. Try adjusting that to return a single number instead:
from random import randint
def d6():
return randint(1,6)
rolls = d6()
if rolls == 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
else:
print "you are back at the start which way will you go?\n"
I am trying to make a Heads Or Tails program in Python. I am a newbie and I have just got into Python. What I try to achieve is to have the program pick either Heads or Tails without me knowing it (Yes, import random, etc.) and I would like to have a single try when guessing. This is what I have achieved so far, yet it is not very close to what i am looking for. Any thoughts? I have tried implementing the different random arguments I found on a Python website but they don't work (such as randint for integers)... Thanks!
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = "Heads" # For Debugging purposes to check if the program works
notCorrectAnswer = "Tails" # To eliminate the possibility of not being either tails or heads in case of mistaken answer
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"
You should try:
import random
ch = random.choice(["Heads","Tails"])
which will put into the variable ch either "Heads" or "Tails". Try to do something from that.
To make the whole thing continue until exited by user, and including #Baruchel's answer:
import random
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
cont = 1 #To force the game to run for one round without user input
while(cont == 1): #cont is used to take user choice, whether to run it again or not
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = random.choice(["Heads","Tails"])
if ourAnswer == "Heads":
notCorrectAnswer = "Tails"
else:
notCorrectAnswer = "Heads"
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"
cont = input("Do you want to continue? Press 1 if yes, press 0 if no.: ") #Take user choice on whether to run it again or not
while (cont != 0 and cont != 1): # If user puts in a different number (neither 1 or 0), make them enter until they put a right choice
cont = input("Please try again. Press 1 if yes, press 0 if no.: ")