Program Doesn't Finish Whole Script - syntax

I am starting a program in which you have to pick a mode, operation, and then it will calculate it for you. It is still a work in progress.
However, I am running into a problem where it works if you input "A" or "B", and it also works when you input the "sign" or operation. However after the user inputs a sign it finishes the program and exits the code.
I need some feedback on this situation:
My end goal is for the program to also ask the user for input of the numbers they want to calculate, but the program doesn't ask the user for their input. I feel as if this problem has to deal with the float (inputs, elifs'(if then else), or how it is stuck in the parameters of the function.
import fractions
print("Welcome to Advanced Calculator Version 1.01")
module = input("Enter a mode, for example; 1NUMBER_OPERATIONS [A], or 2NUMBER_OPERATIONS [B]")
if module == "A":
operation = input('Enter an operation, for example; sq_rt,fraction,percent,round')
elif module == "B":
operation = input('Enter an operation, for example; -,+,*,/,^')
def doublecheck():
#OPERATION|||MODESA
if operation == "-":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 - num2
print(result)
elif operation == "+":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 + num2
print(result)
elif operation == "*":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 * num2
print(result)
elif operation == "/":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 / num2
print(result)
elif operation == "^":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1^num2
print(result)
elif operation == "sq_rt":
num1 = float(input("Enter a number: "))
num_sqrt = num1 ** 0.5
print('The square root of %0.3f is %0.3f' % (num1,num_sqrt))
elif operation == "fraction":
num1 = float(input("Enter a number: "))
str(fractions.Fraction(num1))
elif operation == "percent":
num1 = float(input("Enter a number: "))
v = 100
percent= num1 * v
print(percent + "%")
elif operation == "round":
num1 = float(input("Enter a number: "))
round(num1)
return 0

You need to call your function too. Check the last line. Also indent your return 0 statement.
import fractions
print("Welcome to Advanced Calculator Version 1.01")
module = input("Enter a mode, for example; 1NUMBER_OPERATIONS [A], or 2NUMBER_OPERATIONS [B]")
if module == "A":
operation = input('Enter an operation, for example; sq_rt,fraction,percent,round')
elif module == "B":
operation = input('Enter an operation, for example; -,+,*,/,^')
def doublecheck():
#OPERATION|||MODESA
if operation == "-":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 - num2
print(result)
elif operation == "+":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 + num2
print(result)
elif operation == "*":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 * num2
print(result)
elif operation == "/":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 / num2
print(result)
elif operation == "^":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1^num2
print(result)
elif operation == "sq_rt":
num1 = float(input("Enter a number: "))
num_sqrt = num1 ** 0.5
print('The square root of %0.3f is %0.3f' % (num1,num_sqrt))
elif operation == "fraction":
num1 = float(input("Enter a number: "))
str(fractions.Fraction(num1))
elif operation == "percent":
num1 = float(input("Enter a number: "))
v = 100
percent= num1 * v
print(percent + "%")
elif operation == "round":
num1 = float(input("Enter a number: "))
round(num1)
return 0
doublecheck()

Related

Fibonacci Series using classes and methods

