Python: Issue with Elif Break - python

I'm trying to make a simple program that will take all of your lottery numbers, and compare them (using set intersect) with the winning numbers that you input.
I've gotten the groundwork laid where you enter your numbers, it gets submitted to a sublist, which will then be converted into five separate sets, which will be used to compare. However, when you run the script, the while loop will not break when the length of the list is 5 (this is the goal).
Can someone explain what I'm doing wrong? Or maybe even a better way of working this whole program. I'm relatively new to the world of Python, I'm just diving in, and trying to make this program work.
# Start Program
def set_convert(list):
conversion = set(list)
return conversion
def comparison(winning_numbers, my_numbers):
pass
def main():
print('Welcome to the Lottery Checker v1.0!')
winning_numbers = [int(x) for x in input('Enter the winning numbers(Sep w/ Spaces): ').split()]
winning_set = set_convert(winning_numbers)
my_numbers = []
while True:
numbers = [int(x) for x in input('Enter your numbers(Sep w/ Spaces Max: 5): ').split()]
if len(numbers) == 6:
my_numbers.append(numbers)
print('Added! Want to add more?')
elif len(my_numbers) == 5:
break
else:
pass
else:
pass
print('Here are your numbers: {}. Good luck! :-)'.format(my_numbers))
main()

Replace
elif len(my_numbers) == 5:
with
elif len(numbers) == 5:
Also, it is advisable that you don't use the keyword list as an argument for the function set_convert. Rather, define it as:
def set_convert(mylist):
conversion = set(mylist)
return conversion
And finally, you don't need to pass in my_numbers and winning_numbers into the function comparison as arguments since they are available in the outer scope.

Related

Dice and gamble game Python

Hello I have a problem in my code. I want to check valu of ran_dice in method main but I dont know how I can do. For example I wrote ran_dice(2) it return 2 random integers and I want to check these two integers equals or not. Can I do in main method ? How ?
Printing ran_dice(2) should do the trick.
Edit according to the comment:
a,b=ran_dice(2)
if a==b:
# code to stop
As another comment mentioned, however, the ran_dice(s) function is a little dangerous as the amount of things it returns varies. It's good practice to have a program return a consistent amount of things. You could return the values in a list, and the size of the list could vary, but at least you're always returning one list.
Here is an example, you could return the dice values in a list. So you can adjust the returned number of dice as you like, and compare the result.
import random
def ran_dice(s):
if s==1:
a=random.randint(1,6)
return [a]
elif s==2:
a=random.randint(1,6)
b=random.randint(1,6)
return [a,b]
def main():
credit=100
print('Welcome user, you have ', credit,'credits.')
number=int(input('How much do you want to gamble?: '))
while number <0 or number>100:
print('You need to give a positive integer no more than your credit.')
number=int(input('How much do you want to gamble?: '))
result = ran_dice(2)
print ("dice=", result)
firstdice = 0
for dice in result:
if firstdice == 0:
firstdice = dice
elif dice == firstdice:
print("equal")
else:
print("different")
if result[0] == result[1]:
print("equal")
main()

Trying to locate syntax error in python while loop

