first python program, what am i doing wrong - python

This is my attempt at a simple dice game. when I run the program it asks me how many dice I want to roll when I enter 1, it just asks again and then closes the program.
I feel like at least one of my problems is that the input maybe isn't being read as an integer?
I'm not really sure.
In the mean time, I'm gonna stare at it for a while and maybe ill figure it out.
import random
def roll1Dice():
roll = random.randint(1,6)
print("You rolled a " + roll)
def roll2Dice():
roll1 = random.randint(1,6)
roll2 = random.randint(1,6)
print("You rolled a " + roll1)
print("You rolled a " + roll2)
def main():
input("roll 1 or 2 dice? ")
if input == 1:
roll1Dice()
elif input == 2:
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main()

input is a function that returns a str. You need to capture this return and then compare it.
def main():
user_input = input("roll 1 or 2 dice? ")
if user_input == '1': # notice that I am comparing it to an str
roll1Dice()
elif user_input == '2':
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main() # add this line to request input again
Alternatively, you could cast to an int:
def main():
user_input = int(input("roll 1 or 2 dice? "))
if user_input == 1: # notice that I am comparing it to an int here
roll1Dice()
elif user_input == 2:
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main()
If you cast to an int, however, be aware that a non-int will cause an exception.

You weren't assigning the value of input to anything (input is the function that actually accepts user input) Also, your print statements were failing because they were trying to combine an int with a string, so I've replaced it using string formatting. The below code should help
import random
def roll1Dice():
roll = random.randint(1,6)
print("You rolled a %s" % roll)
def roll2Dice():
roll1 = random.randint(1,6)
roll2 = random.randint(1,6)
print("You rolled a %s" % roll1)
print("You rolled a %s" % roll2)
def main():
myinput = input("roll 1 or 2 dice? ")
if myinput == 1:
roll1Dice()
elif myinput == 2:
roll2Dice()
else:
print("Please enter a 1 or a 2.")
main()

Related

Why does my Python user input code not consider the input correct

I am new to coding and want to train and do my own thing with user inputs. The User Input code does not work. It is a number guessing game. When I guess the right number, it says "Incorrect".
import random
while True:
intro = input("Hello! Want to play a game?(Y or N)")
if intro.lower() == "y" or intro.lower() == "yes":
time.sleep(0.1)
print("Let's play a number-guessing game!")
max_num_in = input("Pick a big number")
max_num = int(max_num_in)
time.sleep(0.1)
min_num_in = input("Now pick a smaller number")
min_num = int(min_num_in)
rndm_num = int(random.randrange(min_num,max_num,1))
print(rndm_num)
rndm_in = input("Guess a number between the maximum and minumum numbers!")
if rndm_num == rndm_in:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in != rndm_num:
print("Whoops, wrong number. Please try again.(Trials left = 2)")
rndm_in1 = input("Guess again!")
if rndm_in1 == rndm_num:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in1 != rndm_num:
print("You didn't get it right. Please try again (Trials left = 1)")
rndm_in2 = input("Guess again!")
if rndm_in2 == rndm_num:
print("Whoo Hoo! You finally did it! The number was" + str(rndm_num))
elif rndm_in2 != rndm_num:
print("Incorrect. The number was " + str(rndm_num))
elif intro.lower() == "n" or intro.lower() == "no":
print("Alright. Bye")
Your inputs are strings convert them to int by using int() function
"5"!=5
This one looks suspicious:
if rndm_num == rndm_in:
It looks like you getting a str as rndm_in but your rndm_num is an int.
Try:
if rndm_num == int(rndm_in):

There's an issue somewhere in my Python code.. I can't find where it's at

I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")

Python3 can't repeat the loop after else statement (googled it and did'nt find a solid resault)

