I am trying to make a program that randomly selects a number, and then you have to guess that number until you get that number correct. So far it works so that I can guess one time, and then the program ends, i need it to repeat my input until i guess the correct number.
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = int(input("What is your guess?: "))
if b == a:
print("You guessed my number!")
elif b > a:
print("You're number is too large")
elif b < a:
print("You're number is too small")
input("\n\nPress the enter key to exit")
You're missing the while loop which will execute until a certain condition is met. In your case, the code would be like this:
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = 0 # We create the variable b
while b != a: # This executes while b is not a
b = int(input("What is your guess?: "))
if b > a:
print("Your number is too large")
elif b < a:
print("Your number is too small")
print("You guessed my number!") # At this point, we know b is equal to a
input("\n\nPress the enter key to exit")
It's working
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
while True: #missing the while loop
b = int(input("What is your guess?: "))
if b == a:
print("You guessed my number!")
exit()
elif b > a:
print("You're number is too large")
elif b < a:
print("You're number is too small")
import random
def g1to9():
a = random.randint(1,9)
wt = 0
b = input("Guess a number from 1 to 9:")
if a == b:
print("You guessed it correctly, it took you {} tries".format(wt))
while True:
if a != b:
print("You are wrong!")
b = input("Guess a number from 1 to 9:")
wt += 1
I am trying to create a game "Guess a number from 1 to 9". But when I run it I check all the numbers but a is never equal to b. I tried to make a a global variable,but it didn't work. What's wrong with my code?
b would of type str as it is an input. You need to cast it to an int first. You can do that by:
b = int(input("Guess a number from 1 to 9:"))
I saw a similar post, but it included functions, which mine does not.
Objective: Write a program that reads an unspecific number of integers, determines how many positive and negative values have read, and computes the total and average of the input values (not counting 0's) while the program will halt at 0.
ISSUE I AM HAVING: When using the following test values
1,
2,
-1,
3
I get the following:
The number of positives: 1
The number of negatives: 2
The total amount of numbers used: 3
The average is 1.33 which is 4 / 3
It should be:
The number of positives: 1
The number of negatives: 3
The total amount of numbers used: 4
The average is 1.25 which is 5 / 4
My Attempt below:
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
else:
while user_input != 0:
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input != 0 and user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
user_input != 0 and user_input < 0
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
What is causing such error? I can only assume that this is a minor fix?
I've fixed the problems in your code and refactored to trap error conditions and removed unnecessary complications:
positive_number = 0
negative_number = 0
average = 0
count = 0
total = 0
user_input = None
while user_input != 0:
try:
user_input = int(input("Enter enter as many intergers as you want, 0 will halt: "))
except ValueError:
user_input=0
if user_input > 0:
total += user_input
positive_number += 1
count += 1
elif user_input<0:
total += user_input
negative_number += 1
count += 1
if count==0:
print("You didn't enter any number, code ended")
else:
average = total / count
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(total), "/", str(count))
First, the first if statement is redundant as you test for user_input != 0 as the loop condition. Second, the reason it was going wrong was because on your first input you immediately overwrote the value of user_input, so I put the reprompt code at the end of the loop. Finally, I cleaned up the if elif else statement as this does the exact same with fewer characters. The print statement for the closing line is also executed once we pull out of the loop - sinc eby definition that means user_input == 0
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
while user_input != 0:
if user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
print("You didn't enter any number, code ended")
Like it was said in the comments, your first input is getting ignored. Here is an alternative that should work. I excluded a few redundant check statements.
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = 1
while user_input != 0:
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
There are a number of issues with your code. First of all, the first number that the user prompts is not being evaluated by the code; it's being overwritten once you get to the while loop. There are multiple ways to fix this, but the best would be along the lines:
cont = True
while cont is True:
user_input = int(input("Prompt user"))
if user_input == 0:
cont = False
You could do a break statement too, it doesn't matter.
So that takes care of why the first number isn't being read, and why the code thinks there were only 3 inputs (as well as your count being off). Now what about the two negatives? I don't know why you got that. When I inputted the numbers you listed, I got one negative and two positives. Try it again and see if it works now, I suspect you must've mistyped.
Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).
Hiiii, thank you for all the answers! I've figured this out! I can't delete this message tho, and I'm not sure how to make it inactive. basically i am a mess. but thank you everyone!!!
Okay i am actually having 456344 problems, but this is my current one
here is my code:
def averages():
grade = 0
x = eval(input("How many grades will you be entering? "))
if type(x) != type(int(x)):
x = eval(input("You can't enter that many grades. How many grades will you be entering? "))
for i in range(x):
y = eval(input("Please enter a grade between 0 and 100: "))
if 0 <= y <= 100:
grade = grade + y
else:
print("Your number is out of range!")
y = eval(input("Please enter a grade between 0 and 100: "))
average = grade/x
print (y)
print (x)
print (grade)
print (average)
averages()
basically whenever i run the code this part doesn't work:
if 0 <= y <= 100:
grade = grade + y
and it only calculates the last number entered in the average.
Also, I'm supposed to make it give an error message if the number entered by the user is out of range (not between 0 and 100), but the error message isn't coming up? I'm not sure what's happening. Please help, thank you.
I have made some changes...
1) Replaced if-else statement with while
2) This condition checking makes sure to give out error message
def averages():
grade = 0
x = int(input("How many grades will you be entering? "))
if type(x) != type(int(x)):
x = int(input("You can't enter that many grades. How many grades will you be entering? "))
for i in range(x):
y = int(input("Please enter a grade between 0 and 100: "))
while not (0 <= y <= 100):
print("Your number is out of range!")
y = int(input("Please enter a grade between 0 and 100: "))
grade = grade + y
average = grade/x
print (y)
print (x)
print (grade)
print (average)
averages()
As grade addition is outside for it considers last input only.
There are some indentation issues and eval issue. Most of all, don't use input() on Python 2 or eval() on Python 3. If you want integer numbers, use int() instead. Try this code :
def averages():
grade = 0
while True:
try:
x = int(raw_input("How many grades will you be entering? "))
except:
print "Input limit exceeds"
continue
else:
break
for i in range(x):
y = int(raw_input("Please enter a grade between 0 and 100: "))
if 0 <= y and y <= 100:
grade = grade + y
else:
print("Your number is out of range!")
y = int(input("Please enter a grade between 0 and 100: "))
average = grade/x
print (y)
print (x)
print (grade)
print (average)
averages()