How to add variables - python

Im making a odds even code i'm struggling to add variables
Im pretty new to coding
from random import *
print("This is the game odds, evens")
game = input("Do you choose odds or evens?")
number = input("What number do you choose")
MyNumber = randint(1,10)
num = game + MyNumber
if num % 2 == 0:
print("even")
if num % 2 == 1:
print("odd")
I got
"Traceback (most recent call last):
File "main.py", line 6, in
num = game + MyNumber
TypeError: must be str, not int"
I don't know how to fix it

use int(game) instead of just game to convert it to numeric

My suggestion for your game:
from random import randint
game = input("Odds (1) or evens (2). Please choose 1 or 2.")
my_random = randint(1,10)
print "My random: {}".format(my_random)
if (my_random % 2 == 0 and game == 2) or (my_random % 2 != 0 and game == 1):
print True
else:
print False

The input method by default gets the input as str so we need to convert it to int. Just make this change to your code and you should be fine.
game = int(input("Do you choose odds or evens?"))
number = int(input("What number do you choose"))
Good Luck!!

I understand where you may have been confused. Theoretically if the user enters 6 and the random number is 3 you would expect to get 9 and the code shouldn't break. However, an input will return a string. So the program now thinks you are trying to add 3 + '6'.
To fix this, you can cast the result of the input to int(game) int(number)

Related

I am a beginner and i was building a card game as little project . i am having a problem with while loop ,plz guide me

in below code i have created function named cards_game in which it will give you random card which will be added to cards list . if we input "hit" then it will give you random no. which simultaneously added to the cards list then [ if you input "stay" then it will stop while loop and will check the sum and if the sum >= 21 then it will stop while loop and run next code ] <--- but this is problem , it repeats the same line in last 'else' condition. If you input hit it will ask for it again rather than proceeding..
sorry if i have elaborated my question badly ...but this my 1st time on this platform
please pardon me and guide me , i would be very grateful for you .
def cards_game():
cards = []
seed(1)
sequence= [i for i in range(10)]
print ("Now you will get to select 1 random card \n but to get that there is 1 code called \"hit\" \nAnd to not to pick card there will be code called \"stay\" ")
x = True
command = input("what would you like to do?\n>>> ")
while x :
if command == 'hit':
cards.append(sample(sequence,1))
elif command == 'stay':
"ok"
sum = 0
for i in cards:
sum = sum + i
if sum >= 21:
x = False
else:
print ("too bad!\n I think you are anout to spend your \nWhole life playing with me \nHAHHHAHHAHAHAAAAAAAAAAHAHAHAAHHAAAA")
else:
print("Bad command")
cards_game()
Taking input one time is one of the issue, include it in your while loop,
....
while x :
command = input("what would you like to do?\n>>> ")
if command == 'hit':
....
You don't have to make sequence list, simply use randint() funciton
import random
....
if command == 'hit':
cards.append(random.randint(1,10))
....
The problem is that you only ask the player once what move to do. The command input should be in the loop.
from random import *
def cards_game():
cards = []
seed(1)
sequence= [i for i in range(10)]
print ("Now you will get to select 1 random card \n but to get that there is 1 code called \"hit\" \nAnd to not to pick card there will be code called \"stay\" ")
x = True
while x :
command = input("what would you like to do?\n>>> ")
if command == 'hit':
cards.append(sample(sequence,1))
elif command == 'stay':
"ok"
som = 0
for i in cards:
som = som + i
if som >= 21:
x = False
else:
print ("too bad!\n I think you are anout to spend your \nWhole life playing with me \nHAHHHAHHAHAHAAAAAAAAAAHAHAHAAHHAAAA")
else:
print("Bad command")
cards_game()
Your code still doesn't compile, because the elements in cards are a list, since sample returns a list. I would advise you to replace it by choice, in random module too.
cards.append(choice(sequence))

Do you know what is wrong with this simple script

