while True:
# main program
number = (" ")
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer in y, n:
break
print("Invalid input.")
if answer == 'y':
continue
else:
print 'Goodbye'
break
Essentially I want the program to restart when the user enters 'y' as a response to 'run again?' Any help would be vastly appreciated. Thanks.
As #burhan suggested, simply wrap your main program inside a function. BTW, your code has some bugs which could use some help:
if answer in y, n: - you probably mean if answer not in ('y', 'n'):
number = (" ") is an irrelevant line
while True makes no sense in your main program
print("Invalid input.") is below a break, thus it'll never be executed
So you'll have something like:
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
break
if answer == 'y':
main()
else:
print("Goodbye")
break
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
if answer == 'y':
main()
else:
print 'Goodbye'
if __name__ == '__main__':
main()
You should probably add a few checks to handle cases when users enter non-number input etc.
Your code looks really messed up. Try to write some better(clean) code next time.
while True:
total = 0
num1 = int(input("enter a number"))
num2 = int(input("enter a number"))
num3 = int(input("enter a number"))
total = num1 + num2 + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
con = int(input("Run again? 1/0: "))
if con==0:
break
Related
I'm trying to write a basic code that prompts the user for a list of numbers as separate inputs, that then identifies the largest and smallest number. If the user enters anything other than a number the code should return an "invalid input" message. The code seems to run through the two inputs once, but then the while input seems completely broken and I'm not sure where its going wrong.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
If you check your exit condition of "done" and if the input is not "done" then convert the string to an integer.
Then all the if conditions would correctly and your while loop should run.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
num = int(num)
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
heres a simple way to do it:
lst = []
while True:
try:
lst.append(int(input("enter a number: ")))
except:
break
print(f"max is {max(lst)}")
print(f"min is {min(lst)}")
enter a number: 10
enter a number: 22
enter a number: 11
enter a number: 22
enter a number: 4
enter a number: done
max is 22
min is 4
In addition to other corrections:
largest = None
smallest = None
try:
num1 = int(input("Enter a number: "))
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if str(num) == "done" :
break
if int(num) > largest:
largest = num
if int(num) < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
I am learning python and I cannot figure out how to get back to a certain part of loop depending on the response.
If it reaches:
else :
print('Answer must be yes or no')
I want it to start back at:
print ("We are going to add numbers.")
I have tried several different suggestions I have seen on here, but they result in starting back at the very beginning.
My code:
import random
num1 = random.randint(1,100)
num2 = random.randint(1,100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print ("Nice to meet you " + name)
print ("We are going to add numbers.")
print ("Does that sound good?")
answer = str.lower(input())
if answer == str('yes'):
print ('Yay!!')
print ('Add these numbers')
print (num1, num2)
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())
elif answer == str('no'):
print ('Goodbye')
else :
print('Answer must be yes or no')
You need a loop that starts with the thing you want to get back to:
def start():
import random
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print("Nice to meet you " + name)
while True:
print("We are going to add numbers.")
print("Does that sound good?")
answer = str.lower(input())
if answer == "no":
print("Goodbye")
return
elif answer == "yes":
break
else:
print('Answer must be yes or no')
print('Yay!!')
print('Add these numbers')
print(num1, num2)
# This following part might want to be a loop too?
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())
How to write a condition in a function to make this comment "Please provide two integers or floats"
Now I have a ValueError like " could not convert string or float "
def divede():
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
num1, num2 = divede()
while True:
if num2 == []:
print("Please provide two integers or floats")
elif num2 != 0:
print(f"{num1} / {num2} is {num1/num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
def divede():
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
num1, num2 = divede()
while True:
if num2 == []:
print("Please provide two integers or floats")
elif num2 != 0:
print(f"{num1} / {num2} is {num1/num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
here I have a problem:
while True:
if num2 == []: # wrong condition
print("Please provide two integers or floats")
Thx for all answers
Change your division function to this:
def divede():
num1 = input("Enter first number:")
num2 = input("Enter second number:")
try:
num1, num2 = float(num1), float(num2)
except ValueError:
print("Invalid entry, please enter numbers")
return divede()
return num1, num2
In that case you do not need the first if in your while loop.
My code is too complicate :)
correct answer is :
def divide(a,b):
try:
total = a / b
except TypeError:
return "Please provide two integers or floats"
except ZeroDivisionError:
return "Please do not divide by zero"
return total
The error you get arises as soon as you try to convert your string input to float in one of the following lines:
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
I would suggest you change your divede function to the following:
def divede():
while True:
try:
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
except(ValueError):
print("Please provide two integers or floats")
The while loop makes sure that the user is asked for repeating input until he actually provides two numbers.
The except(ValueError) is there to catch only the specific errors you want.
Then you also need to change the rest of the script like so:
while True:
if num2 != 0:
print(f"{num1} / {num2} is {num1 / num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
I'm new here in this "world".
I tried to create a calculator with Python,here's the code.
When I try to run it,IDLE gives me errors,can you help me,please? :D
Header 1
print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "add" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "subtract" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is" + result)
elif user_input == "multiply" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "divide" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
else:
print("Unknown command")
Try this (you don't have loop so use exit() rather than break, also use the right operators for add, divide, sub-struct, multiply.
from __future__ import division # to support division
print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
user_input = raw_input(": ")
if user_input == "quit":
exit() #break is uesd in loops
elif user_input == "add" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "subtract" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1-num2)
print("The answer is" + result)
elif user_input == "multiply" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1*num2)
print("The answer is " + result)
elif user_input == "divide" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1/num2)
print("The answer is " + result)
else:
print("Unknown command")
The problem is the break statement here:
if user_input == "quit":
break
You can only use a break statement within a while and/or for loop.
The solution is to replace the break statement with print() or exit() instead.
For your program to be more effective (and to be able to use the break statement), you could execute your if,elif and else statements within a while loop:
print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
while True:
user_input = input(": ")
if user_input == "quit":
print('Program terminated')
break
elif user_input == "add" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "subtract" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is" + result)
elif user_input == "multiply" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "divide" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
else:
print("Unknown command")
The problem is you are implementing a break that is not in a while loop.
Breaks must occur in a while loop. So a way of getting around this problem is by saying:
if user_input == "quit":
exit()
Example2:
import sys
if user_input == "quit":
sys.exit()
Hope this helped!
if user_input == 'quit':
#break
pass
I am trying to create a loop that will get me asking for a user's bet until it runs out of money or decides to quit. How can i take inputs from the different functions?
import random
import sys
def greeting():
print('COP1000 Slot Machine - Jesus Pacheco')
print('Let\'s play slots!')
# Function ask user starting amout to bet
# then it will check for any input error
def intro():
greeting()
print('How much money do you want to start with?')
print('Enter the starting amount of dollars.', end='')
total = int(input())
print('Your current total is '+ str(total)+'\n')
while True:
print('How much money do you want to bet (enter 0 to quit)?', end='');
# Bett will be the amount of money that the player will bet
bett = int(input())
if bett == 0:
sys.exit()
if bett > int(total):
print('ERROR You don\'t have that much left')
elif bett < int(0):
print('ERROR: Invalid bet amount\n')
else:
break
# Function will ask user to press enter to play slot machine
def slotMachine():
print('Press enter to pull slot machine handle!')
input()
# Function shows results of slot machine after handle being pulled
def random():
import random
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
num3 = random.randint(1, 5)
print('/---+---+---\ ')
print('|-'+ str (num1)+'-|-'+ str(num2) +'-|-'+ str (num3) +'-|')
print('\---+---+---/ ')
if num1 == num2 and num2 == num3:
print('JACKPOT! cha-ching, you win')
if num1 == num3 or num2 == num3:
print('Match two, you get your bet back!')
else:
print('sorry, no match')
intro()
slotMachine()
random()
input()
What you need to do is create a way to get input, return it, check if it is valid, then call the slot-machine function. Also, you can use input(s); s is the prompt you want to show (s is usually a string). I suggest housing this all under a main() function:
import sys
import random
def main():
intro()
total = int(input('Starting Money: '))
if total <= 0:
raise ValueError('Starting Money must be greater than 0.')
# the above raises an error if the bet is less than 0
while True:
bet = getInput(total)
total = slotMachine(total, bet)
if total == 'win' or total <= 0:
break
def intro():
print('COP1000 Slot Machine - Jesus Pacheco')
print("Let's play slots!")
def getInput(total):
userInput = int(input('Bet (0 to quit): '))
if userInput > total or userInput < 0:
raise ValueError('Bet must be less than total and greater than 0.')
if userInput== 0:
sys.exit()
# the above raises an error if the bet is less than 0 or greater than the total
return userInput
def slotMachine(total, bet):
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
num3 = random.randint(1, 5)
print('/---+---+---\ ')
print('|-'+ str(num1)+'-|-'+ str(num2) +'-|-'+ str(num3) +'-|')
print('\---+---+---/ ')
if num1 == num2 and num2 == num3:
print('JACKPOT! Cha-Ching, you win!')
return 'win'
elif num1 == num3 or num2 == num3:
print('Match two, you get your bet back!')
return total
else:
print('Sorry, no match.')
return total - bet
main()
I suggest you read about functions and return statements.