I have written a fibonacci series method and tried calling it. It works fine with the following code:
module Fibonacci
class Operation
def fibonacci(n)
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
res.fibonacci(n)
end
But I want to have a seperate method for accepting input within the class and calling it.
module Fibonacci
class Operation
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
end
def fibonacci(n)
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
res.input
res.fibonacci(n)
end
Getting an Error!..I'm a newbie, Would be helpful if I get a support..Thank You
As it stands, your code doesn't use the return value of your input function; it disappears into the ether, and your caller has an undefined n it's attempting to access. If you write your calling code as:
res = Operation.new
res.fibonacci(res.input)
Then you pass the return value from res.input into res.fibonacci and your immediate problem is resolved.
Beyond this, I believe there are noteworthy design issues in your code which you may consider. Functions should be modular and avoid side-effects such as printing, which severely limit their usefulness and flexibility. What if you wish to generate Fibonacci numbers and use them for something else in your program? You have to rewrite the whole function again. If you write it once to populate and return an array, you let the caller decide whether to print the output, save it in a database, send it through a socket, reverse it, send it into another function (you get the idea).
Seek to avoid hard-coded values like string and numbers. Your input function can't work for anything but collecting Fibonacci numbers. What if you let the caller decide what the message is? Then, when you add more math functions to your Operation class, you can reuse the same input routine.
I would also contend that a function like input doesn't belong in an Operator class. I can see it used as a utility function in that class, but it's independent of Operator-like stuff and is too small to warrant its own function in any case.
Here's a re-write that somewhat mitigates these issues:
module Fibonacci
class Operation
def input(message)
puts message
gets.chomp.to_i
end
def fibonacci(n)
num1 = 0
num2 = 1
result = []
while num2 < n
result << num2
num1, num2 = num2, num1 + num2
end
result
end
end
res = Operation.new
puts res.fibonacci(res.input 'Enter the number upto which Fibonacci needs to be printed:')
end
And a sample run:
Enter the number upto which Fibonacci needs to be printed:
15
1
1
2
3
5
8
13
Change code to:
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
fibonacci(n)
end
And remove res.fibonacci(n).
Here is the full code:
module Fibonacci
class Operation
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
fibonacci(n)
end
def fibonacci(n)
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
res.input
end
Hope this helped.
It could incredibly help if you have specified what exact error do you have, but let me guess: it’s kinda “NameError: undefined local variable or method `n'”
That happens because you have not passed an argument in your call to fibonacci. You have an option to fallback to getting the variable from the user input if none was specified:
class Operation
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
gets.chomp.to_i
end
def fibonacci(n = -1)
# HERE
n = input if n <= 0
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
res.fibonacci(5)
#⇒ 1 1 2 3
res.fibonacci
#⇒ 'Enter the number ...'

how to print same randomint after if/elif?

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"

Using multiple else if statements

I was trying to make a calculator in VBScript to test my skill, but came across an error. My program uses multiple else if statement to test what the user has input.
Here is my code below:
Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans
head = "Calculator"
msg1 = msgBox("Ruan's Vbscript calculator",0,head)
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
num1 = inputBox("Enter your first number",head)
num2 = inputBox("Enter your second number",head)
if (input1 = vbcancel) then
wscript.quit()
else if (input1 = "+") then
ans = num1 + num2
else if (input1 = "-") then
ans = num1 - num2
else if (input1 = "*") then
ans = num1 * num2
else if (input1 = "/") then
ans = num1 / num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
msgAns = msgBox "Your answere is: " + head
When I run the program, the error says: "Expected end of statement". I don't see the problem here, as I have end if after all those else if statements.
Remove the space between else and if and make it elseif. Like this:
if (input1 = vbcancel) then
wscript.quit()
elseif (input1 = "+") then
ans = num1 + num2
elseif (input1 = "-") then
ans = num1 - num2
elseif (input1 = "*") then
ans = num1 * num2
elseif (input1 = "/") then
ans = num1 / num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
With the additional space between else and if you start a new if statement nested in the else branch rather than continuing the first if statement. The nested if statements require end ifs of their own, which is why you're getting the error.
Minimal improvements to make it work:
Option Explicit
Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans
head = "Calculator"
msgBox "Ruan's Vbscript calculator", 0, head
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
If Not IsEmpty(input1) Then
num1 = CDbl(inputBox("Enter your first number",head))
num2 = CDbl(inputBox("Enter your second number",head))
if input1 = "+" then
ans = num1 + num2
elseif input1 = "-" then
ans = num1 - num2
elseif input1 = "*" then
ans = num1 * num2
elseif input1 = "/" then
ans = num1 / num2
elseif input1 = "\" then
ans = num1 \ num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
msgBox "Your answere is: " & ans
else
msgBox "Aborted"
end if
Type and range checks for the operants left as execise.
A Select Case is usually a simpler/clearer construction for selecting operations based on a single variables value
Select Case input1
Case vbCancel
wscript.quit()
Case "+"
ans = num1 + num2
Case "-"
ans = num1 - num2
Case "*"
ans = num1 * num2
Case "/", "\" '//multiples
ans = num1 / num2
Case Else
msgBox "Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces", , "Error"
End Select

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