All Im trying to do is make n a random number, if the user gets it correct it outputs "You got it!" but no matter what is always displays as if I got it wrong, even when I answered n
import random
n = random.randint(1,2)
guess = input("1 or 2?")
if guess == n:
print("You won!")
In python, "10" == 10 is False. You must compare the same type, like 10 == 10 or "10" == "10".
input() returns a str, when random.randint() returns an int, so guess == n will always be False.
This is an easy way to solve your issue :
guess = int(input("1 or 2?"))
or
n = str(random.randint(1, 2))
or
n = random.choice("12")

I got stuck on this exercise can't figure the True/False part

I got some homework to do and I got stuck with this code. I have no idea how to continue.
This is what I'm suppose to do:
generate_sequence - Will generate a list of random numbers between 1 to 101. The list
length will be difficulty.
get_list_from_user - Will return a list of numbers prompted from the user. The list length
will be in the size of difficulty.
is_list_equal - A function to compare two lists if they are equal. The function will return
True / False.
play - Will call the functions above and play the game. Will return True / False if the user
lost or won.
(Sorry for copy/pasting. My English is not so good.)
import random
difficulty = 101
secret_number = 6
def generate_number():
global secret_number
secret_number = random.randint(0, difficulty)
def get_guess_from_user():
return input( "Please choose number between 1 to " + str(difficulty))
def compare_results(userInput):
isSame = False
if(secret_number == userInput):
isSame = True
return isSame
def play():
generate_number()
userInput = get_guess_from_user()
isSame = compare_results(userInput)
print("number generated is: " + str(secret_number))
print(isSame)
play()
Your "problem" is, that if(secret_number == userInput): is currently comparing an int to a str, because the result of input() is always a str, even if the input is numeric. An int and a str are never equal, thus isSame will always be False.
You have to cast the user input to int somewhere along the way before or during the comparison.
e.g.:
def get_guess_from_user():
return int(input( "Please choose number between 1 to " + str(difficulty)))
# ^^^
Otherwise, your program seems to do what you are describing.
You could save some lines of code by writing:
def compare_results(userInput):
return (secret_number == userInput)
I took the liberty to rewrite your application w/o global variables:
import random
def generate_number(difficulty):
return random.randint(1, difficulty)
def get_guess_from_user(difficulty):
return int(input( "Please choose number between 1 to {}".format(difficulty)))
def play(difficulty):
secret_number = generate_number(difficulty)
user_input = get_guess_from_user(difficulty)
is_same = (secret_number == user_input)
print("number generated is: {}".format(secret_number))
print("Your guess was {}".format( "correct :)" if is_same else "not correct :(" ))
play(5)
Note: I also changed random.randint(0, difficulty) to random.randint(1, difficulty), because the lower part is also inclusive, meaning that it could return 0. When prompting the user for a number between 1 and 5, the user might be surprised that the correct number was 0 instead.
See the docs:
random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

Bulls and Cows Game - Python programming for beginners

I am a beginer programming Python and for a evaluation assignment I was asked to program a Bulls and Cows game using very simple code.
I have some code already written, but can't seem to make the function work. The function should be able to compare the four digit number the user wrote (num_guess) to the random number generated by the program (stored in a list called num).
I can input the value, but have no further feedback from the program.
Could you please check my code and help me?
Thanks!
import random
guess = raw_input("What is your guess? ")
if (len(guess) != 4):
guess = raw_input("Your guess must be 4 characters long! What is your guess?")
num_guess = []
for c in guess:
num_guess.append(int(c))
def compare(num_guess):
num = []
for i in range(4):
n = random.randint(0, 9)
while n in num:
n = random.randint(0, 9)
num.append(n)
if num_guess == num:
print "Congratulations! Your guess is correct"
output = []
if num_guess[0] == num [0]:
output.append["B"]
else:
output.append["C"]
if num_guess[1] == num [1]:
output.append["B"]
else:
output.append["C"]
if num_guess[2] == num [2]:
output.append["B"]
else:
output.append["C"]
if num_guess[3] == num [3]:
output.append["B"]
else:
output.append["C"]
return output
nguesses = 0
while nguesses < 11:
nguesses = nguesses + 1, compare
Without giving you the corrected code you will want to call the function at the end of your code. If you want to see result do:
print compare(num_guess)
This will show you an additional issue with all of these parts
output.append[]
I'm not sure if it is just how you pasted it but you may want to clean up the indentation. Also:
while n in num:
n = random.randint(0, 9)
This above section is not needed. Have fun and figure out how to make it work well.

