Jump to content
SubSpace Forum Network

Recommended Posts

Posted (edited)

Hey, that seems like a good first try. Here are some points I'd pick up on first:

 

# Getting to know you
userName = raw_input("Hi, don't get too hasty, enter your name: ")
print "Hi there, " +name +" it's nice to meet you! Let's move on..."

# here is an example of a sentinal controlled iterator,
# which will save you writing out the same code over and over

counter = 0 # create an 'empty' variable
userPicks = [] # create a list to store the users lottery picks
while counter < 5:
# grab a number from the user, store it as an int
pickedNumber = int(raw_input("Please enter a number: "))
# append that to the list we created earlier
userPicks.append(pickedNumber)
# just to highlight the use of sentinal controlled values
print "The counter is currently " +str(counter)
# iterate the sentinal by 1
counter += 1

 

You can also use the same methods above, but generating another instance of random.randint() each time. You can then compare the contents of both lists, the easiest way to do this is to sort both lists - then compare them. to do this, you'll need to refer to the Python documentation (make use of the interpreter if you're struggling.)

 

thanks for the tips, and what does "+=" mean? I'd assume it's another syntax for >= ?

Edited by Xog
Posted

Try using this code:

 

#Simple Lotto program
import random
import time

picked = 0


#Greeting
print('''Hello! Welcome to Xog\'s Lotto Application. Thank you for taking the time to test my application out.
To play this Lotto game, I want you to pick three numbers from 1 through 5.''')

#Waits for 2 seconds.
time.sleep(2)

#Getting to know you
print('Don\'t get hasty! First, I want you to tell me your name. Please type it in and press Enter.')
name = raw_input()
print('Hello, ' + name + ', my name is Xog.')

#Number picking
number = random.randint(1, 5)
print('Okay, now that we know eachother a little bit, I think it\'s time we begin.')

while picked < 3:
print('Please pick a number from 1 through 5.')
playerPicked1 = raw_input()
playerPicked1 = int(playerPicked1)
picked = picked + 1

print('Pick your second number, between 1 and 5, that you did not pick.')
playerPicked2 = raw_input()
playerPicked2 = int(playerPicked2)
picked = picked + 1

print('Pick your third and last number, between 1 and 5, that you did not pick.')
playerPicked3 = raw_input()
playerPicked3 = int(playerPicked3)
picked = picked + 1

#Your issue was here. You can't do playerPicked1 or playerPicked2 or playerPicked3 == number.
if (playerPicked1 == number) or (playerPicked2 == number) or (playerPicked3 == number):
number = str(number)
print('The lotto number was ' + number + '! Congratulations! You\'ve just won $500 Hyperspace Dollars!')
time.sleep(3)
print('Well.. Okay, maybe not the money.')
else:
number = str(number)
print('Sorry, the last number was ' + number + '.')

print('Thanks for playing Xog\'s lotto!')

 

What I saw wrong was first of all, you used input(). Use raw_input(). input() expects a valid python expression for input. Also the reason why this wasn't working at all was you did

playerPicked1 or playerPicked2 or playerPicked3 == number. It should be (playerPicked1 == number) or (playerPicked2 == number) or (playerPicked3 == number). And instead of making

a new if statement you could have used an else.

Posted (edited)

Try using this code:

 

#Simple Lotto program
import random
import time

picked = 0


#Greeting
print('''Hello! Welcome to Xog\'s Lotto Application. Thank you for taking the time to test my application out.
To play this Lotto game, I want you to pick three numbers from 1 through 5.''')

#Waits for 2 seconds.
time.sleep(2)

#Getting to know you
print('Don\'t get hasty! First, I want you to tell me your name. Please type it in and press Enter.')
name = raw_input()
print('Hello, ' + name + ', my name is Xog.')

#Number picking
number = random.randint(1, 5)
print('Okay, now that we know eachother a little bit, I think it\'s time we begin.')

