Output not as expected when programs ran - python

I have this program I coded where a computer guesses a random number, but the output isn't as expected with the assignmets output.
import random
import math
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
count = 0
print()
while True:
count += 1
myNumber = (smaller + larger)/2
print("%d %d" %(smaller, larger))
print('Your number is %d' % myNumber)
choice = input('Enter =, <, or >:')
if choice == '=':
print("Hooray, I've got it in %d tries" % count)
break
elif smaller == larger:
print("I'm out of guesses, and you cheated")
break
elif choice == '<':
larger = myNumber - 1
else:
smaller = myNumber + 1

I tested your code and it seems to work.
Are you sure when testing you didn't introduce a weird character in your input? like '< ' (with the space)?
Something you could do would be to do input validation before checking the case and do something else if you detect the character is wrong.

Related

Average and Sums Task

Basic task of making code that can find the sum & average of 10 numbers from the user.
My current situation so far:
Sum = 0
print("Please Enter 10 Numbers\n")
for i in range (1,11):
num = int(input("Number %d =" %i))
sum = Sum + num
avg = Sum / 10
However, I want to make it so that if the user inputs an answer such as "Number 2 = 1sd" it doesn't stop the code immediately. Instead I'm looking for it to respond as "Invalid input. Try again" and then it restarts from the failed input.
e.g.
"Number 2 = 1sd"
"Invalid input. Try again."
"Number 2 = ..."
How would I achieve that?
You can output an error message and prompt for re-entry of the ith number by prompting in a loop which outputs an error message and reprompts on user input error. This can be done by handling the ValueError exception that is raised when the input to the int() function is an invalid integer object string initializer such as as "1sd". That can be done by catching that exception, outputting Invalid input. Try again. and continuing when that occurs.
One possible resulting code that may satisfy your requirements is:
Sum = 0
print("Please Enter 10 Numbers\n")
for i in range (1,11):
num = None
while num is None:
try:
num = int(input("Number %d =" %i))
except ValueError:
print('Invalid input. Try again.')
sum = Sum + num
avg = Sum / 10
This one is working for me.
sum_result = 0
print("Please Enter 10 Numbers\n")
for i in range (1,11):
try:
num = int(input("Number %d =" %i))
sum_result = sum_result + num
except Exception:
print("Please try again")
num = int(input("Number %d =" %i))
sum_result = sum_result + num
avg_result = sum_result / 10
print(sum_result)
print(avg_result)
Suggestions:
Check the conventions for name variables in python, you are using builtin functions, which can be an issue in your code.
When you are dealing with user inputs, usually you need error handling, so try, except, else, finally, are the way to go.
When you have a code similar to this use, you normally name a function to do these tasks.
You can do:
while True:
try:
num = int(input('Enter an integer: '))
break
except Exception:
print('Invalid input')
#now num is an integer and we can proceed
you can check the input, then continue or return an error, something like this:
sum = 0
print('Please Enter 100 Numbers:\n')
for i in range(1, 11):
num = input('Number %d' % i)
while not num.isdigit():
print('Invalid input. Try again.')
num = input('Number %d' % i)
sum += int(num)
avg = sum / 10
print('Average is %d' % avg)
from statistics import mean
i=0
number_list = []
while i <= 9:
num = input("Please Enter 10 Numbers\n")
if num.isdigit() ==False:
print('Invalid input. Try again.')
num
else:
number_list.append(int(num))
i +=1
print(sum(number_list))
print(mean(number_list))
If your data is not too much, I think put them in a list is better. Because you can easier change program to calculate others if you want.
nums = [] # a list only store valid numbers
while len(nums) < 10:
input_n = input("Number %d = " % (len(nums) + 1))
if input_n.isdigit():
n = int(input_n)
nums.append(n)
else:
print("Invalid input. Try again.")
# average is more commonly known as a float type. so I use %f.
print("Average = %f" % (sum(nums) / len(nums)))

how to add score and loop through game