very very new beginner here - just started learning today! stumped on what the syntax error is here:
import random
x = random.randrange(7)
user_start = "yes"
user_start_input = str(input("type 'yes' to generate random number. "))
while user_start_input == user_input:
print("your random dice number is " + str(x))
user_start_input = input("roll again?")
if user_start_input != user_input:
break
print("done")
The error message is:
File "/Users/joel/Documents/Learning Python/Dice.py", line 12
while user_start_input == user_input:
^
SyntaxError: invalid syntax
what am I doing wrong?
First off we're (those that wish to answer) missing some information, while is on line 5 where as the error is being reported with while on line 12, there's plenty that could be causing an error to pop on a following line; eg. missing quote. Looks like G. Anderson already eluded to that last point, as far as errors usually being from a preceding line. My suggestion in this case would be to find an developer friendly text editor (IDE) that'll point out minor typos through syntax-highlighting; Atom is pretty groovy, especially with a few addons, but there's plenty of other text editors to play with.
Second, as commented by CoffeeTableEspresso the tabs are non-existent in your code snip! If your source code looks identical to what has been posted, then your bug-stomping has only just begun.
Third, because ya had stated that Python is not your first language it might be helpful, if not now then certainly in the future, to know of __doc__ strings, eg...
>>> print(random.randrange.__doc__)
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
... many of the things within Python are documented and accessible via the __doc__ method, which can also be accessed with help(), eg. help(random.randrange), and it is possible to write your own with the following syntax...
def test_func(arg):
"""
This is a __doc__ string
"""
print("arg -> {0}".format(arg))
And finally, well for now, it's a good idea when writing in an unfamiliar language to use copious comments and split things up into smaller bits that express your intentions; for example...
#!/usr/bin/env python
import random
def dice(sides = 6):
"""
Returns random int between `1` and `sides`
"""
return random.randrange(start = 1, stop = int(sides) + 1, step = 1)
def prompt(message, expected):
"""
Returns `True` if user input matches `expected`
"""
return expected == str(input("{0} ".format(message)))
def main_loop():
"""
Returns list of `dice(...)` results, list length depends
upon number of times `prompt(...)` returns `True`
"""
roll_results = []
user_start = 'yes'
# Set message for first run of loop
message = "Type '{0}' to roll the dice".format(user_start)
while prompt(message = message, expected = user_start):
# Save dice output to variable for later use and
# append to list of rolls that will be returned
roll = dice(sides = 6)
roll_results.append(roll)
# For now just print each roll, but this is one
# aria to expand upon with your own edits
print("Rolled {0}".format(roll))
# Set new message line for following loop iterations
message = 'Roll again?'
return roll_results
# Do stuff if script is run directly instead of imported as a module
if __name__ == '__main__':
main_loop()
P.S. keep at it, eventually all the learnings'll start to click and the following RP related example classes will make more since...
#!/usr/bin/env python
from __future__ import range
import random
class DiceBag(dict):
"""
DiceBag is a collection of short-cuts to `random.randrange`.
- `selection`, list of `n` sided dice, eg `[4, 20]` would _stock_ bag with d4 and d20
"""
def __init__(self, selection = [2, 4, 20], **kwargs):
super(DiceBag, self).__init__(**kwargs)
self.update(selection = selection)
def dice(self, sides = 6):
"""
Returns random int between `1` and `sides`
"""
return random.randrange(start = 1, stop = int(sides) + 1, step = 1)
def handfull_of(self, dice = {}):
"""
Returns `dict` with lists of dice rolls
## Example
dice_bag = DiceBag()
toss_results = dice_bag.handfull_of({20: 1, 4: 2})
Should return results of one `d20` and two `d4` such as
{
20: [18],
4: [1, 3]
}
"""
output = {}
for sides, count in dice.items():
if sides not in self['selection']:
continue
rolls = []
for roll in range(count):
rolls.append(self.dice(sides))
output[sides] = rolls
if not output:
raise ValueError("No dice in bag matching sizes -> {0}".format(dice.keys()))
return output
"""
Short cuts for dice of a `n` sides, expand upon it if you wish
"""
#property
def coin(self):
return self.dice(sides = 1)
#property
def d4(self):
return self.dice(sides = 4)
#property
def d6(self):
return self.dice(sides = 6)
class Flail(DiceBag):
def __init__(self, damage_modifier = 0, damage_dice = {'sides': 6, 'count': 2}, **kwargs):
super(Flail, self).__init__(selection = [damage_dice['sides'], 20], **kwargs)
self.update(damage_modifier = damage_modifier)
self.update(damage_dice = damage_dice)
def attack(self, attack_modifier = 0):
"""
Returns `dict` with `hit` chance + `attack_modifier`
and `damage` rolls + `self['damage_modifier']`
"""
rolls = self.handfull_of(dice = {
20: 1,
self['damage_dice']['sides']: self['damage_dice']['count']
})
return {
'hit': rolls[20][0] + attack_modifier,
'damage': sum(rolls[self['damage_dice']['sides']]) + self['damage_modifier']
}
Updates
Here's what your code block may look like with proper indentation...
import random
x = random.randrange(7)
user_start = "yes"
user_start_input = input("type 'yes' to generate random number. ")
while user_start_input == user_input:
print("your random dice number is " + str(x))
user_start_input = input("roll again?")
print("done")
... and here's what a working version might look like...
import random
message = "type 'yes' to generate random number. "
expected = "yes"
while input(message) == expected:
x = random.randrange(7)
print("your random dice number is {num}".format(num = x))
message = "roll again? "
print("done")
... there's little reason to use an if something break when using while to do the same kinda thing, well given the current question's code sample.
Moving the assignment of x to be within the loop ensures that there's a chance of a new number on each iteration, while not stated I've a feeling that that was your intent.
Using input(message) and updating the message displayed instead hopefully makes sense. Though I'm not sure why you where wrapping things within str(), didn't seem to make a bit of difference when I tested.
First, it seems like you've mixed up the two variable names user_start and user_input, so those need to be changed to the same variable name.
Next, Python structures code with indentation: so the content in while loops and the like would need to be indented.
So here, you would indent all the code inside the while loop, and further indent the code inside the if statement inside the while loop.
It also seems like the purpose of your code is to simulate a dice roll each time the while loop runs again. In the while loop, you call on the variable x for the dice roll, but x is never changed. You never changed x to be a different random number, so it will just show the same random number every time the user rolls the dice again.
To fix this, simply re-define x each time the while loop is run. So just move the definition of the variable x to within the while loop.
With all these fixes, the code works:
import random
user_start = "yes"
user_start_input = str(input("type 'yes' to generate random number. "))
while user_start_input == user_start:
x = random.randrange(7)
print("your random dice number is " + str(x))
user_start_input = input("roll again?")
if user_start_input != user_start:
break
print("done")
Of course the variable names could be a bit more informative, and the code could be structured better to improve performance and user friendliness, but overall, great job for a beginner!

How to run a function several times for different results in Python 3

EDIT: Thanks for each very detailed explanations for the solutions, this community is golden for someone trying to learn coding!! #DYZ, #Rob
I'm a newbie in programming, and I'm trying to make a simple lotto guesses script in Python 3.
The user inputs how many guesses they need, and the program should run the function that many times.
But instead my code prints the same results that many times. Can you help me with this?
I'm pasting my code below, alternatively I guess you can run it directly from here : https://repl.it/#AEE/PersonalLottoEn
from random import randint
def loto(limit):
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess
guess = [] #Need to create an empty list 1st
#User input to select which type of lotto (6/49 or 6/54)
while True:
choice = int(input("""Please enter your choice:
For Lotto A enter "1"
For Lotto B enter "2"
------>"""))
if choice == 1:
lim = 49 #6/49
break
elif choice == 2:
lim = 54 #6/54
break
else:
print("\n1 or 2 please!\n")
times = int(input("\nHow many guesses do you need?"))
print("\nYour lucky numbers are:\n")
for i in range(times):
result = str(sorted(loto(lim)))
print(result.strip("[]"))
Your loto function is operating on a global variable, guess. Global variables maintain their values, even across function calls. The first time loto() is called, guess is []. But the second time it is called, it still has the 6 values from the first call, so your while loop isn't executed.
A solution is to make the guess variable local to the loto() function.
Try this:
def loto(limit):
guess = [] #Need to create an empty list 1st
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

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