Dice Simulator project in Python 3 - python-3.x

My code works to quit the program for my 'elif' and 'else' statements, but when I input 'yes', I'm stuck in this input loop where anything I input still rolls the dice. How can I get out of the program by inputting 'no', once I've already inputted 'yes' and entered the loop?
import random
min = 1
max = 6
prompt = "Roll dice? Type yes or no. "
roll_dice = input(prompt)
while roll_dice:
if roll_dice == "yes":
print ("you rolled", random.randint(min, max), random.randint(min, max))
input(prompt)
elif roll_dice == "no":
print ("see you later!")
break
else:
print ("invalid answer")
break

Instead of just doing:
input(prompt)
Which does nothing with the given input which means
roll_dice will always be equal to yes and you will be stuck in an infinite loop.
You should use:
roll_dice = input(prompt)
which sets roll_dice to the new value, and hence lets you exit out of the loop.

You can modify the code in this manner:
while roll_dice =="yes":
print ("you rolled", random.randint(min, max), random.randint(min, max))
roll_dice = input(prompt)
You must include roll_dice for getting the return value from the input function and validating if the response is yes, no or invalid.
In your code, input returns a value but that value is never checked after the if statement is executed once.
while roll_dice =="yes":
print ("you rolled", random.randint(min, max), random.randint(min, max))
input(prompt)

Related

Python 3.6 elif syntax error

using a nested if statement and my indentation seems correct thru out yet still reviving a syntax error.thank you
# FIGHT Dragons
if ch3 in ['y', 'Y', 'Yes', 'YES', 'yes']:
# WITH SWORD
if sword == 1:
print ("You only have a sword to fight with!")
print ("You quickly jab the Dragon in it's chest and gain an advantage")
time.sleep(2)
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print (" Fighting... ")
print (" YOU MUST HIT ABOVE A 5 TO KILL THE DRAGON ")
print ("IF THE DRAGON HITS HIGHER THAN YOU, YOU WILL DIE")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
time.sleep(2)
fdmg1 = int(random.randint(3, 10))
edmg1 = int(random.randint(1, 5))
print ("you hit a", fdmg1)
print ("the dragon hits a", edmg1)
time.sleep(2)
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
return complete
this is where i run into a syntax error
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
return complete
else:
print ("You killed the drgon!")
complete = 1
return complete
Your return must be at the end of the if...elif...else statement. This works :
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
else:
print ("You killed the drgon!")
complete = 1
return complete
Note that if the first if-condition is True, Python won't check for the subsequent ones.

How to make the program stop asking for the "4-digit number" if the user has already guessed the number, and make the program display "You Win!"

The code here in all in all fulfills its purpose, except that I cannot get the code to end and print "You Win!" after all four numbers have been guesses. We have tried using break statements, switching "ifs" with "whiles" and "elifs" as well as changing variables
import random
#Gets 4 random single digits to be guesses
n1 = random.randint (0,9)
n2 = random.randint (0,9)
n3 = random.randint (0,9)
n4 = random.randint (0,9)
wrong_guesses = 0
print ("I'm thinking of a 4-digit code. Guess what it is!")
print ("X = wrong guess, O = right guess")
guess = int(input("Enter your 4-number digit here:"))
#Guesses the first (leftmost) number
if guess // 1000 % 10 != n1:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
#Guesses the second (second from the left) number
if guess // 100 % 10 != n2:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
#Guesses the third (second from right) number
if guess // 10 % 10 != n3:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
#Guesses the last (rightmost) number
if guess // 1 % 10 != n4:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if wrong_guesses == 0:
print ("You win!")
while wrong_guesses != 0:
guess = int(input("Enter your 4-digit code here:"))
#Display O if number is correct, X if otherwise
if guess // 1000 % 10 != n1:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess // 100 % 10 != n2:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess // 10 % 10 != n3:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess // 1 % 10 != n4:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess == n1 and guess == n2 and guess == n3 and guess == n4:
print ("You win!")
Here is the part where the code fails to end. Instead of displaying validation of a right answer, the code just keeps on asking for more numbers, evem if the numbers were already guessed
I think the problem lies when you write :
while wrong_guesses != 0:
guess = int(input("Enter your 4-digit code here:"))
Since you have no way to change wrong_guesses value in your loop, you're entering an infinite loop.
I'd try to verify it by throwing some debug print in this loop, to see if this is the case.
Plus, don't "try using break statements, switching "ifs" with "whiles" and "elifs" as well as changing variables" without understanding what you are doing.
Hope this helps.