import random
x = 50
score = 0
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
while True:
if int(input('Guess: ')) == number:
print('You got it')
break
else:
print('Try again!')
What the code does so far is takes a random integer between 1 and whatever number I want. It tells me which numbers it is divisible by between 1-9 and also if it is bigger than half the maximum possible number. It essentially gives you a lot of info to guess.
I want to add a score aspect where after you guess the correct number, you will get 1 added to your score. Then it will loop back to the beginning, get a new number to guess and give all it's information again so you can guess. I'm trying to get the looping part but I'm really lost right now.
When your guess is correct we can add 1 to your current score and print it. You can play till you guess it right. You have to put the whole code in a while loop for looping through the game after every correct answer. You can break the loop if your score is greater than 10 and the game stops.
import random
x = 50
score = 0
while True:
if score >= 10:
break
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
while True:
if int(input('Guess: ')) == number:
print('You got it')
score+=1
print('Your current score',score)
break
else:
print('Try again!')
Haven't worked with Python myself before but I assume you want to encapsulate everything inside a huge while loop and ask at the end of each iteration if you want to keep playing
Something like this (this is more pseudocode than anything, didn't even tested it)
import random
x = 50
score = 0
keepPlaying = True
while keepPlaying:
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
if int(input('Guess: ')) == number:
print('You got it')
score++
break
else:
print('Try again!')
score--
if (input("do want to keep playing?")=="no")
keepPlaying = False

TypeError for Python program (string formatting with %d)

My program: A Math Quiz that prompts a user for a choice of difficulty (Beginner, Intermediate, Advanced) and then generates five questions (with random #'s) depending on their choice.
It was working completely fine until I started adding the comments and doc strings (I apologize if it's hard to read with the mess, instructor requires an exorbitant amount of comments.)
I apologize in advance for the messiness of the code (the instructor wants an exorbitant amount of comments).
# Import randint so program can generate random numbers
from random import randint
'''
Set the variable choice equal to the users input for choosing which level
they want to do. Then, we created an if statement equal to beginner
(for user's input). The range is the amount of questions for that
particular type of problem (addition, multiplication, etc.)
n1 is a random number from the range 1 to 10, program picks two
The variable 'sum' is set to the value n1 plus n2
'''
choice = input("Choose Level: Beginner,Intermediate, or Advanced?").lower()
if choice == "beginner":
correct = 0
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
# Set variable 'ans' to the input "What is (n1) plus (n2)"
# %d = program generates a random number for the problem
# correct = correct + 1 -> adds one point to the user's overall score
ans = input("What's %d plus %d?" % (n1, n2))
if int(ans) == sum:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No it's not correct. The answer is %d.\n" % sum) ## < Here is where I'm getting the error message.**
for i in range(3):
n1 = randint(1, 10)
n2 = randint(1, 10)
difference = n1 - n2
ans = input("What's %d minus %d?" % (n1, n2))
if int(ans) == difference:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % difference)
# This is where the program calculates the score, and tells the user
# "Well Done", "Need more practice" or "Ask teacher for help".
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "intermediate":
correct = 0
for i in range(3):
n1 = randint(1, 25)
n2 = randint(1, 25)
product = n1 * n2
ans = input("What's %d times %d?" % (n1, n2))
if int(ans) == product:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % product)
for i in range(2):
n1 = randint(1, 25)
n2 = randint(1, 25)
quotient = n1 / n2
# For this section, we had to use a float input type and 'round' so that
# the program will take in a decimal point, and tell the user to round.
ans = float(input("What's %d divided by %d? (Round 2 decimal places)" \
% (n1, n2)))
if round(ans, 2) == round(quotient, 2):
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %f.\n" % quotient)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "advanced":
correct = 0
for i in range(3):
n1 = randint(11, 20)
n2 = randint(1, 10)
modulus = n1 % n2
ans = input("What's %d modulus %d?" % (n1, n2))
if int(ans) == modulus:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % modulus)
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
exponent = n1 ** n2
ans = input("What's %d to the power of %d? \
Don't need commas for answers)" % (n1, n2))
if int(ans) == exponent:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % exponent)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
I'm getting this type error (on the first else print statement):
I'm not sure if I messed something up when I added the comments, but I can't seem to figure out what it is.
You use a variable called sum but don't define it. Python has a builtin function called sum - and you really should change your variable name so you don't get this type of problem - and python tried using that function for the %d calculation. Rename it my_sum and you'll get a different error saying its not defined. Then you can fix that!
You are using sum as a variable name, but that shadows a builtin function sum. Change your variable name to something else and the error will go away.
With if int(ans) == sum:, all you are doing is comparing int(ans) to the sum function itself, rather than the result it returns when passed some numbers. You want to do something like if int(ans) == sum(n1, n2):. What you should probably do instead though, is save this sum to a variable (not named sum, and then replace all your sums with it. For example:
_sum = sum(n1, n2)
...
if int(ans) == _sum:
...
print("No it's not correct. The answer is %d.\n" % _sum)
You need to change some values.
In line
ans = input("What's %d plus %d?" % (n1, n2))
Add
result = n1 + n2
if int(ans) == result:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No it's not correct. The answer is %d.\n" % result) # Here is where I'm getting the error message.**
...
...

Simple python iteration exercise..stuck with try and except

Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
This is what I have.
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
try:
total += numbers
count += 1
average = total / len(number)
except:
print ("Invalid input")
continue
print (total, count, average)
When I run this, I always get invalid input for some reason. My except part must be wrong.
EDIT:
This is what I have now and it works. I do need, however, try and except, for non numbers.
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
total += float(number)
count += 1
average = total / count
print (total, count, average)
I think I got it?!?!
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
try:
if number == "done":
break
total += float(number)
count += 1
average = total / count
except:
print ("Invalid input")
print ("total:", total, "count:", count, "average:", average)
Should I panic if this took me like an hour?
This isn't my first programming language but it's been a while.
I know this is old, but thought I'd throw my 2-cents in there (since I myself many years later am using the same examples to learn). You could try:
values=[]
while True:
A=input('Please type in a number.\n')
if A == 'done':
break
try:
B=int(A)
values.append(B)
except:
print ('Invalid input')
total=sum(values)
average=total/(len(values))
print (total, len(values), average)
I find this a tad cleaner (and personally easier to follow).
The problem is when you try to use your input:
try:
total += numbers
First, there is no value numbers; your variable is singular, not plural. Second, you have to convert the text input to a number. Try this:
try:
total += int(number)
It's because there is no len(number) when number is an int. len is for finding the length of lists/arrays. you can test this for yourself by commenting out the try/except/continue. I think the code below is more what you are after?
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
try:
total += number
count += 1
average = total / count
except:
print ("Invalid input")
continue
print (total, count, average)
note there are still some issues. for example you literally have to type "done" in the input box in order to not get an error, but this fixes your initial problem because you had len(number) instead of count in your average. also note that you had total += numbers. when your variable is number not numbers. be careful with your variable names/usage.
A solution...
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
else:
try:
total += int(number)
count += 1
average = total / count
except ValueError as ex:
print ("Invalid input")
print('"%s" cannot be converted to an int: %s' % (number, ex))
print (total, count, average)
Problems with your code:
total+=numbers # numbers don't exist; is number
len(number) # number is a string. for the average you need count
if is not done, else process it
Use try ... except ValueError to catch problem when convert the number to int.
Also, you can use try ... except ValueError as ex to get an error message more comprehensible.
So, after several attempts, I got the solution
num = 0
count = 0
total = 0
average = 0
while True:
num = input('Enter a number: ')
if num == "done":
break
try:
float(num)
except:
continue
total = total + float(num)
count = count + 1
average = total / count
print(total, count, average)
Old problem with Update solutions
num = 0
total = 0.0
while True:
number = input("Enter a number")
if number == 'done':
break
try :
num1 = float(number)
except:
print('Invailed Input')
continue
num = num+1
total = total + num1
print ('all done')
print (total,num,total/num)
Write and Run picture
Covers all error and a few more things. Even rounds the results to two decimal places.
count = 0
total = 0
average = 0
print()
print('Enter integers and type "done" when finished.')
print('Results are rounded to two decimals.')
while True:
inp = input("Enter a number: ")
try:
if count >= 2 and inp == 'done': #only breaks if more than two integers are entered
break
count = count + 1
total += float(inp)
average = total / count
except:
if count <=1 and inp == 'done':
print('Enter at least 2 integers.')
else:
print('Bad input')
count = count - 1
print()
print('Done!')
print('Count: ' , count, 'Total: ' , round(total, 2), 'Average: ' , round(average, 2))

how can i return a changing int within a string in python?

the function i am working on is supposed to tell a user whether a number they have given is a perfect number or not (i.e. is equal to half the sum of its factors). if a user gives the number 8, the output should look like this:
8 is not a perfect number
but i can't figure out what to put in the return statement to make the int, which changes depending on the user input, print out with the string. the code so far looks like this:
#the code is within another larger function which is the reason for the elif
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
thisNum = isPerfect(num1)
if(thisNum == True):
return num1, is a perfect number
elif(thisNum == False):
return num1 is not a perfect number
def isPerfect(num1):
sumOfDivisors = 0
i = 0
listOfDivisors = getFactors(num1)
for i in range(0, len(listOfDivisors) - 1):
sumOfDivisors = sumOfDivisors + listOfDivisors[i]
i += 1
if(sumOfDivisors / 2 == num1):
return True
else:
return False
if i were to do return(num1, "is not a perfect number") it would come out like
(8, 'is not a perfect number')
return "%d is not a perfect number" % number
You can do this with string formating using %s. Anyway there is some other ways as describes String Formating Operators
convert the integer to a string and concatenate the rest of your statement:
return str(num1) + ' is not a perfect number'
You can use the .format() mini language, and at the same time, simplify your code:
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
if isPerfect(num1):
return '{} is a perfect number'.format(num1)
else:
return '{} is not a perfect number'.format(num1)
Also in your other method, simply return the result of the comparison:
def isPerfect(num1):
sumOfDivisors = 0
listOfDivisors = getFactors(num1)
for i listOfDivisors:
sumOfDivisors += i
#if(sumOfDivisors / 2 == num1):
# return True
#else:
# return False
return sumOfDivisors / 2 == num1
Also, I would suggest having a read of PEP-8, which is the style guide for Python.

Categories