how to print same randomint after if/elif? - python-2.6

I want to get randint to be printed the same as in the if/elif statements each time it executes without a new integer returning. Also is there another way instead of having to write so much code after the while statement or is it fine?
from random import *
def randomchance():
return randint(1, 100)
def randomknife():
return randint(1, 8)
skins = ['blue', 'purple', 'pink', 'red']
knives = ['karambit', 'flip', 'bowie', 'butterfly', 'm9 bayonet', 'bayonet', 'daggers', 'falchion']
print 'Welcome to CS GO case lottery'
for skin in skins:
print "Available", skin,
for knife in knives:
print "Available", knife,
print '(blue = common, purple = uncommon, pink = rare, red = epic)'
keys = 10
while keys >0:
resp=raw_input("Enter 'yes' to open a case: ")
if (resp == str('yes') or resp == str('Yes')):
print 'Opening case...'
if (randomchance() >= 35):
print 'You\'ve won a', skins[0]
elif (randomchance() >= 20):
print 'You\'ve won a', skins[1]
elif (randomchance() >= 10):
print 'You\'ve won a', skins[2]
elif (randomchance() >= 5):
print 'You\'ve won a', skins[3]
elif (randomchance() >= 1):
if randomknife == 1:
print 'You\'ve won a', knifes[0]
elif randomknife() == 2:
print 'You\'ve won a', knifes[1]
elif randomknife() == 3:
print 'You\'ve won a', knifes[2]
elif randomknife() == 4:
print 'You\'ve won a', knifes[3]
elif randomknife() == 5:
print 'You\'ve won a', knifes[4]
elif randomknife() == 6:
print 'You\'ve won a', knifes[5]
elif randomknife() == 7:
print 'You\'ve won a', knifes[6]
elif randomknife() == 8:
print 'You\'ve won a', knifes[7]
keys -= 1
elif(resp == str('no') or resp==str('No')):
resp1=raw_input('Would you like to exit? Enter no for exit: ')
if resp1 == 'no' or "No":
exit()
else:
print "Yes or No. Answers only"
else:
print 'You\'ve run out of keys!'

#Konstantin has the right answer for how to choose the random number just once before testing all your conditions.
As to your second question (how to use less code to test all the conditions), take a look at my rewrite/cleanup below. In particular, I used random.choice to pick a knife, and I used a list of thresholds (35, 20, etc.) to pick skins.
I also fixed up a couple bugs, like your if resp1 == 'no' or "No": which should be if resp1 == 'no' or resp1 == "No": (but I used resp1.lower() instead).
And I couldn't stand 'Would you like to exit? Enter no for exit: ', so I made "yes" exit instead. :-)
import random
skins = ['blue', 'purple', 'pink', 'red']
knives = ['karambit', 'flip', 'bowie', 'butterfly', 'm9 bayonet', 'bayonet', 'daggers', 'falchion']
print 'Welcome to CS GO case lottery'
print "Available skins: %s" % ', '.join(skins)
print "Available knives: %s" % ', '.join(knives)
print '(blue = common, purple = uncommon, pink = rare, red = epic)'
for _ in range(10):
resp = raw_input("Enter 'yes' to open a case: ")
while resp.lower() != 'yes':
if resp.lower() == 'no':
if raw_input('Would you like to exit? ').lower() == 'yes':
exit()
else:
print "Yes or no answers only."
resp = raw_input("Enter 'yes' to open a case: ")
print 'Opening case...'
chance = random.randint(1, 100)
for i, n in enumerate([35, 20, 10, 5]):
if chance >= n:
print "You've won a %s skin." % skins[i]
break
if chance < 5:
print "You've won a %s knife." % random.choice(knives)
print "You've run out of keys!"

Try to save to a variable before if/else statement:
number = randomchance();
if (number >= 35): print 'you select a ', number

This is how I would do it:
knives = ['karambit', 'flip', 'bowie', 'butterfly', 'm9 bayonet', 'bayonet', 'daggers', 'falchion']
skins = ['blue'] * 35 + ['purple'] * 20 + ['pink'] * 10 + ['red'] * 5 + [0]
skin = random.choice(skins)
print "You won a " + skin + " skin" if skin else "You won a " + random.choice(knives) + " knife"

