I'm a new programmer and I was struggling with a solution to this problem:
User Input with Loops and Conditionals. Use raw_input() to prompt for a number
between 1 and 100. If the input matches criteria, indicate so on the screen and exit.
Otherwise, display an error and re-prompt the user until the correct input is received.
My last attempt finally worked but I'm interested to know your more elegant solutions, my memory appreciates all of your input :P
n = int(input("Type a number between 1 and 100 inclusive: "))
if 1 <= n <= 100:
print("Well done!" + " The number " + str(n) + " satisfies the condition.")
else:
while (1 <= n <= 100) != True:
print("Error!")
n = int(input("Type a number between 1 and 100: "))
else:
print ("Thank goodness! I was running out of memory here!")
You can simplify the code, using a single loop:
while True:
n = int(input("Type a number between 1 and 100 inclusive: "))
if 1 <= n <= 100:
print("Well done!" + " The number " + str(n) + " satisfies the condition.")
print ("Thank goodness! I was running out of memory here!")
break # if we are here n was in the range 1-100
print("Error!") # if we are here it was not
You just print the output and break if the user enters a correct number or print("Error!") will be printed and the user will be asked again.
On a side note, if you are using python2, input is the equivalent to eval(raw_input()), if you are taking user input you should generally use raw_input as per the instructions in your question.
Related
Apologies if the question to this is worded a bit poorly, but I can't seem to find help on this exercise anywhere. I am writing a basic Python script which sums two numbers together, but if both numbers inputted are the same the sum will not be calculated.
while True:
print('Please enter a number ')
num1 = input()
print('Please enter a second number ')
num2 = input()
if num1 == num2:
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
If both numbers are equal I want the script to loop back once more and if the numbers inputted are equal again I want the program to end. With the code I have provided the issue I am having is that when I enter two equal numbers it keeps constantly looping until I enter two different numbers.
You would likely want to have a variable keeping track of the number of times that the numbers were matching. Then do something if that counter (keeping track of the matching) is over a certain threshold. Try something like
matches = 0
while True:
num1 = input('Please enter a number: ')
num2 = input('Please enter a second number: ')
if num1 == num2 and matches < 1:
matches += 1
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
You can add give input code again inside first if statement or use some other dummy variable for loop so that you can break the loop, for e.g. use while j == 0 and increase it j += 1when you are inside the first if statement
continue skips the execution of everything else in the loop. I don't see it much useful in your example. If you want to print the sum then just remove it.
How continue works can be demonstrated by this sample (taken from python docs)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Result
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
I am completing questions from a python book when I came across this question.
Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.
My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.
#Avg, Sum, and count program
total = 0
count = 0
avg = 0
num = None
# Ask user to input number, if number is 0 print calculations
while (num != 0):
try:
num = float(input('(Enter \'0\' when complete.) Enter num: '))
except:
print('Error, invalid input.')
continue
count = count + 1
total = total + num
avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))
Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.
Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.
while True:
num = input('(Enter \'done\' when complete.) Enter num: ')
if num == 'done':
break
try:
num = float(num)
except ValueError:
print('Error, invalid input.')
continue
I think a better approach that would solve your problem would be as following :
input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
num = float(input_str)
else:
if (input_str == "done"):
done()
else:
error()
This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).
#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user invalid guess and do not count that as an attempt
My problem is that even if the user guesses a number between 0 and 100, it still prints out the "Invalid guess. Try again". How do I control my loop to skip past the print statement and question repeat if it's acceptable input(1-100)? Thanks in advance!
favoriteNumber = 7
attempts = 0
guess = raw_input("Guess a number between 0 and 100: ")
if (guess < 0) or (guess > 100):
print "Invalid guess. Try again"
guess = raw_input("Guess a number between 0 and 100: ")
attempts1 = str(attempts)
print "it took " + attempts1 + "attempts."
Use input and not raw_input,so you get integer and not string
favoriteNumber = 7
attempts = 0
while True:
guess = input("Guess a number between 0 and 100: ")
if (guess < 0) or (guess > 100):
attempts=attempts+1
print "Invalid guess. Try again"
else:
attempts=attempts+1
break
attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."
In Python 2.7.10 it appears that if you do not convert a string to an integer, it accepts it but all rules that apply to numbers return false.
Here is a working example:
favoriteNumber = 7
attempts = 0
guess = raw_input("Guess a number between 0 and 100: ")
if (int(guess) < 0) or (int(guess) > 100):
print "Invalid guess. Try again"
guess = raw_input("Guess a number between 0 and 100: ")
attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."
In Python 3.4 the original code yields an error where it tells you that it is a string instead of an integer. But, like Paul said you could put raw_input inside of an int() command.
you raw_input returns a string, which is always > 100. Cast it to a number with int(raw_input())
I'm currently working on a program in Python and I need to figure out how to convert a string value to a float value.
The program will ask the user to enter a number, and uses a loop to continue asking for more numbers. The user must enter 0 to stop the loop (at which point, the program will give the user the average of all the numbers they entered).
What I want to do is allow the user to enter the word 'stop' instead of 0 to stop the loop. I've tried making a variable for stop = 0, but this causes the program to give me the following error message:
ValueError: could not convert string to float: 'stop'
So how do I make it so that 'stop' can be something the user can enter to stop the loop? Please let me know what I can do to convert the string to float. Thank you so much for your help! :)
Here is some of my code:
count = 0
total = 0
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
if (number == 0):
if (count == 0):
print("")
print("Total: 0")
print("Count: 0")
print("Average: 0")
print("")
print("Your average is equal to 0. Cool! ")
else:
print("")
print("Total: " , "%.0f" % total)
print("Count: " , count)
print("Average: " , total / count)
Please let me know what I should do. Thanks.
I'd check the input to see if it equals stop first and if it doesn't I'd try to convert it to float.
if input == "stop":
stop()
else:
value = float(input)
Looking at your code sample I'd do something like this:
userinput = input("Enter a number (0, or the word 'stop', to stop): ")
while (userinput != "stop"):
total += float(userinput) #This is not very faulttolerant.
...
You could tell the user to enter an illegal value - like maybe your program has no use for negative numbers.
Better, would be to test if the string you've just read from sys.stdin.readline() is "stop" before converting to float.
You don't need to convert the string to a float. From what you've said it appears that entering 0 already stops the loop, so all you need to do is edit you're currently existing condition check, replacing 0 with "stop".
Note a few things: if the input is stop it will stop the loop, if it's not a valid number, it will just inform the user that the input were invalid.
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
user_input = input("Enter a number (0, or the word 'stop', to stop): ")
try:
if str(user_input) == "stop":
number = 0
break
else:
number = float(user_input)
except ValueError:
print("Oops! That was no valid number. Try again...")
PS: note that keeped your code "as is" mostly, but you should be aware to not use explicit counters in python search for enumerate...
for lp in range(100):
if guess == number:
break
if guess < number:
print "Nah m8, Higher."
else:
print "Nah m8, lower."
This is some basic code that I was told to make for a basic computing class. My aim is to make a simple 'game' where the user has to guess a random number that the computer has picked (1-100) This is a small section of the code where I want to continue checking if the guess is equal to, lower or higher than the number; but if I put a print statement below, it will print the text 100 times. How can I remove this problem?
Thanks in advance.
It seems like you're omitting the guessing stage. Where is the program asking the user for input?
Ask them at the beginning of the loop!
for lp in range(100):
guess = int(input('Guess number {0}:'.format(lp + 1)))
...
You need to get a new input each time through your loop; otherwise you just keep checking the same things.
for lp in range(100):
if guess == number:
break
if guess < number:
# Get a new guess!
guess = int(raw_input("Nah m8, Higher."))
else:
# Get a new guess!
guess = int(raw_input("Nah m8, lower."))
You should ask for a guess inside the loop:
while True:
guess = int(raw_input("Guess: "))
if guess == number:
break
if guess < number:
print "Nah m8, Higher."
else:
print "Nah m8, lower."
import random
number = 0
x = []
while number < 100:
guess = random.randint(1,100)
if number < guess:
print(f 'Number {number} is less than guess {guess}')
elif number > guess:
print(f 'Number {number} is greater than guess {guess}')
number += 1
This will work for you