I am starting to code a game just to practice. However, the user needs to enter an odd number to play. If they don't then I want the program to ask them for an odd number they loop and play again. I put this code in the else statement but if I enter an odd number it will not loop again.
Question 2:
how can I get the program to display Game 1, Game 2, etc as the loop runs however many times the input in 'Games' is?
Can someone help?
games = input("How many games would you like to play?")
for i in range(games):
if games % 2 == 1:
print('Game 1')
# code here
else:
input('Enter an odd number')
Try this:
games = int(input("How many games would you like to play?"))
while True:
if games % 2 == 1:
for i in range(games):
print('Game', i+1 )
break
else:
games = int(input('Enter an odd number: '))
It appears to me that you your confusion lies in a couple casting errors. Please note that input returns a type string, which you attempt to use as an integer. Try the following code instead:
games = input("How many games would you like to play? ")
numberOfGames = int(games)
for i in range(numberOfGames):
print('Processing Game ' + str(i))
testVal = input('Enter an odd number ')
if int(testVal) % 2 == 1:
print("Congratts! " + testVal + " is odd!\n\n")
else:
print("You Loose. " + testVal + " is even.\n\n")
Related
I'm trying to complete this assignment asking user for a number and if it's not -1 then it should loop. if it's -1 then to calculate the average of the other numbers.
I'm getting stuck with the actual loop - it endlessly keeps printing the message to user to enter a different number - as in the picture - and doesn't give user a chance to enter a different number. Please help, I've been through so many videos and blogs and can't figure out what's actually wrong.
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num =int(input("number:"))
#looping
while num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
break
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
print("Nope, guess again:")
You need to include the input function in the loop if you want it to work. I corrected the rest of your code as well, you don't need the if condition. More generally you should avoid to use break, it often means you are doing something wrong with your loop condition. Here it is redondant and the code after break is never executed.
wrong = []
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num = int(input("Number: "))
while num != -1 :
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
You are just breaking the loop before printing the results, first print the results, then break the loop.
And a while loop isn't necessary for your program, use if condition wrapped in a function instead:
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
#looping
def go():
num =int(input("number:"))
if num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
break
print("Nope, guess again:")
go()
There are lots of issues in the code.
If you want to get inputs in while looping, you should include getting input code inside the while loop like below,
while num != -1:
......
num =int(input("number:"))
......
Also you don't have to include 'break' inside the while loop because, when num != 1, the loop will stop.
You should ask for input inside your loop, but you just print "Nope, guess again:".
wrong = []
print("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\n"
"If not correct you'll have to guess again ^-^")
num = int(input("number: "))
# looping
while num != -1:
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
hello I am trying to make a warhammer 40k dice roller and I made this code however it does not roll the right amount of dice I would appreceate help on how to make it work
import random
count = 0
dice_to_roll=input("how many dice are you rolling? ")
hit = input("what do you hit on? ")
print("rolling dice!!!!!!")
while str(count) < dice_to_roll:
die = random.randint(1, 6)
count = count + 1
if str(die) >= hit:
print(die)
else:
print("done")
input is returning a string. Making the other one a string and checking equality is comparing the lengths of the string, not the values. To make yours work, use int(input(...)) and remove the str() casts that you're doing.
Code:
import random
dice_to_roll = int(input("how many dice are you rolling? "))
hit = int(input("what do you hit on? "))
print ("rolling dice!!!!!!")
for i in range(dice_to_roll):
die = random.randint(1,6)
if die>=hit:
print(f"dice result:{die},hit:{hit},hit success!")
else:
print(f"dice result:{die},hit:{hit},hit failed!")
print("done")
Result:
how many dice are you rolling? 1
what do you hit on? 3
rolling dice!!!!!!
dice result:6,hit:3,hit success!
done
Instead of converting your count to a string try and convert your input dice_to_roll to an int.
I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.
So this is a bit confusing. I am currently making a Top-Trumps game. Right now I have two arrays, a player deck and a computer deck. The way it works is that it creates an array from a text file of dog names, then assigns 4 values to it (Exercise, Intelligence, Friendliness and Drool). This all works. Then it splits up the deck and gives half to each array (player and computer). The user gets the first pick and I have managed to get it to allow the user to pick a category. What I don't know how to do is compare exact values in the two arrays. The arrays are listed as follows (example):
[['Fern-the-Fox-Terrier'], 'Exercise: ', 3, 'Intelligence: ', 67, 'Friendliness: ', 10, 'Drool: ', 4]
Here is the code if you need it: (I'm not sure how to attach a text file)
import random
import shutil
import os #here I have imported all necessary functions for the following code to work
import array
import time
allowedresponses = ["Exercise","Intelligence","Friendliness","Drool"] #this allows me to make sure both the user and the computer select only the values available
cardcount = 0
usercards = 0 #the following variables are used for later
computercards = 0
x = 1
y = 0
play = input("Welcome to Celebrity Dogs Top Trumps! Press S to start, or Q to quit: ")
play = play.upper()
while x==1:
if play == "S" or play == "s":
print("Great! Lets play!")
x+=1 #here the user is given the option to play the game or quit. Pressing Q will immediatley end the the program, whilst pressing S will start it.
elif play == "Q" or play == "q": #x = 1 variable is used to end the while loop, permitted the user enters an appropriate answer
print("OK, bye")
quit
x+=1
else:
print("That's not a valid answer. Please try again")
play = input("Welcome to Celebrity Dogs Top Trumps! Press S to start, or Q to quit: ")
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: ")) #the following section of code asks the to select the number of cards they want played
while x==2:
if cardcount < 4:
print("Thats too small! Please try again!") #the programs tells the user to select again if they have picked a number smaller than 4
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: "))
elif cardcount > 30:
print("Thats too big! Please try again!") #the programs tells the user to select again if they have picked a number larger than 30
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: "))
if cardcount % 2 != 0:
print("Thats an odd number! Please try again!")#the programs tells the user to select again if they have picked a number that can't be divided by 2 with no remainders, essentially forcing only even numbers
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: "))
else:
print("Perfect! Onwards!")
x+=1 #once again I have used the x variable to allow the user to continue if they have selected a number that fits the requirements
time.sleep(1)
print("----------------------------------------------------------------------")
print("Rules: 1) For exercise, intelligence and friendliness, the highest value wins. For drool, lowest wins")
print(" 2) If there is a draw, the player that picked the value wins and gets the cards")
shutil.copyfile('dogs.txt','celebdogs.txt') #this creates a copy of the dogs text file. It is mainly for if I ever need to edit a file with the dogs in,, the origin file is never changed.
topdogs = [] #here I have created an array for the dogs
inp = open('celebdogs.txt','r') #I have used python's text file edits to import everything in the newly made celebdogs text file into an array, in order to import it later
for line in inp.readlines():
topdogs.append([])
for i in line.split():
topdogs[-1].append(i)
inp.close()
deck = [] #here I have created an array for the deck of cards that will be used in the game
print("----------------------------------------------------------------------")
for index in range(0,cardcount): #this part of the code tells the program to repeat the following until the number of cards selected by the user is in the deck
deck.insert([index][0], [(random.choice(topdogs))])#h
deck[index].append("Exercise: ")
deck[index].append(random.randint(0,5))
deck[index].append("Intelligence: ")
deck[index].append(random.randint(0,100))
deck[index].append("Friendliness: ")
deck[index].append(random.randint(0,10))
deck[index].append("Drool: ")
deck[index].append(random.randint(0,10))
time.sleep(1)
playerDeck=[]
computerDeck=[]
while len(deck)>0:
playerDeck.append(deck.pop(0))
computerDeck.append(deck.pop(0))
time.sleep(1)
print("This is your deck: ")
print(playerDeck)
playerTurn = True
print("----------------------------------------------------------------------")
time.sleep(1)
print("This is your first card: ")
print(playerDeck[0])
if playerTurn == True:
answer = input("Please select an attack (Exercise, Intelligence, Friendliness and Drool): ")
while allowedresponses.count(answer) == 0:
answer = input("That isn't a valid choice, please try again: ")
else:
answer = random.choice(allowedresponses)
print("Computer chooses", answer)
print("Computer Card: ")
print(computerDeck[0])
if playerDeck == cardcount:
print("You win!!!!")
if computerDeck == cardcount:
print("Computer wins!!!!")
os.remove('celebdogs.txt')
Just in case I haven't explained this well, I need help knowing how to compare precise values in two arrays, so if I want to compare the values of Exercise in both decks for the single cards. Both arrays have the exact same format (name, exercise, value, intelligence, value, friendliness, value, drool, value) so I need to be able to compare specific values.
Thanks!
Try use python's zip function:
computerDeck = [1, 2, 3]
playerDeck = [1, 3, 3]
for computer_card, player_card in zip(computerDeck, playerDeck):
if computer_card == player_card:
print('valid')
else:
print('invalid')
This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.