Related

How To Implement Tie function into Tic-Tac-Toe With Nested Lists

In my game, I am trying to add a tie function by using else under my win determiner, but I'm having trouble. Can someone help me add a tie function into my code under the win determiner? I have tried to add else under the win determiner, but the tie will end up printing that the game has ended in a tie randomly. Some help would be appreciated, thanks!
player1 = str(input("What is player X's name?"))
print()
player2 = str(input("What is player O's name?"))
turn = 1
location = [
[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' '],
]
while turn <= 9:
if turn % 2 == 1:
print()
print("It is currently " +player1+ "'s turn")
row = int(input("What row would you like to mark?"))-1
print()
col = int(input(" What column would you like to mark?"))-1
print()
while "O" in location[row][col]:
print(player1+" that spot has already been taken")
print("Please pick again")
row = int(input("What row would you like to mark?"))-1
print()
col = int(input(" What column would you like to mark?"))-1
print()
location[row][col] = "X"
print(location[0][0] + '|' + location[0][1] + '|' + location[0][2])
print("-----")
print(location[1][0] + '|' + location[1][1] + '|' + location[1][2])
print("-----")
print(location[2][0] + '|' + location[2][1] + '|' + location[2][2])
turn = turn + 1
if ((location[0][0] == 'X' and location[0][1] == 'X' and location[0][2]
== 'X') or
(location[1][0] == 'X' and location[1][1] == 'X' and location[1][2] ==
'X') or
(location[2][0] == 'X' and location[2][1] == 'X' and location[2][2] ==
'X') or
(location[0][0] == 'X' and location[1][0] == 'X' and location[2][0] ==
'X') or
(location[0][1] == 'X' and location[1][1] == 'X' and location[2][1] ==
'X') or
(location[0][2] == 'X' and location[1][2] == 'X' and location[2][2] ==
'X') or
(location[0][0] == 'X' and location[1][1] == 'X' and location[2][2] ==
'X') or
(location[0][2] == 'X' and location[1][1] == 'X' and location[2][0] ==
'X')):
print (player1+" won the game!")
turn = 10
else:
print("The game ended in a tie!")
else:
print("It is currently " +player2+ "'s turn")
row = int(input("What row would you like to mark?"))-1
print()
col = int(input(" What column would you like to mark?"))-1
print()
while "X" in location[row][col]:
print(player2+" that spot has already been taken")
print("Please pick again")
row = int(input("What row would you like to mark?"))-1
print()
col = int(input(" What column would you like to mark?"))-1
print()
location[row][col] = "O"
print(location[0][0] + '|' + location[0][1] + '|' + location[0][2])
print("-----")
print(location[1][0] + '|' + location[1][1] + '|' + location[1][2])
print("-----")
print(location[2][0] + '|' + location[2][1] + '|' + location[2][2])
turn = turn + 1
if ((location[0][0] == 'O' and location[0][1] == 'O' and location[0][2]
== 'O') or
(location[1][0] == 'O' and location[1][1] == 'O' and location[1][2] ==
'O') or
(location[2][0] == 'O' and location[2][1] == 'O' and location[2][2] ==
'O') or
(location[0][0] == 'O' and location[1][0] == 'O' and location[2][0] ==
'O') or
(location[0][1] == 'O' and location[1][1] == 'O' and location[2][1] ==
'O') or
(location[0][2] == 'O' and location[1][2] == 'O' and location[2][2] ==
'O') or
(location[0][0] == 'O' and location[1][1] == 'O' and location[2][2] ==
'O') or
(location[0][2] == 'O' and location[1][1] == 'O' and location[2][0] ==
'O')):
print (player2+" won the game!")
turn = 10
else:
print("The game ended in a tie!")
Your problem is, that the code checks after every single turn if the player whos turn it is won the game, if he did not win (yet) it prints your "else" meaning the The game ended in a tie!
Your solution would be to add another if: to you else-es that checks if all 9 fields are either filled with X or O and if that is the case you have to print your The game ended in a tie!

Number of repeats