Simple calculator works in Python 2 but not 3

This calculator works in Python 2:
print ("First calculator!")
print ("")
firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
print ("You mistyped")
exit(0)
print ("")
secondnum=input ("Insert the second number: ")
if operation == 1:
print ("The result is:", firstnum+secondnum)
if operation == 2:
print ("The result is:", firstnum-secondnum)
if operation == 3:
print ("The result is:", firstnum*secondnum)
if operation == 4:
print ("The result is:", firstnum/secondnum)
But in Python 3 the script does nothing after accepting input.
--UPDATE--
After fixing thanks the help of #moses-koledoye, I'll post the final source code, it could be help for some other newbie.
print ("First calculator!")
print ("")
firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
print ("You mistyped")
exit(0)
print ("")
secondnum=input ("Insert the second number: ")
firstnum=int(firstnum)
secondnum=int(secondnum)
print ("")
if operation == "1":
print ("The result is:", firstnum+secondnum)
elif operation == "2":
print ("The result is:", firstnum-secondnum)
elif operation == "3":
print ("The result is:", firstnum*secondnum)
elif operation == "4":
print ("The result is:", firstnum/secondnum)
You're comparing strings with integers:
if operation == 1 # '1' == 1
will always be False, so none of the if blocks is executed.
Do a string-string comparison instead:
if operation == '1'
And when the if block conditions are fixed, others bugs will show up:
firstnum + secondnum
This will concat your strings and not perform a numerical operation as you intend, while operation -, * and / will raise TypeError. You should cast your operands, firstnum and secondnum to the appropriate type: float or int.
Besides, you could also chain all the if clauses into one if-elif clause

Variable not Defined in Python 3.5.1

I am a new coder with Python and I was wondering how I can fix this bug. Every time i put in the correct input in the code that I have, it spits out an error message, like so.
The code
total = 12
print ("I will play a game, you will choose 1, 2, or 3, and I will do the same, and I should always win, do you want to play?")
yesnoA = input("Yes or No?")
if yesnoA == yes:
print ("Yay, your turn!")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
yesnoB = input("Ok, you sure?")
if yesnoB == yes:
print ("Yay, your turn")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
print ("Well, goodbye")
The Output
Yes or No?yes
Traceback (most recent call last):
File "C:/Users/*user*/Desktop/Code/Python/Nim Game.py", line 5, in <module>
if yesnoA == yes:
NameError: name 'yes' is not defined
This is in version 3.5.1
You need to either declare a variable yes with a value 'yes', or compare your variable yesnoA with a string 'yes'. Maybe something like this:
if yesnoA.lower() == 'yes': # using lower(), so that user's input is case insensitive
# do the rest of your work
Your code afterwards has some more issues. I will give you a clue. input always returns the user's input as string. So if you need integer from user, you will have to convert the user input into integer using int(your_int_as_string) like so:
turnAA = int(input('Your First Move'))
# turnAA is now an integer, provided the user entered valid integer value
Your take from this question on SO:
Look at the Traceback. It says clearly which line the error is in, and also what the error is. In your case it is NameError
Take a look at docs for NameError
Study this tutorial. It will help you get used to with some basic errors commonly encountered.
You have not defined the variable yes. You should do something like:
yes = "Yes"
At the start of the code
You're attempting to compare yesnoA to a variable named yes, which, indeed was not defined, instead of the string literal 'yes' (note the quotes!). Add the quotes and you should be fine:
if yesnoA == 'yes':
# Here --^---^

Python variable checking

How would I get Python to check a variable to see if it is an integer and below a specific number then carry on depending on the result perhaps breaking from a loop.
so something roughly like this:
x = input
if x is integer AND below 10:
print ("X is a number below 10")
break from loop
elif x is NOT an integer:
print ("X is not an integer try again")
ask again
Else:
print ("Error")
ask again
pretty sure this works :D thanks
while True:
x = input("Enter Something: ") #user input
if x.isdigit() == True:
if (int(x)>=1) and (int(x)<=2): #if it is 1 or 2
print (x)
break
elif (int(x)>2): #or if its above 2
print ("To Large")
else:
print ("Else")
elif x.isdigit() == False: #data non integer
print ("please try again")
else:
print ("ERROR") #error with input
print ("Hello") #show the loop broke correctly

Resources