How can I get this program to stop at when the number 13 is entered?
print "\t:-- Enter a Multiplication --: \n"
x = ("Enter the first number: ")
y = ("Enter your second number to multiply by: ")
for total in range(1, 12):
x = input("Enter a number: ")
y = input("Multiplied by this: ")
print "\n TOTAL: "
print x, "X", y, "=", (x * y)
#Exits the program.
raw_input("\t\tPress Enter to Exit")
If I understand what you are trying to do here, I think an if statement would be a better solution. Something like this:
print("Enter a multiplication")
x = int(input("Enter a number: "))
y = int(input("Multiplied by this: "))
def multiply(x, y):
if 1 < x < 13 and 1 < y < 13:
answer = x * y
print("Total:")
print("%s X %s = %s" % (x, y, answer))
else:
print("Your number is out of range")
multiply(x, y)
But to be honest, there are quite a few parts of your code that some work.
You used a for loop; this is appropriate when you know before you enter the loop how many times you want to execute it. This is not the problem you have. Instead, use a while loop; this keeps going until a particular condition occurs.
Try something like this:
# Get the first input:
x = input("Enter a number (13 to quit): ")
# Check NOW to see whether we have to quit
while x <= 12:
# As long as the first number is acceptable,
# get the second and print the product.
y = input("Multiplied by this: ")
print "\n TOTAL: \n", x, "X", y, "=", (x * y)
# Get another 'x' value before going back to the top.
x = input("Enter a number (13 to quit): ")
# -- Here, you're done with doing products.
# -- Continue as you wish, such as printing a "times table".
Related
I have to make a program using while that:
Will ask for user to put 2 integer numbers
and give back the addition and multiplication
of those 2.
Will check if the numbers are integers.
Will close if the user uses the word stop.
I have made 1 and 2 but am stuck on 3. Here is what I wrote:
while True:
try:
x = int(input("Give an integer for x"))
c = int(input("Give an integer for c"))
if x=="stop":
break
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Your code isn't working because you are starting off by defining x as an integer, and for it to equal "stop", it needs to be a string.
What you therefore want to do is allow x to be input as a string, and then convert it to an integer if it isn't stop:
while True:
try:
x = input("Give an integer for x")
if x=="stop":
break
else:
x = int(x)
c = int(input("Give an integer for c"))
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Just a slight change is required (and you can be slightly more structured using else in your try block.
You need to input the first value as a string so that you can first test it for "stop" and only then try to convert it to an integer:
while True:
try:
inp = input("Give an integer for x: ")
if inp == "stop":
break
x = int(inp)
c = int(input("Give an integer for c: "))
except:
print("Try again and use an integer please!")
else:
t = x + c
f = x * c
print("the results are", t, f)
I have also fixed up some spacing issues (i.e. extra spaces and missing spaces in your strings).
I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.
So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:
x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
What would you do?
There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:
import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
continue jumps to the next iteration of the loop, and break terminates the loop altogether.
(Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)
Python does not support goto or anything equivalent.
You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the control flow page for more information.
x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
In many other cases, you'll want to use a function to handle the logic you want to use a goto statement for.
You can use infinite loop, and also explicit break if necessary.
x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break
myList = []
numbers = int(input("How many numbers would you like to enter? "))
for numbers in range(1,numbers + 1):
x = int(input("Please enter number %i: " %(numbers)))
myList.append(x)
b = sum(x for x in myList if x < 0)
for x in myList:
print("Sum of negatives = %r" %(b))
break
c = sum(x for x in myList if x > 0)
for x in myList:
print("Sum of positives = %r" %(c))
break
d = sum(myList)
for x in myList:
print("Sum of all numbers = %r" %(d))
break
I need to figure out how to ask the user if they'd like to use the program again. I haven't learned functions yet, and every time I try to put the entire program into a "while True:" loop, it will only repeat "How many numbers would you like to enter?" Any help is appreciated, I'm inexperienced with python and this has been frustrating!
You can try something like this:
Keep a variable which asks the users if they want to play the game or not and in the end ask them again.
k = input("Do you want to play the game? Press y/n")
while k == 'y':
myList = []
numbers = int(input("How many numbers would you like to enter? "))
for numbers in range(1,numbers + 1):
x = int(input("Please enter number %i: " %(numbers)))
myList.append(x)
b = sum(x for x in myList if x < 0)
for x in myList:
print("Sum of negatives = %r" %(b))
break
c = sum(x for x in myList if x > 0)
for x in myList:
print("Sum of positives = %r" %(c))
break
d = sum(myList)
for x in myList:
print("Sum of all numbers = %r" %(d))
break
k = input("Do you want to play again? y/n")
You're exiting the loop when you hit break, so that won't work either.
Use a while loop, and think of the problem in another way: Assume the user will enter more input, and ask if he/she wants to quit.
I think this is what you're looking for (assuming you're using Python 3):
myList = []
# This variable will change to False when we need to stop.
flag = True
# Run the loop until the user enters the word 'exit'
# (I'm assuming there's no further error checking in this simple example)
while flag:
user_input = input("Please enter a number. Type 'q' to quit. ")
if user_input == 'q':
flag = False
elif ( . . . ): //do other input validation (optional)
pass
else:
myList.append(int(user_input))
print "The sum of negatives is %d" % sum([i for i in myList if i<0])
print "The sum of positives is %d" % sum([i for i in myList if i>0])
print "The sum of all numbers is %d" % sum([i for i in myList])
I'm working my way through the Code Academy Python course and have been trying to build small side projects to help reinforce the lessons.
I'm currently working on a number game. I want the program to select a random number between 1 and 10 and the user to input a guess.
Then the program will return a message saying you win or a prompt to pick another higher/lower number.
My code is listed below. I can't get it to reiterate the process with the second user input.
I don't really want an answer, just a hint.
import random
random.seed()
print "Play the Number Game!"
x = raw_input("Enter a whole number between 1 and 10:")
y = random.randrange(1, 10, 1)
#Add for loop in here to make the game repeat until correct guess?
if x == y:
print "You win."
print "Your number was ", x, " and my number was ", y
elif x > y:
x = raw_input("Your number was too high, pick a lower one: ")
elif x < y:
x = raw_input("Your number was too low, pick a higher one: ")
You need use a while loop like while x != y:. Here is more info about the while loop.
And you can only use
import random
y = random.randint(1, 10)
instead other random function.
And I think you should learn about int() function at here.
These are my hints :)
import random
n = random.randint(1, 10)
g = int(raw_input("Enter a whole number between 1 and 10: "))
while g != n:
if g > n:
g = int(raw_input("Your number was too high, pick a lower one: "))
elif g < n:
g = int(raw_input("Your number was too low, pick a higher one: "))
else:
print "You win."
print "Your number was ", g, " and my number was ", n
Code:
def Division():
print "************************\n""********DIVISION********\n""************************"
counter = 0
import random
x = random.randint(1,10)
y = random.randint(1,10)
answer = x/y
print "What will be the result of " + str(x) + '/' + str(y) + " ?"
print "\n"
userAnswer = input ("Enter result: ")
if userAnswer == answer:
print ("Well done!")
print "\n"
userInput = raw_input ("Do you want to continue? \n Enter 'y' for yes or 'n' for no.")
if userInput == "y":
print "\n"
Division()
else:
print "\n"
Menu()
else:
while userAnswer != answer:
counter += 1
print "Try again"
userAnswer = input ("Enter result: ")
if counter == 3: break
userInput = raw_input ("Do you want to continue? \n Enter 'y' for yes or 'n' for no.")
if userInput == "y":
print "\n"
Division()
else:
print "\n"
Menu()
In this case I want x value to be always bigger than y value. How to do I do it?
Code for subtraction is similar and the question remains the same, target is to avoid
negative result.
You can check if x < y and swap them e.g.
if x < y:
x, y = y, x
Note in python you can swap two variables without need of a temporary variable.
You can even take further shortcut by using bultin min and max and do it in a single line e.g.
x, y = max(x,y), min(x,y)
In addition to Anrag Uniyal's answer, you might also try this:
y,x = sorted([x,y])
You can do randint between x and 10 to get a number greater than x:
x = random.randint(1,10)
y = random.randint(x,10)