Write a method that takes in a string and returns the number of letters that appear more than once in the string. You may assume the string contains only lowercase letters. Count the number of letters that repeat, not the number of times they repeat in the string.
I implemented methods and test cases as:
def num_repeats(string)
count = 0
dix = 0
new = ""
while dix < string.length
letter = string[dix]
if !(new.include?(letter))
new = new + "letter"
else
break
end
dix2 = dix + 1
while dix2 < string.length
if letter == string[dix2]
count +=1
break
end
dix2 +=1
end
dix += 1
end
puts(count.to_s)
return count
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts('num_repeats("abdbc") == 1: ' + (num_repeats('abdbc') == 1).to_s)
# one character is repeated
puts('num_repeats("aaa") == 1: ' + (num_repeats('aaa') == 1).to_s)
puts('num_repeats("abab") == 2: ' + (num_repeats('abab') == 2).to_s)
puts('num_repeats("cadac") == 2: ' + (num_repeats('cadac') == 2).to_s)
puts('num_repeats("abcde") == 0: ' + (num_repeats('abcde') == 0).to_s)
Test results:
1
num_repeats("abdbc") == 1: true
2
num_repeats("aaa") == 1: false
2
num_repeats("abab") == 2: true
2
num_repeats("cadac") == 2: true
0
num_repeats("abcde") == 0: true
For the second test that returned false, what was wrong with my code?
You are appending "letter", rather than the letter variable to new on line 8.
if !(new.include?(letter))
new = new + "letter"
else
#...
end
becomes:
unless new.include?(letter)
new = new + letter
else
#...
end

Total newb here and other fizzbuzz issue

I'm trying to write a looping fizzbuzz code that ends with the user_input's number. So far the code works, but it loops the number of times you put in for the user_input, not end at the user_input's limit. For example, if I type in 25, it will loop 25 times, and not end at 25. How do I set the parameters/range?
Here is my code:
puts("Please select a number that is at least 25. This is the limit for the fizzbuzz game.")
user_input = gets().chomp().to_i
if
user_input < 25
puts("Please select a larger number.")
else
user_input >= 25
user_input = user_input
counter = 1
while counter < user_input
puts(counter)
counter = counter + 1
(1..user_input).step do |i|
if i % 3 == 0 && i % 5 == 0
puts("fizzbuzz")
elsif i % 3 == 0
puts("fizz")
elsif i % 5 == 0
puts("buzz")
else
puts(i)
end
end
end
end
It is optional to write () when you send no parameters to a method and usually discouraged
You shouldn't use else user_input >= 25, else is enough
user_input = user_input is totally useless line
while cycles with counters isn't the way rubists code, prefer iterators. Moreover, you shouldn't have while here at all
puts 'Please select a number that is at least 25. This is the limit for the fizzbuzz game.'
user_input = gets.chomp.to_i
if user_input < 25
puts 'Please select a larger number.'
else
1.upto(user_input) do |i|
if i % 3 == 0 && i % 5 == 0
puts 'fizzbuzz'
elsif i % 3 == 0
puts 'fizz'
elsif i % 5 == 0
puts 'buzz'
else
puts i
end
end
end
optionally, you can use case-when instead of multiple elsif statements:
puts 'Please select a number that is at least 25. This is the limit for the fizzbuzz game.'
user_input = gets.chomp.to_i
if user_input < 25
puts 'Please select a larger number.'
else
1.upto(user_input) do |i|
case
when [3, 5].all? { |n| i % n == 0 }; puts 'fizzbuzz'
when i % 3 == 0; puts 'fizz'
when i % 5 == 0; puts 'buzz'
else; puts i
end
end
end

While loop continues despite conditions not being met?