while picked < 3:
print('Please pick a number from 1 through 5.')
playerPicked1 = raw_input()
playerPicked1 = int(playerPicked1)
picked = picked + 1

print('Pick your second number, between 1 and 5, that you did not pick.')
playerPicked2 = raw_input()
playerPicked2 = int(playerPicked2)
picked = picked + 1

print('Pick your third and last number, between 1 and 5, that you did not pick.')
playerPicked3 = raw_input()
playerPicked3 = int(playerPicked3)
picked = picked + 1

#Your issue was here. You can't do playerPicked1 or playerPicked2 or playerPicked3 == number.
if (playerPicked1 == number) or (playerPicked2 == number) or (playerPicked3 == number):
number = str(number)
print('The lotto number was ' + number + '! Congratulations! You\'ve just won $500 Hyperspace Dollars!')
time.sleep(3)
print('Well.. Okay, maybe not the money.')
else:
number = str(number)
print('Sorry, the last number was ' + number + '.')

print('Thanks for playing Xog\'s lotto!')

 

What I saw wrong was first of all, you used input(). Use raw_input(). input() expects a valid python expression for input. Also the reason why this wasn't working at all was you did

playerPicked1 or playerPicked2 or playerPicked3 == number. It should be (playerPicked1 == number) or (playerPicked2 == number) or (playerPicked3 == number). And instead of making

a new if statement you could have used an else.

 

Ahh, thank you! I was asking lynx and rootbear why the ors weren't working - they were both returning true no matter what. They didn't know the answer. Now I know. Thanks!

 

edit: tried to run your version and i get

Traceback (most recent call last):

File "C:/Documents and Settings/Administrator/Desktop/Python/lotto4.py", line 17, in

name = raw_input()

NameError: name 'raw_input' is not defined

 

so I changed all the raw_input() to input() and it works!

 

#Simple Lotto program
import random
import time

picked = 0


#Greeting
print('''Hello! Welcome to Xog\'s Lotto Application. Thank you for taking the time to test my application out.
To play this Lotto game, I want you to pick three numbers from 1 through 5.''')

#Waits for 2 seconds.
time.sleep(2)

#Getting to know you
print('Don\'t get hasty! First, I want you to tell me your name. Please type it in and press Enter.')
name = input()
print('Hello, ' + name + ', my name is Xog.')

#Number picking
number = random.randint(1, 5)
print('Okay, now that we know eachother a little bit, I think it\'s time we begin.')

while picked < 3:
	print('Please pick a number from 1 through 5.')
	playerPicked1 = input()
	playerPicked1 = int(playerPicked1)
	picked = picked + 1
	
	print('Pick your second number, between 1 and 5, that you did not pick.')
	playerPicked2 = input()
	playerPicked2 = int(playerPicked2)
	picked = picked + 1
	
	print('Pick your third and last number, between 1 and 5, that you did not pick.')
	playerPicked3 = input()
	playerPicked3 = int(playerPicked3)
	picked = picked + 1

#Your issue was here. You can't do playerPicked1 or playerPicked2 or playerPicked3 == number.
if (playerPicked1 == number) or (playerPicked2 == number) or (playerPicked3 == number):
	number = str(number)
	print('The lotto number was ' + number + '! Congratulations! You\'ve just won $500 Hyperspace Dollars!')
	time.sleep(3)
	print('Well.. Okay, maybe not the money.')
else:
	number = str(number)
	print('Sorry, the last number was ' + number + '.')

print('Thanks for playing Xog\'s lotto!')

 

returns as:

Hello! Welcome to Xog's Lotto Application. Thank you for taking the time to test my application out.

To play this Lotto game, I want you to pick three numbers from 1 through 5.

Don't get hasty! First, I want you to tell me your name. Please type it in and press Enter.

Logan

Hello, Logan, my name is Xog.

Okay, now that we know eachother a little bit, I think it's time we begin.

