So we have a school project to make a program that asks the user whether to pick a random card from a 52 deck or simulate a coin toss - heads or tails. I've got a beta version working but I'm looking into how to make the program more efficient. Basically, the program sets the tuples 'card' and 'coin' to all the possible types, so for coin, heads and tails, and card, the 52 different cards.
The following part of the program sets the variable 'choice' to either card or coin
while choice!='card' and choice!='coin':
choice=input("Pick a card or toss a coin (card/coin)?: ")
if choice!="card" and choice!="coin":
print("Please enter either 'card' or 'coin'...")
time.sleep(2)
Next I want to be able to return a value from either tuple depending on the value of 'choice' without using and if statement, something along the following:
print("The ",choice," picked at random is... ",random.choice("Either card, or coin"),"!")
How would I do this? Thanks, Brandon.
Full program:
#importing modules used in program
import time
import random
#creating duples for possible cards and coins
cards=["Ace of spades","King of spades","Queen of spades","Jack of spades","10 of spades","9 of spades","8 of spades","7 of spades","6 of spades","5 of spades","4 of spades","3 of spades","2 of spades","Ace of diamonds","King of diamonds","Queen of diamonds","Jack of diamonds","10 of diamonds","9 of diamonds","8 of diamonds","7 of diamonds","6 of diamonds","5 of diamonds","4 of diamonds","3 of diamonds","2 of diamonds","Ace of clubs","King of clubs","Queen of clubs","Jack of clubs","10 of clubs","9 of clubs","8 of clubs","7 of clubs","6 of clubs","5 of clubs","4 of clubs","3 of clubs","2 of clubs","Ace of hearts","King of hearts","Queen of hearts","Jack of hearts","10 of hearts","9 of hearts","8 of hearts","7 of hearts","6 of hearts","5 of hearts","4 of hearts","3 of hearts","2 of hearts"]
coin=["Heads","Tails"]
#setting variable 'repeat' to 'y' to start the mainloop of the program
repeat="y"
while repeat=="y":
#blanking the repeat and choice variables so they can be reset later
repeat=""
choice=""
#won't allow the user to continue until either 'card' or 'coin' is entered
while choice!='card' and choice!='coin':
choice=input("Pick a card or toss a coin (card/coin)?: ")
if choice!="card" and choice!="coin":
print("Please enter either 'card' or 'coin'...")
time.sleep(2)
print("The ",choice," picked at random is... ",random.choice(card),"!")
#won't allow the user to continue until either 'y' or 'n' is entered
while repeat!="y" and repeat!="n":
repeat=input("Go again..? (y/n): ")
if repeat!="y" and repeat!="n":
print("Please enter either 'y' for yes or 'n' for no...")
time.sleep(2)
#ending of the program
print("Goodbye!")
time.sleep(2)
The easiest way to accomplish this is to have a dictionary of tuples:
items = { 'coin': coin,
'card': cards }
Then, after choice has been set properly by your while loop, use the word provided by the user as the key to select from the dictionary the correct list, which can then be passed to random.choice:
print("The ", choice, " picked at random is ...", random.choice(items[choice]))
I'm for sure if this is what you're asking, but if the tuple you're talking about is this ('coin', 'card'), then you can do the following:
import random
test = ('coin', 'card')
test[random.randint(0, 1)]
That will randomly select one of the two choices.
Related
I am very new to Python (literally just started learning last week). My group got an assignment to code a program to compute system that calculate total price with several conditions. But we are stuck because the user input returns as string but we need it to link with the variable. And also we aren't allowed to use IF, ELSE method and everyone is new to this so we are at dead end. Please help :')
This is what we have coded in the last hour.
min_price=30
oak_type=15
pine_type=0
black=0
white=0
gold_leaf=15
print("Welcome to Mark Daniels Carpenting Service!")
import random
order_num=random.randint(1000,1999)
print("\nYour order number is", (order_num))
cust_name=input("Enter name:")
print("Type of wood available:")
print("1 oak_type \n2 pine_type")
wood_type=input("Enter choice of wood:")
And when we tried to total up the price it comes up as error because the wood_type returns as string while the other data returns as integer.
How to make input from wood_type link to oak_type or pine_type value?
wood_type=input("Enter choice of wood:")
You can use wood_type=int(input("Enter choice of wood:"))
Use integer_x = int(input("Enter... ")) for integer and float_x = float(input("Enter... ")) for float.
You can add the type of your input at the beginning of your input syntax.
So for your case, it will be :
wood_type = int(input("Enter choice of wood:"))
I'm trying to code a game of craps in which the player has a virtual 'wallet' to gamble with. I've gotten to the user input part and it's not going as planned.
Here is what I have so far:
import random
import sys
money = "500"
# start the game
a = input("Hello travler, to start the game, please type 'yes'. If you are not ready to begin your journey, type 'no' ")
if a.lower() == "no":
sys.exit()
else:
print("Welcome")
print("Hold on... I'm missing something,")
name = input("What is your name, traveler?: ")
print("Welcome,", (name))
# those who need instructions can ask for it,
# others can start the game directly.
a = input("Welcome to a game that'll determine the rest of your life. Do you need instructions? (yes) or (no)? \n")
if a.lower() == "yes":
print('''1. the player will roll two six sided dice. the sum of the two dice is the player's number for the round.
2. rolling a 7 or an 11 as your first roll win you the game, but be weary, a 2, 3, or 12 automatically causes the player to lose. no more game for you. If a 4, 5, 6, 8, 9, or 10 are rolled on this first roll, that number becomes the 'point.'
3. the fated player continues to roll the two dice again until one of two things occur: either they roll the 'point' again, causing them to win the game; or they roll a 7, causing them to be doomed to the eternals.''')
elif a.lower() == "no":
print("may luck be with you on this fateful day,", name)
print("You will start off with 500 pieces of luck, if you leave this game with over 1000 pieces of luck, you will be fated for sucsess. On the other hand, should you drop below 0 peices of luck, you will find yourself in debt to the universe, a misfortune that few recover from.")
print("You currently have", money, "luck to spare")
# betting time
while True:
bet = input("How much luck do you wish to bet? ")
if bet.isdigit() is True:
if money > bet:
print("Bet accepted")
if bet.isdigit() is True:
if bet > money:
print("How unfortunate, you do not have the luck to make this bet.")
elif bet.isdigit() is False:
print ("Sorry, luck can only be quantitated in number values.")
# if you bet higher than your money, it wont allow you to bet within after that.
The code below the line # betting time is where I am hitting my head over.
I need the code to do the following:
check if the user input is in fact a number, if it's not a number, make them enter a new input
if the user input is a number, determine if it is within the amount they have in their 'wallet' (if not, make them input a new number)
if the number is within the amount in their 'wallet' and is a digit, give the user the option to "roll dice" triggering the game to start.
If they win, they need to be granted double what they bet, if they lose, they need to lose the amount they bet. The wallet will need to update after each play, giving the user the option to play again with their updated wallet (so if they bet 50 and win, their new balance will be 550. The process continues until the user either reaches 1000 or 0, causing the game to end either way.)
For checking if the user's bet is a number use the .isnumeric() function on your bet like:
bet.isnumeric()
to do the second thing you needed help with you could do:
if bet < wallet: blah blah blah elif
bet > wallet: print("You do not enough money")
around like that it with actual good syntax
to do dice you could use the random.randint() function like this:
random.randint(1,6)
I hope that helps!
Complete beginner here.
I'm making a short game where one of the two players is randomly chosen to start the game:
from random import randint
player1 = input("First player, enter your name: ")
player2 = input("Second player, enter your name: ")
print("{randint(0,1)} will go first".format(name1, name2))
I want randint() to choose either player1 or player2, but I'm getting a TypeError. If I were to put either 0 or 1 into the {} instead of randint(0, 1) it works fine. Why doesn't this work? What other options are there besides an if/elif statement?
use randint(0,1) as an index to get the player name
players=[player1,player2]
print("{} will go first".format(players[randint(0,1)])
That isn't quite how the string format method works, the numbers you pass in like {0} and {1} serve as indices in the things you pass into the string in the .format(0th item here, 1st item here...etc.) call. So if you want your random integer to show up you should do something like:
print("{0} will go first".format(randint(0,1)))
What I want to do is have Python generate a number between 1 and 6, then add 6 to that number which I have got it to do and provide me with a result, however what I can't seem to figure out is how to make that value able to be called so it can go up and down during the game, here is what I have so far:
import random
import time
Name = input("Before we get started lets get your character created, tell me what is your name?")
print()
print ("Welcome ",Name," to the adventure of a lifetime. The next thing you will need to do is sort out your character stats. This will require dice rolls which we will do within the game.")
print()
def skillroll():
skillroll=""
while skillroll !="Y" and skillroll != "N":
skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")
if skillroll=="Y":
print("Rolling the dice..")
skill=random.randint(1,6)
time.sleep(2)
print("I rolled a", skill, " I will now add 6 to this so your skill is", skill+6)
skill=skill+6
print()
return skillroll
skillroll()
I just cant see how to get that final answer out so I can use it during the game-play.
A friend of mine sent me this to help
https://github.com/protocol7/python-koans/blob/master/python%202/koans/about_classes.py
But I just cant see how this relates and every answer I found on Stackoverflow is for different languages.
Simply use:
import random
random.randrange(1, 7)
to get any number between 1 and 6.
Your code becomes:
import random
import time
def skillroll():
skillroll=""
while skillroll !="Y" and skillroll != "N":
skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")
if skillroll=="Y":
print("Rolling the dice..")
skill = random.randrange(1, 7)
time.sleep(2)
print("I rolled a ", skill, ". I will now add 6 to this so your skill is", skill+6, "\n")
skill=skill+6
return skillroll # What if N??
Name = input("Before we get started lets get your character created, tell me
what is your name?")
print ("\nWelcome ",Name," to the adventure of a lifetime. The next thing you
will need to do is sort out your character stats. This will require dice
rolls which we will do within the game.\n")
skillroll()
I am new to python, My first project that I am still working on is a kind of a game in which you throw a dice and stuff like that, so it's pretty much a dice simulator.
Before the user actually starts the game I have made the program ask them questions like; "Type 'start' on keyboard to begin the game, and this I am doing with raw_input.
Here's the problem:- I want to make only the input 'start' possible to write, if something else is written, the game doesn't start. I hope you understand me
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name);
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
You just need if_else
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
if start=='start':
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name)
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
else:
print("XYZ message")