When I run the game and type either "yes" or "no" at the end, it always reverts back to the start of the while loop at line 41, when the conditions for both that and the containing loop are not met.
replay = true
while replay
#Pre-var
print "What difficulty? (1 for easy, 2 for medium, or 3 for hard): "
difficulty = gets.chomp.to_i
until difficulty == 1 || difficulty == 2 || difficulty == 3 do
print "Please type either 1, 2, or 3: "
difficulty = gets.chomp.to_i
end
#Variables
if difficulty == 1
r = Random.new
number = r.rand(100..1000)
puts "You have 15 guesses. "
print "Guess a number with three digits: "
within_num = 50
elsif difficulty == 2
r = Random.new
number = r.rand(1000..10000)
puts "You have 15 guesses. "
print "Guess a number with four digits: "
within_num = 500
elsif difficulty == 3
r = Random.new
number = r.rand(10000..100000)
puts "You have 15 guesses. "
print "Guess a number with five digits: "
within_num = 5000
end
guess = ""
num_guess = 0
guess_array = Array.new
array_location = 0
count_through = 0
array_print = count_through - 1
replay_inner = true
#Body
puts number
while num_guess <= 14 || replay_inner == true #Keeping as <= 14 as to avoid unnecessarily rewriting code, still gives 15 guesses
guess = gets.chomp.to_i
if guess > number * 2
print "That is more than double the number. Guess again: "
elsif guess < number / 2
print "That is less than half the number. Guess again: "
elsif guess > number && guess < number + within_num #within_num: 50 for easy, 500 for medium, 5000 for hard
print "You are close. That is too big. Guess again: "
elsif guess < number && guess > number - within_num
print "You are close. That is too small. Guess again: "
elsif guess < number
print "That is too small. Guess again: " #Hinting the user to how close they are.
elsif guess > number
print "That is too big. Guess again: "
elsif guess == number
puts "Congragulations! You win!"
print "Your "
print guess_array.length
print " incorrect guesses were: "
if num_guess == 0
sleep(0.5)
print "... Oh."
else
while count_through < num_guess #Loop to relay user's guesses with a delay of 0.5 seconds
print guess_array[count_through]
if count_through == num_guess - 2
print ", and "
elsif count_through == num_guess - 1
puts ". "
else
print ", "
end
count_through += 1
sleep(0.5)
end
puts "Would you like to play again? (yes/no)"
replay_answer = gets.chomp
until replay_answer == "yes" || replay_answer == "y" || replay_answer == "no" || replay_answer == "n" do
print "Please answer with yes, y, no, or n: "
replay_answer = gets.chomp
end
if replay_answer == "yes" || replay_answer == "y"
replay = true
puts "yes"
elsif replay_answer == "no" || replay_answer == "n" #Determining whether or not to replay
replay = false
puts "no"
end
end
end
guess_array.push guess
num_guess += 1
#puts num_guess
#puts guess_array[array_location]
array_location += 1
if num_guess >= 15 && guess != number
puts "Sorry, you lost. "
print "Your "
print guess_array.size
print " guesses were: "
while count_through < num_guess
print guess_array[count_through] #Same as loop above; for when player fails to guess correctly
if count_through == num_guess - 2
print ", and "
elsif count_through == num_guess - 1
puts ". "
else
print ", "
end
count_through += 1
sleep(0.5)
end
puts "Would you like to play again? (yes/no)"
replay_answer = gets.chomp
until replay_answer == "yes" || replay_answer == "y" || replay_answer == "no" || replay_answer == "n" do
print "Please answer with yes, y, no, or n: "
replay_answer = gets.chomp
end
if replay_answer == "yes" || replay_answer == "y"
replay = true
replay_inner = true
puts "yes"
elsif replay_answer == "no" || replay_answer == "n" #Determining whether or not to replay
replay = false
replay_inner = false
puts "no"
end
end
end
I think the condition in the while should be:
numberGuess<=14 && replay_inner == true
The way you and especially your fellow programmers will find this and future bugs is by properly commenting your code, e.g.:
# ask the user about an optional replay
replay_answer = gets.chomp
# only accept yes/y/no/n
until replay_answer == "yes" || replay_answer == "y" || replay_answer == "no" || replay_answer == "n" do
print "Please answer with yes, y, no, or n: "
replay_answer = gets.chomp
end
## recoded this to a case, as I think it's much nicer :)
# determining whether to replay or to stop the loop
case replay_answer
when "yes", "y"
replay = true
puts "yes"
when "no", "n"
replay = false
puts "no"
replay_inner = false
end
I've modified a little your code, you should really use some decent editor with at least syntax errors highlighting. I've changed OR to AND condition in inner loop (comment in code) and added way of breaking from it when guessed number. I've also removed second occurence of code responsible of playing again, remember, DRY yourself.
replay = true
while replay
p replay
#Pre-var
print "What difficulty? (1 for easy, 2 for medium, or 3 for hard): "
difficulty = gets.chomp.to_i
until difficulty == 1 || difficulty == 2 || difficulty == 3 do
print "Please type either 1, 2, or 3: "
difficulty = gets.chomp.to_i
end
#Variables
if difficulty == 1
r = Random.new
number = r.rand(100..1000)
puts "You have 15 guesses. "
print "Guess a number with three digits: "
within_num = 50
elsif difficulty == 2
r = Random.new
number = r.rand(1000..10000)
puts "You have 15 guesses. "
print "Guess a number with four digits: "
within_num = 500
elsif difficulty == 3
r = Random.new
number = r.rand(10000..100000)
puts "You have 15 guesses. "
print "Guess a number with five digits: "
within_num = 5000
end
guess = ""
num_guess = 0
guess_array = Array.new
array_location = 0
count_through = 0
array_print = count_through - 1
replay_inner = true
#Body
puts number
while num_guess <= 14 && replay_inner == true #Keeping as <= 14 as to avoid unnecessarily rewriting code, still gives 15 guesses
guess = gets.chomp.to_i
if guess > number * 2
print "That is more than double the number. Guess again: "
elsif guess < number / 2
print "That is less than half the number. Guess again: "
elsif guess > number && guess < number + within_num #within_num: 50 for easy, 500 for medium, 5000 for hard
print "You are close. That is too big. Guess again: "
elsif guess < number && guess > number - within_num
print "You are close. That is too small. Guess again: "
elsif guess < number
print "That is too small. Guess again: " #Hinting the user to how close they are.
elsif guess > number
print "That is too big. Guess again: "
elsif guess == number
puts "Congragulations! You win!"
print "Your "
print guess_array.length
print " incorrect guesses were: "
if num_guess == 0
sleep(0.5)
print "... Oh."
else
while count_through < num_guess #Loop to relay user's guesses with a delay of 0.5 seconds
print guess_array[count_through]
if count_through == num_guess - 2
print ", and "
elsif count_through == num_guess - 1
puts ". "
else
print ", "
end
count_through += 1
sleep(0.5)
end
end
replay_inner = false # or just `break`, you have to break somehow from inner loop here
end
guess_array.push guess
num_guess += 1
#puts num_guess
#puts guess_array[array_location]
array_location += 1
if num_guess >= 15 && guess != number
puts "Sorry, you lost. "
print "Your "
print guess_array.size
print " guesses were: "
while count_through < num_guess
print guess_array[count_through] #Same as loop above; for when player fails to guess correctly
if count_through == num_guess - 2
print ", and "
elsif count_through == num_guess - 1
puts ". "
else
print ", "
end
count_through += 1
sleep(0.5)
end
end
end
puts "\nWould you like to play again? (yes/no)"
replay_answer = gets.chomp
until replay_answer == "yes" || replay_answer == "y" || replay_answer == "no" || replay_answer == "n" do
print "Please answer with yes, y, no, or n: "
replay_answer = gets.chomp
end
if replay_answer == "yes" || replay_answer == "y"
replay = true
replay_inner = true
puts "yes"
elsif replay_answer == "no" || replay_answer == "n" #Determining whether or not to replay
replay = false
replay_inner = false
puts "no"
end
end

If type is character I want to puts error

puts "Let's sum many numbers"
sum = 0
num = 0
while(num != 'x')
puts "Press a number and then Enter if you exit press 'x'"
num = gets.chomp
if num != 'x'
num = num.to_i
print "#{sum} + #{num} = "
sum += num
puts "#{sum}"
elsif num == 'x'
puts "Total sum is #{sum}"
break
else
puts "error!"
end
end
I want to make code to show error If user press char except 'x'.
How should I do?
Change your first if to a condition that checks if the input is a number, e.g.
if num =~ /\A[0..9]+\z/ # or /\A\d+\z/
The way your code is currently, all strings except 'x' are treated as number -- with value 0 in case they aren't really numbers:
'foobar'.to_i # => 0

Resources