Need program to repeat itself instead of ending - python-2.x

I'm trying to make a guessing game that allows three tries. So far, it works exactly as I want it to, but the user isn't allowed three tries. After the first, the program just ends and you have to restart it to continue playing. I don't want the program to end until three tries are finished.
How can I do this?
Current code:
from random import randint
guesses = 3
secret = randint(0, 999)
number = 1
PreGuess = input("Enter a number: ")
try:
guess = int(PreGuess)
except:
number = 0
if input:
if number == 1:
if 0 < guesses:
if 0 <= guess <= 999:
if guess < secret:
print("too low")
guesses -= 1
elif guess > secret:
print("too big")
guesses -= 1
elif guess == secret:
print("correct")
else:
print("Number is not in the playable range!")
else:
print("game over")
else:
print("Please enter a number.")

Notice that you only call input() once - at the beginning. You also do not have any loops that make the program jump back to the beginning to allow the player to make another guess.
What you should do is enclose the part that you want repeated in a while loop.
...
while guesses > 0:
PreGuess = input("Enter a number: ")
...
if input:
if number == 1:
if 0 <= guess <= 999:
if guess < secret:
print("too low")
guesses -= 1
elif guess > secret:
print("too big")
guesses -= 1
elif guess == secret:
print("correct")
break
else:
print("Number is not in the playable range!")
else:
print("Please enter a number.")
Then, after the while loop, you can check if the loop was terminated because the user won or if the user made 3 incorrect guesses. If the user made 3 incorrect guesses, guesses would equal 0, and if the user successfully guessed the number, guesses would be greater than 0.
if guesses == 0:
print("game over")

Related

Counting how many "countdown" sequences exists in array

I know this sounds kind of simple but I'm trying to get the count of "countdown" sequences that exists in my array. Example:
[1,2,3,2,5,4,3,0] - > 2 ([3,2] and [5,4,3])
I just need a little push, please!
Just iterate through the list every time the countdown breaks you increment the counter
Python, also known as pseudo code:
def count_finder(l):
prev = l[0]
counter = 0
inCount = False
for num in l[1:]:
if num == prev-1: #Checks if the previous was 1 greater than this one
inCount = True # if it is then "inCount" is True
elif num+1 != prev and inCount: #Checks if your exiting a countdown
inCount = False
counter += 1 #Increment Counter
prev = num #Change previous number to current number for next loop
if inCount: counter+=1 #If the loop ends while in a count down increment counter
return counter
print(count_finder([9, 8, 7, 6, 5, 4]))

my code result in an infinite loop

puts "enter a number"
x = gets.chomp.to_i
y = 0
while x != 1
y += 1
if x % 2 == 0
x = x / 2
else
x = x*3 + 1
end
print "#{x} "
end
puts "\nThe number of sequence is #{y+1}"
Hi, if I key in negative number or 0, I will get an infinite loop. How do I avoid entering the loop if my number is 0 or negative.
You can use x > 1 i.e
puts "enter a number"
x = gets.chomp.to_i
# if you want to consider negative as positive then x = gets.chomp.to_i.abs
y = 0
while (x > 1)
y += 1
if x % 2 == 0
x = x / 2
else
x = x*3 + 1
end
print "#{x} "
end
puts "\nThe number of sequence is #{y+1}"
Hope it helps
To answer your question:
Your code works perfectly well and does exactly what it is told to do:
while x is not 1 OR x is smaller than 0 do this codeblock.
If you set x to a negative number, x will never be a positive number, so it runs forever (because x is always smaller 0).
So, the code is correct, but there is a flaw in the logic behind it :)

Ruby armstrong numbers in a range

puts "Enter range(starts at 1), ends at the number that you enter: "
range = gets.chomp.to_i
number = 1
while number <= range
temporary_number = number
sum_angstrom = 0
number += number
while(temporary_number != 0)
digit = temporary_number % 10
temporary_number /= 10
sum_angstrom = sum_angstrom + (digit ** 3)
end
if (sum_angstrom == number)
puts number
end
end
This time, I tried to make a program to show the armstrong numbers in a range that's taken from the user's input. The program just stops after I enter the number and press enter and i can't figure out why.
Keep in mind that i can't use for(each), that's why i'm using while so often.
First of all, change number += number to number += 1; otherwise you will only test the powers of 2.
Second, move the number += 1 line at the bottom of the while block it is in. Otherwise you will always test if sum_armstrong(n) == n+1.
This works:
puts "Enter range(starts at 1), ends at the number that you enter: "
range = gets.chomp.to_i
number = 1
while number <= range
temporary_number = number
sum_angstrom = 0
while(temporary_number != 0)
digit = temporary_number % 10
temporary_number /= 10
sum_angstrom = sum_angstrom + (digit ** 3)
end
if (sum_angstrom == number)
puts number
end
number += 1
end
Armstrong Number in Ruby one liner
n = 153
s = 0
n.to_s.split("").map{|e| s+=(e.to_i*e.to_i*e.to_i)}
puts (n==s ? "Armstrong number" : "Not Armstrong number")
You can iterate in a range to print the value based on your requirement.
Main logic lies in below line.
n.to_s.split("").map{|e| s+=(e.to_i*e.to_i*e.to_i)}
Improving my answer a little bit
n.digits.map{|e| s+=(e**3)}

Ruby not incrementing number

I wrote code to find how many operations a number required under the Collatz Conjecture. However, my operations variable doesn't seem to be incrementing.
My code is:
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number =! 1
if modulo == 0
number = number / 2
operations = operations + 1
elsif modulo =! 0 && number =! 1
number = number * 3
number = number += 1
operations = operations + 2
else
puts "Uh oh, something went wrong."
end
end
puts "It took #{operations} operations!"
I am running this code on https://www.repl.it.
First of all, it's elsif; not elseif (I edited that in your question). And unequal sign is !=; not =!. But that has a somewhat different meaning. (i.e.: number =! 1 means number = !1)
In the 12th line, what is number = number += 1? I think you meant number += 1 or number = number + 1.
Now, the code works. :)
Here's the final version.
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number != 1
if modulo == 0
number = number / 2
operations = operations + 1
elsif modulo != 0 && number != 1
number = number * 3
number = number + 1
operations = operations + 2
else
puts "Uh oh, something went wrong."
end
end
puts "It took #{operations} operations!"
Usage:
Please input a number
256
It took 8 operations!
An optimal solution using functions:
def collatz(n)
if n % 2 == 0
return n / 2
else
return 3*n + 1
end
end
def chainLength(num)
count = 1
while num > 1
count += 1
num = collatz(num)
end
return count
end
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = chainLength(number)
puts "It took #{operations} operations!"
If you need more performance, read about dynamic programming and memoization techniques.

how to use next on ruby for this case?

I'm learning Ruby On Rails program and I've came to a road block on one of the lessons. The assignment has me creating an odd numbers for the script to read starting from "20 to 0" using the next component. This is the example they've given me to change :
i = 20
loop do
i -= 1
print "#{i}"
break if i <= 0
end
This is the problem:
Add a line to your loop before your print statement. Use the next keyword so that you skip to the next iteration if the number i is odd.
How do I accomplish this?
You can just insert a next that skips the rest of the loop if the number is odd:
i = 20
loop do
i -= 1
next if i.odd?
puts "#{i}"
break if i <= 0
end
I would solve it this way:
i = 20
loop do
i -= 1
next if i%2 != 0
print "#{i}"
break if i <= 0
end
i = 20
loop do
i -= 1
next if i % 2 == 0
print "#{i}"
break if i <=1
end

Resources