Please pick a number from 1 through 5.

1

Pick your second number, between 1 and 5, that you did not pick.

2

Pick your third and last number, between 1 and 5, that you did not pick.

3

The lotto number was 3! Congratulations! You've just won $500 Hyperspace Dollars!

Well.. Okay, maybe not the money.

Thanks for playing Xog's lotto!

 

(possibly because I'm using python's GUI (IDLE)?)

 

As far as I know, input() asks the user to put any information in and stores it as the variable. the next line playerPicked1 = int(playerPicked1) turns the variable into an integer. Ofcourse, if the user put in something other than an integer it would result in an error blum.gif but hey its just a simple little program and I'm still learning, so that's all I could do for now

Edited by Xog
Posted

Straight from python.org:

 

Warning

 

This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.)

 

Consider using the raw_input() function for general input from users.

 

Posted (edited)

Straight from python.org:

 

Warning

 

This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.)

 

Consider using the raw_input() function for general input from users.

 

 

 

 

 

Traceback (most recent call last):

File "C:\Documents and Settings\Administrator\Desktop\Python\lotto4.py", line 17, in

name = raw_input()

NameError: name 'raw_input' is not defined

 

does that mean i'd have to def raw_input? if so how would that go?

 

edit: i also noticed that it might be because i'm using windows and not a unix platform:

 

Platforms: Unix

 

The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly or via the rlcompleter module. Settings made using this module affect the behaviour of both the interpreter’s interactive prompt and the prompts offered by the raw_input() and input() built-in functions.

 

i ordered a wireless PCI card for my PC from dealextreme.com to use ubuntu since my wireless USB adapter isn't supported and i couldn't find any working solution. I ordered it last month but it should be here by today or monday

Edited by Xog
Posted

It should be 'name = raw_input("What is your name?: ")'. If you leave the function empty, you'll get an error.

 

My bad on the use of multiple variables and operators to make a truth statement, 5am. :/

 

I've just done this a minute ago, I've not tested it so it probably won't run but:

 

# Bleuurghh bored, I should have gone to the pub...
import random
import time

