"""
I am new to coding in general and I have looked up how to fix this but when I input a letting than
a letting 2x then a number this happens
ges a number 1 tho 100 t
your ges is t
plz input a positive number below 100 that is not a word. exmp(42)
ges a number 1 tho 100 w
your ges is w
plz input a positive number below 100 that is not a word. exmp(42)
this is where I get confused
ges a number 1 tho 100 2
your ges is 2
2
your ges is t
plz input a positive number below 100 that is not a word. exmp(42)
ges a number 1 tho 100 2
your ges is 2
2
None
Traceback (most recent call last):
File "c:\Users\BertD\OneDrive\Desktop\random_number_gessing_game.py", line 20, in<module>
ges = int(ges)
ValueError: invalid literal for int() with base 10: 't'
I am concerned about how python is coming up with this?
It's a tuff puzzle to solve for me.
"""
import random
ges = input("ges a number 1 tho 100 ")
def valid_ges(num):
while True:
print("your ges is "+str(num))
if num.isdigit():
print(num)
break
elif num != num.isdigit():
print("plz input a positive number below 100 that is not a word. exmp(42)")
num = input("ges a number 1 tho 100 ")
elif num > 100:
print("try a number below 100")
num = input("pic a number 1 tho 100 ")
valid_ges(ges)
print(valid_ges(ges))
r = random.randint(1, 100)
ges = int(ges)
while ges != r:
if (ges <= 100):
print("your "+str(r - ges)+" away")
ges = abs(int(input("pic a number 1 tho 100 ")))
elif(ges == r):
break
print("yay you did it")
thank you for your time and have a nice day!
I don't think that giving you the solution will be beneficial for your learning process. Instead, I'll try to point out where your mistake is.
The main problem is in your function valid_guess. You successfully look if your input is a valid number. However, you never give back this information to the rest of your program. Instead, you do print(num) whenever the user input is valid, which only shows the valid guess on the screen. This value is however not stored anywhere.
You should have a good look at return in python. When you write a function that needs to process some information and then forward that information back to the rest of the program, you use return statements instead. Let me show this with an example:
def square(num):
print(num**2)
>>> x = 5
>>> square(x)
25
>>> xsquared = square(x)
25
>>> print(xsquared)
None
Do you see how the result is not stored in xsquared? It just shows the result to the user, then completely forgets about it!
If I however use this instead:
def square(num):
return(num**2)
>>> x = 5
>>> xsquared = square(x)
>>> print(xsquared)
25
The result is now successfully stored! Do note however that we didn't ask the program to show us the results this time. To do so, we need to add another print statement, as you can see in the last line!
Try to use this information to your problem now. Try to store the new guess in ges whenever you give a valid number.
As #pranav-hosangadi mentioned, you should have a close look at a python debugger and learn to work with it. This will help you understand your code much better! Good luck with learning, and feel free to comment if you have more questions!
This a python value error which occurs when you try to convert a string value that is not formatted as an integer.
Here, the line which causes the error is ges = int(ges).
Where when you first executed you are giving(ges) it a String t. It's not changing it's value while guessing again. Go through your code.
Related
I know there are multiple posts on this question. But I could not post my code in any other way except by asking a question. Can someone please help me understand how I can stop n from being input into the collatz function each time the global scope executes.
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number
until the function returns the value 1.
(Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence,
you’ll arrive at 1! Even mathematicians aren’t sure why.
Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)#
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
desired output
3
10
5
16
8
4
2
1
Input Validation
Add try and except statements to the previous project to detect whether the user types in a noninteger string.
Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy').
In the except clause, print a message to the user saying they must enter an integer.
def collatz(number):
if number%2==0:
number=number//2
print(number)
elif number%2==1:
number=3*number+1
print(number)
print('Enter number: ')
n=int(input())
while n!=1:
collatz(n)
You‘ve created an infinite loop, since your „n“ doesn‘t change within the loop and „n!=1“ is never met as long as the user doesn’t input “1” in the beginning.
Try this:
def collatz(number):
if number % 2 == 0:
number = number // 2
else:
number = 3 * number + 1
print(number)
return number
n = int(input("Enter number: "))
while n != 1:
n = collatz(n)
So I basically wanna compare "Number" and "Guess" in the if statement, but no matter what it says they don't match (I get the else response, not included here). Even if I copy the random number they don't match.
Thanks in advance!
import time
def the_start():
points = 0
attempt = 1
print("Attempt:",attempt)
print("Your goal is to guess a number between 1 and 10 - Points:",points)
time.sleep(2)
attempt = attempt + 1
number = random.randint(0,10)
print(number)
guess = input("What is your guess? :")
time.sleep(2)
if guess == number:
points = points + 1
print("OMG YOU WERE RIGHT! Here, have some fake cheers! *cheer*")
time.sleep(5)
guess is a string. You need to do conversion of the string and handle error conditions. int() will convert a string to an integer, but it will throw an exception if the string is not purely numbers.
I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?
Here is my code:
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
print ('Wrong')
else:
print ('Correct')
You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."
import random
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
print('Wrong')
else:
print('Correct')
Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.
Here is the mistake,
random = print(random.randint(1,9))
You need to do something like this.
random = random.randint(1,9)
print(random)
Also, you have already converted the input to int so, you can do just this.
if x != random:
As pointed out your mistake is the line
random = print(random.randint(1,9))
But why?
functions (like print() take something, do something (with it) and give something back.
Example:
sum(3,4) takes 3 and 4, may add them and returns 7.
print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").
You then assign None to the name random and test if it equals your number, which it (of course) doesn't.
I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)
I'm relatively new to Python, and I don't understand the following code produces the subsequently unexpected output:
x = input("6 divided by 2 is")
while x != 3:
print("Incorrect. Please try again.")
x = input("6 divided by 2 is")
print(x)
the output of which is:
6 divided by 2 is 3
Incorrect. Please try again.
6 divided by 2 is 3
3
Incorrect. Please try again.
6 divided by 2 is
Why is the while loop still being executed even though x is equal to 3?
input() returns a string, which you are comparing to an integer. This will always return false.
You'll have to wrap input() in a call to int() for a valid comparison.
x = int(input("6 divided by 2 is"))
while x != 3:
print("Incorrect. Please try again.")
x = int(input("6 divided by 2 is"))
print(x)
Read more on int() here.
You are getting this error is because you are not parsing the input like so:
x = int(input("6 divided by 2 is"))
If you replace your inputer statement with that, it'll work.
input method gives the string. So you need to typecast to int as:
x = int(input("6 divided by 2 is"))
Here is my answer to your question
Guesses = 0
while(Guesses < 101):
try:
x = int(input("6 divided by 2 is: "))
if(x == 3):
print("Correct! 6 divide by 2 is", x)
break
else:
print("Incorrect. try again")
Guesses += 1
except ValueError:
print("That is not a number. Try again.")
Guesses += 1
else:
print("Out of guesses.")
I am assuming you wanted the user to input a number so i put your code into a while\else loop containing a try\except loop. The try\except loop ensures that if the users inputs a number, a ValueError will appear and it will inform them that what they inputted was not a number. The while\else loop ensures that the user will be inputted the question if the Guesses limit is no higher than 100. This code will ensure that if the user guesses the answer which is 3, the user will be prompted that they got the answer right and the loop will end; if the users guesses anything besides 3 (Number wise) the answer will be incorrect and the user will be prompted the question again; if the user guesses a string it will be classified as a ValueError and they will be notified that their answer wasn't a number and that the user has to try again.
Considering this was asked a long time ago, I'm assuming your probably forgot about this or you figured out the answer but if not try this and tell me if you like this answer. Thank :)
I actually tried this myself now with python 2.6, and did get an int without converting to int. For example, when I try the following:
x = input("6 divided by 2 is")
print "Your input is %s, %s" % (x, type(x))
I get the following:
6 divided by 2 is 2
Your input is 2, <type 'int'>
So is this a version issue? Or maybe an environment issue (I'm using OS X)?
What I do conclude is that it should be a good practice using previous recommendations using int().