random.randint generating incorrect numbers [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
So i am making a quick dice roller (for D&D) and when I try to roll dice it only generates numbers from 1 to 4!
import random
def d4():
x = (random.randint(1,4))
print(x)
def d6():
x = (random.randint(1,6))
print(x)
def d8():
x = (random.randint(1,8))
print(x)
def d10():
x = (random.randint(1,10))
print(x)
def d12():
x = (random.randint(1,12))
print(x)
def d20():
x = (random.randint(1,20))
print(x)
def d100():
x = (random.randint(1,100))
print(x)
choice = input("What dice will you roll: ")
if choice == "d4" or "4":
d4()
elif choice == "d6" or "6":
d6()
elif choice == "d8" or "8":
d8()
elif choice == "d10" or "10":
d10()
elif choice == "d12" or "12":
d12()
elif choice == "d20" or "20":
d20()
elif choice == "d100" or "100":
d100()
else:
print(random.randint(1,20))
For example when I put my input as d100 I can only get 1,2,3, or 4!
what on earth is going on?!

Your if statements are not correct, they should be like this:
if choice == "d4" or choice == "4":
d4()
The way you did it makes "4" evaluate to True, so the if always enters to the first statement, which is for D4.

Related

Python - How do I get the defined variable from one function to another function?

I have simplified it to this:
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
def two_player_word():
print("2")
elif gameinput == "1":
def one_player_word():
print("1")
def hangman():
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman()
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()
I had previously defined gameinput in the 'hang()' it collects the user input and so on.
My problem is in the 'hangman()' I need gameinput again to make the variable word (its made so a user can either make a word (two_player_word) or one player when it generates a random word (one_player_word()
It works perfectly without gameinput being in a function but after the player either wins or loses I want it to let the user decide if they want to change gamemode or not as shown in main().
There is a lot more code but figured it would be easier to try figure out the problem using just this.
Just pass the gameinput from hang into hangman as an argument.
def hang():
while True:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput not in ("1", "2"):
continue
hangman(gameinput)
break
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
There are two problems that cause your code to fail (besides indentation).
You are defining nested functions (one/two_player_word) which you then try to call from outside the function (where they are not defined). You can change this by defining the functions outside the function hang().
hangman() uses the gameinput variable but it's not defined nor provided. You can change this by adding it as a parameter to the function call.
Your adjusted code could work like this:
import time
def one_player_word():
print("1")
def two_player_word():
print("2")
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
two_player_word()
elif gameinput == "1":
one_player_word()
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman(gameoverinput)
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()

Program not allowing chosen number output to run

This is the code that does not seem to work:
choice = input()
if input() == "1":
circle()
elif input() == "2":
square()
elif input() == "3":
triangle()
while input() != ("1" or "2" or "3"):
print("You have not chosen a correct number. Please try again.")
choice = input()
if input() == "1":
circle()
elif input() == "2":
square()
elif input() == "3":
triangle()
Basically the part that checks the correct number has been input does not seem to work and I don't know why, its only a logic error and i think its something to do with this part:
while input() != ("1" or "2" or "3"):
print("You have not chosen a correct number. Please try again.")
while input() != ("1" or "2" or "3"): is not correct.
("1" or "2" or "3") is a logical statement and resolves to the first non-empty or non-zero item:
>>> "1" or "2" or "3"
'1'
So the statement resolves to:
while input() != '1':
To correct it, use not in and a tuple:
while input() not in ("1", "2", "3"):
Alternatively, use the following pattern when asking for input and have a dispatch table of functions to eliminate the multiple if statements:
def circle():
print('circle')
def square():
print('square')
def triangle():
print('triangle')
funcs = {'1':circle,
'2':square,
'3':triangle}
while True:
choice = input()
if choice in ('1','2','3'):
break
print("You have not chosen a correct number. Please try again.")
funcs[choice]()
It looks like you're storing the input as choice but then calling input() again instead of using the value you already read.
Additionally, you can simplify this code significantly.
You should instead do the following:
choice = input()
while choice not in ("1", "2" ,"3"):
print("You have not chosen a correct number. Please try again.")
choice = input()
if choice == "1":
circle()
elif choice == "2":
square()
elif choice == "3":
triangle()

invalid syntax with elif and else

Whenever I try to use elif and else after if, it says invalid syntax. For example:
if number == "1"
print("123213")
elif number == "2"
print("23423")
else number == "3"
print("324234")
There are three mistakes
: is missing
Indent is missing
else cannot have a conditional
The code can be re-written as
if number == "1":
print("123213")
elif number == "2":
print("23423")
elif number == "3":
print("324234")
Complete working code
number = input("Enter a number - ")
if number == "1":
print("123213")
elif number == "2":
print("23423")
elif number == "3":
print("324234")
Output
Enter a number - 1
123213

A local or global name can not be found error [duplicate]

This question already has answers here:
Python NameError from contents of a variable
(2 answers)
Closed 8 years ago.
I'm trying to make a simple rock paper scissors game, and I get an error with in the line, guess = input. It says I need to define the function or variable before I use it in this way and I am unsure of how I can do that. This is using Python/JES programming
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
guess = input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
return user_guess()
def is_valid_guess(guess):
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
Using raw_input instead of input seems to solve the problem.
guess = raw_input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
and also in
answer = raw_input("Would you like to play again? Enter 'y' for yes or 'n' for no: ")
I'm using Python 2.7.x

why do i get "Attribute Error: 'int' object has no attribute 'lower'"?

i need x to be an integer so my next part of code works, but as soon as i remove quotation marks around 0,1 or 2 where it says "making input readable for computer" i get this error message.
from random import randint
# Input
print("Rock: R Paper: P Scissors: S")
x = input("Please pick your choice: ")
y = randint(0,2)
#Making input readable for computer
if x.lower() == "r":
x = 0;
if x.lower() == "p":
x = "1";
if x.lower() == "s":
x = "2";
print("value entered ", x, "value generated ", y)
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 0 and y == 1:
print("Computer wins!")
if x == 0 and y == 2:
print("You won!")
if x == 1 and y == 0:
print("You won!")
if x == 1 and y == 2:
print("Computer wins!")
if x == 2 and y == 0:
print("Computer wins!")
if x == 2 and y == 1:
print("You won!")
You should be using elif here:
if x.lower() == "r":
x = 0
elif x.lower() == "p":
x = 1
elif x.lower() == "s":
x = 2
Otherwise, all three conditions are evaluated with every run. Meaning, if the first passes, then x will be an integer for the second.
Also, you should write your code like this:
x = x.lower() # Put this up here
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
That way, you don't call str.lower multiple times.
Lastly, Python does not use semicolons.
You are calling x.lower() after you assign x to an integer.
Also, you should probably not use the same variable for the integer and the input string.
With a couple of dictionaries this code will be short and concise:
x_conversion = {'r':0, 'p':1, 's': 2}
x = x_conversion[x.lower()]
or list(in this particular case)
x_conversion=['r', 'p', 's]
x = x_conversion.index(x.lower())
And for winner
winner_choice = {(0,1): 'Computer', (1, 2): 'You', ...}
winner = winner_choice[(x, y)]
Don't forget try/except and you'll have your results in much shorter and more readable code
iCodez answer is the one, but you should just use the strings, like the following, if you are not using the number conversion to factor your print statement, not both.
Edit: Had to change what y was, oops
x = raw_input("Please pick your choice: ").lower()
y = choice(['r','p','s'])
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 'r' and y == 'p':
print("Computer wins!")
elif x == 'r' and y == 's':
print("You won!")
elif x == 'p' and y == 'r':
print("You won!")
elif x == 'p' and y == 's':
print("Computer wins!")
elif x == 's' and y == 'r':
print("Computer wins!")
elif x == 's' and y == 'p':
print("You won!")
Now if you want to go with the convertion to integer then you could just use this:
y = randint(0,2)
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
print ['tie', 'you win', 'they win'][x-y]
And semicolons are not needed in Python, but you can still use them if it makes you comfortable.
Edit: Just for fun.
import random
pick = ['r', 'p', 's']
x = ""
while x not in pick:
x = str(raw_input("r, p, or s? ")).lower()
print ['tie', 'y win', 'y win', 'x win', 'x win'][ord(x)-ord(random.choice(pick))]
Use raw_input() instead of input.
Also this should be:
if x.lower() == "r":
x = "0"

Categories