def beginGame():
userName = raw_input("To begin, enter your name: ")
print("Hello, %s, my name is Xog." % userName)
randNumbers = []
userCoices = []
while len(userChoices) <= 4:
	randNumber = random.ranint(1, 5)
	randNumbers.append(randNumber)
	userChoice = int(raw_input("Pick a number between 1 and 5: ")
	userChoices.append(userChoice)
	print("So far you've picked: " +str(userChoices)
else:
	randNumbers.sort; userChoices.sort
	matchingNumbers = [i for i, j in zip(randNumbers, userChoices) if i == j]
	if len(matchingNumbers) > 0:
		print("Congratulations %s, you've won!" % userName)
		if len(matchingNumbers) == 4:
			print("You entered: " +str(userChoices) +" and our computer picked "\
			+str(randNumbers) +" and you managed to guess them all correctly! GJ!")
		elif len(matchingNumbers < 4:
			print("Unfortunately you never got them all correct, here are the ones\
			that you guessed: " +str(userChoices) +" and here are the ones that\
			our computer picked: " +str(randNumbers) +" better luck next time!")
			playAgain = str(raw_input("Would you like to play again? (y/n): ")
			if playAgain == y or playAgain == n:
				if playAgain == y:
					beginGame()
				elif playAgain == n:
					print("Thanks for playing!"); exit()
			else:
				print("Seeing as you can't hit y/n, you don't deserve me")
				exit()

print("Hello, welcome to Xog's Lotto application! Thank you for playing!.")
time.sleep(2)
beginGame()

 

That's an idea of how I'd do it.

Posted (edited)

It should be 'name = raw_input("What is your name?: ")'. If you leave the function empty, you'll get an error.

 

 

Traceback (most recent call last):

File "C:\Documents and Settings\Administrator\Desktop\Python\lotto4.py", line 16, in

name = raw_input('Don\'t get hasty! First, I want you to tell me your name: ')

NameError: name 'raw_input' is not defined

 

but yea screw that - cre> found what the problem was and the other one works fine with input(). blum.gif lesson learned and back to the tutorial I go!

Edited by Xog
Posted

If I had gotten a chance to rewrite it in java, I probably would have figured it out.

Anywho, I overlooked that because, well, I was thinking the problem lied in the if part of the statement and the way you had it layed out.

Posted

I've had a chance to jump on Linux (where I have Python installed). Here is the correct code, it probably still has a couple of minor bugs but this is how I'd have done it:

 

# Lottery Application
import random
import time

def playAgain():
playAgain = str(raw_input("Would you like to play again? (y/n): "))
if playAgain == 'y' or playAgain == 'n':
	if playAgain == 'y':
		userChoices = []
		randNumbers = []
		beginGame()
	elif playAgain == 'n':
		print("Thanks for playing!")
		exit()
	else:
		print("Let's try again, shall we?")
		playAgain()

def beginGame():
userName = raw_input("To begin, enter your name: ")
print("Hello, %s, my name is Xog." % userName)
randNumbers = []
userChoices = []
while len(userChoices) <= 4:
	randNumber = random.randint(0, 5)
	randNumbers.append(randNumber)
	userChoice = int(raw_input("Pick a number between 1 and 5: "))
	userChoices.append(userChoice)
	print("So far you've picked: " +str(userChoices))
else:
	randNumbers.sort(); userChoices.sort()
	matchingNumbers = [a for a in randNumbers if a in userChoices]
	if len(matchingNumbers) > 0:
		print("Congratulations " +userName +" you've won! You entered: " \
		+str(userChoices) +" and our computer picked " +str(randNumbers) \
		+" That's " +str(len(userChoices)) +" of " +str(len(randNumbers))\
		+" correct! Well done!")
	else:
		print "Sorry, you lost!"
		playAgain()

print("Hello, welcome to Xog's Lotto application! Thank you for playing!.")
time.sleep(2)
beginGame()

Posted

I've had a chance to jump on Linux (where I have Python installed). Here is the correct code, it probably still has a couple of minor bugs but this is how I'd have done it:

 

# Lottery Application
import random
import time

def playAgain():
playAgain = str(raw_input("Would you like to play again? (y/n): "))
if playAgain == 'y' or playAgain == 'n':
	if playAgain == 'y':
		userChoices = []
		randNumbers = []
		beginGame()
	elif playAgain == 'n':
		print("Thanks for playing!")
		exit()
	else:
		print("Let's try again, shall we?")
		playAgain()

def beginGame():
userName = raw_input("To begin, enter your name: ")
print("Hello, %s, my name is Xog." % userName)
randNumbers = []
userChoices = []
while len(userChoices) <= 4:
	randNumber = random.randint(0, 5)
	randNumbers.append(randNumber)
	userChoice = int(raw_input("Pick a number between 1 and 5: "))
	userChoices.append(userChoice)
	print("So far you've picked: " +str(userChoices))
else:
	randNumbers.sort(); userChoices.sort()
	matchingNumbers = [a for a in randNumbers if a in userChoices]
	if len(matchingNumbers) > 0:
		print("Congratulations " +userName +" you've won! You entered: " \
		+str(userChoices) +" and our computer picked " +str(randNumbers) \
		+" That's " +str(len(userChoices)) +" of " +str(len(randNumbers))\
		+" correct! Well done!")
	else:
		print "Sorry, you lost!"
		playAgain()

print("Hello, welcome to Xog's Lotto application! Thank you for playing!.")
time.sleep(2)
beginGame()

 

Yep, definitely has to do with me using windows. The only thing I changed in your code was the invalid syntax on line 39: print "Sorry, you lost!" to print("Sorry, you lost!")

lynx.JPG

Posted
Aiye, I've heard things about Python 3 that causes a lot of incompatibility; that could be why. Also, for future reference be careful with copy+pasting code from the web, as the code parser on this forum counts 1 tab as 8 spaces. There are usually functions on programming editors that allow you to convert spaces to tabs, which makes checking that kinda stuff quicker.
Posted (edited)

WOOO!

 

Redid xog's lotto game in Java.... I feel proud of myself. Thank you Java API for the little help you did help me with.

 

/*
Xog's lotto game.
Ported over to Java
Author: Rootbear75
Date: Feb 7, 2010
*/

  import java.io.*;
  import java.util.*;


   public class Lotto
  {
      public static void main(String[] args)
     {
     //All Variables are declared here.
        Random random = new Random(); //Uses class random instead of hard way using Math.random... etc.
        int picked = 0; //Number of numbers the user is picked (Init)
        int[] playerPicked = new int[3]; //Array of user selected numbers
        int number; //The lotto number
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); //The Input handler.
        String name = null; //User's name. (requires null init)
        boolean win = false; //They haven't won as of the start of the program, therefore win = false.
        
     //Greeting
        System.out.println("Hello! Welcome to Rootbear's Lotto Application. Thank you for taking the time to test my application out. To play this Lotto game, I want you to pick three numbers from 1 through 5.");
     
     //Sleep for 2 seconds.
        try
        {
           Thread.sleep(2000);
        }
        //I don't see any exception coming out of this statement, therefore empty catch.
            catch(Exception e) 
           {}
     
     //Getting to know you
        System.out.print("Don't get too hasty! First, I want you to tell me your name. Please type it here and press Enter: ");
        try
        {
           name = bufferRead.readLine();
        }
        //Catch refers to line. if there's a problem, let me know. I dont expect one :/
            catch(Exception e)
           {
              System.out.print("Could not read input. Please restart program and contact the author.. ERROR LINE 34");
              System.exit(0);
           }
        System.out.println("Hello, " + name + ", my name is Rootbear.");
     	
        System.out.println("Okay, now that we know each other a little bit, I think it's time we begin.");
     
     	//Get lotto number
        number = random.nextInt(5) + 1;
        
     	//Pick 3 numbers
        while(picked < 3)
        {
        //Adds one to picked so string displays correctly. Removes it immediately after.
        picked++;
           System.out.print("Pick a number from 1 to 5. (Choice " + picked + "):  ");
           picked--;
           try
           {
              playerPicked[picked] = Integer.parseInt(bufferRead.readLine());
             
           }
          catch(Exception e)
              {
                //Cancels out iterator. Will re-loop and ask for input again until correct type of input is given.
                 picked--;
              }
           picked++;
        }
        //Reset picked to verify winning number.
        picked=0;
     //While they didnt win.
        while(win != true)
        {
        //Checks number picked at 
           if(playerPicked[picked]==number)
           {
              System.out.println("The number was " + number + "! Congratulations! You've just won HS$500!");
              try
              {
              //Sleep 3sec.
                 Thread.sleep(3000);
              }
                  catch(Exception e)
                 {
                 //If something happens, idk?
                    System.out.println("Error Line 92");
                    System.exit(0);
                 }
              System.out.println("Well... Okay, maybe not the money.");
              win = true;
           }
           
           if(picked==playerPicked.length-1)
           {
           //If loop goes thru array, prints statement, then breaks from loop so it does not go on infinitely.
              System.out.println("Sorry, the lotto number was " + number +".");
              break;
           }
           picked++;
        }
     }
  }

 

i know the point of this blog is python but hey... :)

 

 

Added class file incase you guys feel like testing it :excl:

if you dont know how to execute .class

 

Command Prompt (on windows, dont know how on other OSs)

navigate to folder you saved file in using the "cd" command

type: java Lotto

Lotto.class

Edited by rootbear75

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...