Using random.randint help in python

The following code is my attempt at simulating a lottery.
import random
def lottery(numbers):
lottoNumbers = [randint('0,100') for count in range(3)]
if numbers == lottoNumbers:
print('YOU WIN $10,000')
else:
print('YOU LOSE,DUN DUN DUNNN!')
return numbers
def main():
numbers = int(input('Enter a number: '))
if numbers == lottoNumbers:
numbers = lottery(numbers)
else:
numbers = lottery(numbers)
main()
Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys?
Thanks for your help everyone.
You seem a bit confused about what the role of the arguments in a function are. You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.
Also, the function is trying to return x, when x hasn't been assigned within the function. Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x.
Here's a quick example I've done where you pass their three numbers as a list as an argument to the function.
import random
theirNumbers=[5,24,67]
def checkNumbers(theirNumbers):
lottoNumbers = []
for count in range(3)
lottoNumbers.append(random.randint(0,100))
winning = True
for number in theirNumbers:
if not each in lottoNumbers: winning=False
if winning == True: print("Winner!")
There are a few things wrong with your implementation, to name a few:
if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so:
def randm():
return return_value
You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so:
list_name = [randint(0,100) for x in range(x)]
This will generate randint(0,100) x times in a list, which will allow you to access all the values later.
To fix up your code as close to what you were attempting as possible I would do:
import random
def randm(user_numbers):
number = []
for count in range(3):
number.append(random.randint(0, 100))
print(number)
return user_numbers == number
if randm(x):
print('WINNER')
If you are looking for a very pythonic way of doing this task,
you might want to try something like this:
from random import randint
def doLotto(numbers):
# make the lotto number list
lottoNumbers = [randint(0,100) for x in range(len(numbers))]
# check to see if the numbers were equal to the lotto numbers
if numbers == lottoNumbers:
print("You are WinRar!")
else:
print("You Lose!")
I'm assuming from your code (the print() specifically) that you are using python 3.x+
Try to post your whole code. Also mind the indentation when posting, there it looks like the definition of your function would be empty.
I'd do it like this:
import random
def lottery():
win = True
for i in range(3):
guess = random.randint(1,100)
if int(raw_input("Please enter a number...")) != guess:
win = False
break
return win
Let so do this in few steps.
First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs.
First lets create function to make lottery:
def makeLottery(slotCount, maxNumber):
return tuple(random.randint(1,maxNumber) for slot in range(slotCount))
Next lets create function to ask user's guess:
def askGuess(slotCount, maxNumber):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = parseGuess(userInput,slotCount,maxNumber)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))
return numbers
here we are using another function and custom exception class, lets create them:
def parseGuess(userInput, slotCount,maxNumber):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
return numbers
class GuessError(Exception):
def __init__(self,wrongCount = False, notInRange = False):
super(GuessError,self).__init__()
self.wrongCount = wrongCount
self.notInRange = notInRange
and finally function to check solution and conratulate user if he will win:
def checkGuess(lottery,userGuess):
if lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
As you can see many functions here uses common data to work. So it should suggest you to collect whole code in single class, let's do it:
class Lottery(object):
def __init__(self, slotCount, maxNumber):
self.slotCount = slotCount
self.maxNumber = maxNumber
self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))
def askGuess(self):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = self.parseGuess(userInput)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
continue
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
continue
return numbers
def parseGuess(self,userInput):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
return numbers
def askAndCheck(self):
userGuess = self.askGuess()
if self.lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
finally lets check how it works:
>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123 asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!

Categories

Resources