I am learning Python and did this little game where you try to guess the number the Computer has generated.
from random import randint
def guess():
play = 0
while play != 'exit':
numbercomp = randint(1, 9)
tries = 0
humanno = 0
while numbercomp != humanno:
humanno = int(raw_input("What is my number, from 1 to 9? "))
if numbercomp == humanno:
tries = tries + 1
print('you are right, nice!')
elif numbercomp < humanno:
tries = tries + 1
print('my number is smaller than yours')
else:
tries = tries + 1
print('my number is bigger than yours')
print 'you got it in', tries, 'tries'
play = raw_input('press any key to play , type "exit" to leave')
print "Good bye!"
exit()
while True:
try:
guess()
except ValueError:
print('that was not a number from 1 to 9!')
I wonder what would be a way to save the best score (less tries) and the name of the holder into a file and have the program show this information up every time it starts. Less important would be making this file encrypted in some way.
Also, if you spot that the could would be done in a more elegant fashion I would appreciate feedback.
For instance something you could is like this
if tries > score:
pickle.dump( favorite_color, open( "save.p", "wb" ) )
If the trys are lower than the high score then it changes the highest score.
then to open it just do
highscore = pickle.load( open( "save.p", "rb" ) )
and you can just print the high score when the function is first ran.
Related
So I am rather new to programming and just recently started with Classes and we are supposed to make a phonebook that can be loaded in seperate text files.
I however keep running into the problem in this section that when I get into the for-loop. It hits a brick wall on
if storage[2] == permaStorage[i].number:
And tells me "IndexError: list index out of range". I am almost certain it is due to permaStorage starts out empty, but even when I attempt to fill it with temporary instances of Phonebook it tells me it out of range. The main reason it is there is to check if a phone number already exists within the permaStorage.
Anyone got a good tip on how to solve this or work around it?
(Sorry if the text is badly written. Just joined this site and not sure on the style)
class Phonebook():
def __init__(self):
self.name = ''
self.number = ''
def Add(name1, number1):
y = Phonebook()
y.name = name1
y.number = number1
return y
def Main():
permaStorage = []
while True:
print " add name number\n lookup name\n alias name newname\n change name number\n save filename\n load filename\n quit\n"
choices = raw_input ("What would you like to do?: ")
storage = choices.split(" ")
if storage[0] == "add":
for i in range(0, len(permaStorage)+1):
if storage[2] == permaStorage[i].number:
print "This number already exists. No two people can have the same phonenumber!\n"
break
if i == len(permaStorage):
print "hej"
try:
tempbox = Add(storage[1], storage[2])
permaStorage.append(tempbox)
except:
raw_input ("Remember to write name and phonenumber! Press any key to continue \n")
I think problem is that permaStorage is empty list and then u try to:
for i in range(0, len(permaStorage)+1):
if storage[2] == permaStorage[i].number:
will cause an error because permaStorage has 0 items but u trying to get first (i=0, permaStorage[0]) item.
I think you should replace second if clause with first one:
for i in range(0, len(permaStorage)+1):
if i == len(permaStorage):
print "hej"
try:
tempbox = Add(storage[1], storage[2])
permaStorage.append(tempbox)
if storage[2] == permaStorage[i].number:
print "This number already exists. No two people can have the same phonenumber!\n"
break
So in this case if perStorage is blank you will append some value and next if clause will be ok.
Indexing starts at zero in python. Hence, a list of length 5 has the last element index as 4 starting from 0. Change range to range(0, len(permastorage))
You should iterate upto the last element of the list, not beyond.
Try -
for i in range(0, len(permaStorage)):
The list of numbers produced in range() is from the start, but not including the end, so range(3) == [0, 1, 2].
So if your list x has length 10, range(0, len(x)) will give you 0 through 9, which is the correct indices of the elements of your list.
Adding 1 to len(x) will produce the range 0 through 10, and when you try to access x[10], it will fail.
I need to find 2 random numbers from 1-100 and send a message:
to high or to low according to the random number,
This is the code I wrote..., it doesn't work after the first if...,
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while guess != a:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = raw_input("guess a new number:")
from random import randint
a = randint(1, 101)
guess = input("guess the number:")
while True:
if guess > a:
print "your guess is too high"
elif guess < a:
print "your guess is too low"
else:
print 'You are correct'
break
guess = input("guess again:")
If I understood correctly your aim this code will work. It will stop when he guesses correctly the number. You had many mistakes with input and int. For future reference - if you use input() instead of raw_input() it will automatically pick the right type for the var.
In order to make your code work as intended just fix the input:
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while True:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = input("guess a new number:") #not raw_input()
I'm trying to make a simple 2 player game on python 2.7 .
The program will determine the result of a rock, paper, scissors game, given Player 1 and Player 2’s choices. The program will print out the result, score by each player and the total number of game played.
My question is:
The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
1.The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? ")).lower()
player_2 = str(input(">>Player 2? ")).lower()
2.Both player must input their choices before the program can be terminated. That means when player 1's input "-1", the program doesn't terminate immediately. It will proceed to ask player 2 for input before it get terminated. How can I make the program terminate itself immediately when player 1's input is "-1"?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? "))
if (player_1=='-1'):
print 'End of game'
break
player_2 = str(input(">>Player 2? "))
3.My code is very long, any suggestions or tips on shortening it without sacrificing any of the function?
use function definitions. Sample:
if (player_1=='-1' or player_2=='-1'):
print 'End of game'
break
elif dif in [-1, 2]:
print ('Player 1 wins.')
score1 = score1 + 1
showScore()
elif dif in [1, -2]:
print('Player 2 wins.')
score2 = score2 + 1
showScore()
else:
print('Tie')
showScore()
continue
def showScore():
print '==================='
print 'Score:'
print 'Player 1: ' + `score1`
print 'Player 2: ' + `score2`
print 'Total game played: ' + `times`
print ''
Here's a good read
For starters, I converted your program to Python 3. It's better in every way. For one thing, it has a normal definition for input.
In general, if you have N of something, where N is greater than 1, it's better to use an array. If you see repetition, move the data into an array and call a function. When N is 2, you won't necessarily shorten the code (my version is longer than yours) but you'll avoid treating the players differently because they both pass through the same logic.
Put the main logic in a function, too, and reserve the "main" code for dealing with startup & command-line stuff.
When you see a string of elifs, that's also a use data instead indicator. In my victor function, I iterate over tuples of winning combinations. You might consider how to use a dict instead.
import sys, os
def print_results( msg, times, scores ):
print( (msg) )
print( '===================' )
print( 'Score:' )
print( 'Player 1: %d' % scores[0] )
print( 'Player 2: %d' % scores[1] )
print( 'Total game played: %d' % times )
print( '' )
def victor( inputs ):
results = ( ('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock') );
for (a, b) in results:
if a == inputs[0] and b == inputs[1]:
return 1
if b == inputs[0] and a == inputs[1]:
return 2
return 0
def play(times, scores):
inputs = ['', '']
for (i, choice) in enumerate(inputs):
prompt = '>>Player %d? ' % (i + 1)
choice = input(prompt).lower()
if choice == '-1':
return False
inputs[i] = choice
result = victor(inputs)
if result == 0:
print_results('Tie', times, scores)
else:
scores[result - 1] += 1
print_results('Player %d wins' % result, times, scores)
times += 1
return True
print('''Welcome to play Rock, Paper, Scissors game. Enter -1 to end''')
scores = [0, 0]
times = 0
while play(times, scores):
pass
if scores[0] == scores[1]:
player = 'Tie'
else:
if scores[0] > scores[1]:
i = 1
else:
i = 2
player = 'Player %d' % i
print( '*******************' )
print( 'Winner: %s' % player )
print( '*******************' )
Ok, so, this is the longest code I've ever written, so I apologize if it's a bit messy. First computer science assignment ever.
def main():
#generate random value
import random
rand = random.randint(1, 99)
#instructions
print("""The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value. Enter coins as 1=penny, 5-nickel,
10-dime, 25-quarter. Hit return after the last entered coin value.""")
#defining function for 'first coin'
def firstCoin ():
coins = []
global coins
coin = int(input("Enter first coin: "))
if coin > rand:
print("Sorry, total value exceeds", rand, "cents.")
again = input("Try again (y/n): ")
if again == "y" or "Y":
main()
else:
sys.exit() #ends program
elif coin in possible:
coins.append(coin)
nextCoinplease()
#defining function for 'next coin'
def nextCoinplease ():
while True:
nextcoin = (input("Enter next coin: "))
if nextcoin in possible:
coins.append(nextcoin)
elif nextcoin == "":
break
else: print("Invalid entry.")
#making lists
possible = [1, 5, 10, 25]
print("Enter coins that add up to", rand, "cents, one per line.") #program start
firstCoin ()
sumcoin = sum(coins)
print(sumcoin)
if sumcoin == rand:
print("Correct!")
else:
print("Invalid entry.")
firstCoin()
main()
So, this is my issue. For some reason, user input in the function nextCoinplease does not get added to the list "coins", only the first input from the function firstCoin does. This means that sum(coins) is literally only the first input. I cannot for the life of me figure out why, so any input would be greatly appreciated, thanks!
You have two input statements, one to get coin and one to get nextcoin. They are different. What's the difference?
(I'm deliberately not giving the answer outright because from what you've written so far, I am sure you can figure this one out given this hint.)
The return type of input is a string, so nextcoin in possible always fails since possible only contains integers. Try using int() to parse the input as an integer.
Your code never gets to check if the rand is equal to sumCoin, so it never stopped. I've fixed the problem, this code works now.
Demo on repl.it
What did I do?
I moved your if statement that checked if rand == sumCoin at the beginning of the while loop in nextCoinPlease(), so that it will check the sumCoin value before entering each next coin value and will stop once it equals rand.
Code:
import random
import sys
def main():
rand = random.randint(1, 99)
print('''The purpose of this exercise is to enter a number of coin values \
that add up to a displayed target value. Enter coins as 1=penny, \
5=nickel, 10-dime, 25-quarter. Hit return after the last entered \
coin value.''')
coins = []
def firstCoin():
coin = int(input("Enter first coin: "))
if coin > rand:
print('Sorry, total value exceeds ', rand, ' cents.')
again = input('Try again? (y/n): ')
if again == 'y' or 'Y':
main()
else:
sys.exit()
elif coin in possible:
coins.append(coin)
nextCoinPlease()
def nextCoinPlease():
while True:
sumCoin = sum(coins)
print('Total Value: ' + str(sumCoin))
print ''
if sumCoin == rand:
print('Correct! You Win!')
sys.exit()
elif sumCoin > rand:
print('You exceeded the total value! You lose! Try again!')
sys.exit()
nextCoin = (input('Enter next coin: '))
if nextCoin in possible:
coins.append(nextCoin)
elif nextCoin == "":
break
else:
print('Invalid entry.')
possible = [1, 5, 10, 25]
print('Enter coins that add up to', rand, 'cents, one per line.')
firstCoin()
main()
What if i want to ask the user whether he wants to perform another calculation or not everytime the user makes a calculation and gets the answer? I just want the code to run again from start everytime user performs calculation
var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division respectively: "))
if var == 1:
print "You chose to add.Lets add!! :)"
def main ():
total = 0.0
while True:
number = float(raw_input('enter a number: '))
total+=number
if number == 0:
break
print "your answer is:",total
main()
elif var == 3:
print "You chose to multiply.Lets multiply!! :) "
def main ():
total = 1.0
while True:
number = float(raw_input('enter a number:'))
total*=number
if number == 1:
break
print "the answer is", total
main()
Just put
while True:
around the whole thing. This will continue looping indefinitely. If you want the user to be able to choose to end the program, try:
while True:
...
continue = raw_input("Continue? (Y/N) ")
if continue.lower in ("n", "no"):
break