can't repeat the loop after the "else statement" (googled it and did'nt find a solid resault)
example:
I'm trying to make a dice game
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
user_input = input("Roll the Dice? [Y/N] ")
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while user_input:
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
else:
print('Invalid')
continue
user_input = input("Roll again? [Y/N] ")
print(user_input)
Your while loop needs a condition. While x == 1: or while 1:
If you use x = 1. When the value of x is other than 1, the while loop will stop or when a break is used.
If you use while 1, it will continue to loop until you use break.
Another point, you want to have the user_input within the while loop so that it can ask the user if they would like to roll again.
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
x = 1
while x == 1:
user_input = input("Roll the Dice? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
Answer: As noted by Klaus, removing the continue in the while user_input will fix the loop, to only re-roll when the user responds 'y'
Changing print(dice_roll()) to just dice_roll() (function call without printing it's return value) will keep this program from printing 'None' after dice rolls.
If you want it to print the return, you can change the
print(" The sum is", dices_sum) to
return(" The sum is", dices_sum)
try this
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while 1:
user_input = input("Roll? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input == 'y':
dice_roll()
elif user_input == 'N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
There are two problems that you need to fix.
Since your function dice_roll ends without return syntax, python interpreter will add return None at the end of the function. I change 'print(dice_roll())' to 'dice_roll()'.
In your while loop, if elif else syntax has covered all situations, the code will never go to
user_input = input("Roll again? [Y/N] ")
print(user_input)
So, I just put these two lines in front of 'if elif else'. and remove ' again'.

apparently ran_num is not defined

So I've remade part of my dicegame's code and it's works somewhat decently, however after ROLL'ing the dice and attempting to display the users score, I run in to an error where is says 'name p1_score is not defined'. It says the same thing for the variable p2_score aswell. However I defined p1_score as ran_num+ran_num so I don't get why I'm getting an error.
import random
import time
player_1 = input("")
player_2 = input("")
def rollDice(player_1):
ran_num = random.randint(1,6)
if ran_num == 1:
print("You rolled a",ran_num)
else:
print("You rolled a",ran_num)
p1_score = ran_num+ran_num
def rollDice(player_2):
ran_num = random.randint(1,6)
if ran_num == 1:
print("You rolled a",ran_num)
else:
print("You rolled a",ran_num)
p2_score = ran_num+ran_num
print("Please press ENTER to roll the dice")
input()
rollDice(player_1)
print("Good job",player_1,)
print("Your score is now",p1_score)
time.sleep(5)
print(player_2,"Press ENTER to roll the dice")
input()
rollDice(player_2)
print("Nice work",player_2)
print("Your score is now",p2_score)
def main():
rollDice(player1, player2)
main()
This is a variable scoping issue, you either need to use a global (globals can be dangerous if used incorrectly) the same way you have with player_1 and player_2, OR return from that function and use the returned value for the output.
http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html
"Not affiliated with that website, just did a quick google to see if I could find a resource for you to read so you can understand"
import random
import time
def rollDice():
ran_num = random.randint(1,6)
print("You rolled a " + str(ran_num))
raw_input()
resolved_score = ran_num+ran_num
return str(resolved_score)
player_1 = raw_input("Enter player one name: ")
player_2 = raw_input("Enter player two name: ")
print("Please press ENTER to roll the dice")
raw_input()
p1_result = rollDice()
print("Good job "+player_1)
print("Your score is now "+p1_result)
time.sleep(5)
print(player_2+" Press ENTER to roll the dice")
raw_input()
p2_result = rollDice()
print("Nice work "+player_2)
print("Your score is now "+p2_result)
I've rationalised your code a bit, there were some logic errors. Notice in the def I have a return statement, the return statement adds two numbers together, converts it to a string using str() and I use RETURN to spit the value back out to the calling code. In this case the calling code is first encountered where we see:
p1_result = rollDice()
Now p1_result will equal whatever the ran_num+ran_num resolved to inside the function.

if statement doesnt work python 2.7 using if and while in function

I am using Python 2.7. The program generates a random number and asks the user to guess what it is. The while statements work good. The conditional if statement ends the program without following instructions of print followed by calling the function to see if the user wants to play again.
What makes an if statement not follow instructions? Is there a conflict with the later while statements?
# generate random number between 1 & 9
# have user guess the number, then
# tell them if they guessed too low,
# too high, or exactly right
# keep the game going until user types "exit"
# track how many guesses the user has taken, and when game ends, print it out
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
guessThis()
elif wieder == "N":
print ("Have a day")
elif wieder != "Y" or "N":
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
while findout > a:
print ("too high")
findout = int(input("Enter a number from 1 to 9 "))
i += 1
while findout < a:
print ("too low")
findout = int(input("Enter a number from 1 to 9 "))
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Two issues (might be more):
wieder != "Y" or "N": you can't do that, you probably meant to do: wieder not in ["Y", "N"]:
When you declare findout inside a function - it will not be recognized outside. If you want it to be accessed from the outside - create it outside and pass it to the function, or alternatively, make the function return the value that you want back to the caller. Same goes for i.
Comment: regards #1, since you already checked both for 'Y' and 'N', the last condition can be modified from elif wieder != "Y" or "N": to a simple else
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = raw_input("Do you wish to play again? Y or N ")
if wieder == 'Y':
guessThis()
elif wieder == 'N':
print ("Have a day")
elif wieder != 'Y' or 'N':
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
if findout > a:
print ("too high")
guessThis()
i += 1
if findout < a:
print ("too low")
guessThis()
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Replace guessThis() and everything after with this:
def guessThis():
findout = int(input("Enter a number from 1 to 9 "))
i = 1
#Keep going until win condition reached
while findout != a:
#too high guess
if findout > a:
print ("too high")
#too low guess
if findout < a:
print ("too low")
#get next guess
findout = int(input("Enter a number from 1 to 9 "))
i += 1
#We got out of the while, so the game is done :)
print ("You got it correct")
playAgain()
guessThis()
As yours is currently it will not work if the user guesses too high and then too low.
The main problem was that none of your code was executed in the right order cause your indents were off. You need to put the checking logic in the guessThis() function.
Also there is are issues on this function:
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
#need to reset a when playing again
a = random.randint(1, 9)
guessThis()
elif wieder == "N":
print ("Have a day")
#because we have already checked (Y || N), simple 'else' gives us (!Y && !N)
else:
wieder = input("Do you wish to play again? Y or N ")
The !"Y" or "N" doesn't work quite like you expect it does, and I assume you want a new value of a for a new game

Categories