Getting an "invalid literal for int with base 10" in Python - python

import random
print("Welcome to RNG Guesser!\n")
gld = random.randrange(1,10)
counter = 0
ccounter = 0
while True:
print("Number of tries: {}".format(counter))
print("Number of correct guesses: {}".format(ccounter))
num = input("Enter a number: ")
if num is "exit":
print("Number of tries: {}".format(counter))
print("Number of correct guesses: {}".format(ccounter))
break
else:
if int(num) is gld:
print("Congratulations, your guessed number {} was right!".format(num))
counter += 1
ccounter += 1
elif int(num) < gld:
print("Pick a higher number!")
counter += 1
else:
print("Pick a lower number!")
counter += 1
Why am I getting the "invalid literal for int" when I type in exit? I tried converting the input variable to int, I tried with an else statement, I tried making 2 variables, one for string one for int, and none of them worked.

I believe the issue is from the line:
if num is "exit"
Is evaluating to False and further down the script when Python tries to convert the literal string exit to an int, it will fail.
Try replacing is with ==
The problem is that is compares two objects to see if they are the same, whereas what want to is to see if the tow objects' values are the same. Check this stack overflow thread for more info.

Assuming that the incorrect indentation in the question is just a copy-paste mistake... try this:
x = input('enter x > ')
print('x == "exit": {}'.format(x == "exit"))
print('x is "exit": {}'.format(x is "exit"))
Here's what happens:
enter x > exit
x == "exit": True
x is "exit": False
Or maybe:
x is "exit": True
The is operator compares object identity but you are trying to compare the contents of two strings.

Note that you cannot give a string with non-numeric characters to int().
Now num is supposed to be a str, and it could be anything from user input. Also note that when you want to evaluate two values, use == instead of is. is is supposed to be used as judging if two things are the same object.
If you want to use if-else, try this:
if num == "exit":
print("Number of tries: {}".format(counter))
print("Number of correct guesses: {}".format(ccounter))
break
elif not num or not all(char.isdigit() for char in num):
print("You are not giving a number.")
else:
if int(num) == gld:
print("Congratulations, your guessed number {} was right!".format(num))
counter += 1
ccounter += 1
elif int(num) < gld:
print("Pick a higher number!")
counter += 1
else:
print("Pick a lower number!")
counter += 1
Here, all(char.isdigit() for char in num) is checking for every character in num to see if they are all numbers. We should be aware that anything could appear in user's input. Only numbers can be converted to int.
We have another solution which is more clear and simple. You may need to read some documents on try...except... in Python.
try:
if int(num) ...
except ValueError:
# num is not able to be converted to int
print("You are not giving a number.")

Related

How to prevent the entry of more than ten digits and also letters and symbols in python

I started learning Python, and I was working on a simple draft number manual, and I had a problem of only 10 digits and no letters or symbols.
this is my code
number = 10
def num():
number = input("Enter the number")
if number == "1111111111":
print("Amal")
elif number == "2222222222":
print("Mohammed")
elif number == "3333333333":
print("Khadijah")
elif number == "4444444444":
print("Abdullah")
elif number == "5555555555":
print("Rawan")
elif number == "6666666666":
print("Faisal")
elif number == "7777777777":
print("Layla")
else:
print("Sorry, the number is not found ")
num()
So, if you want to differentiate the error message for a non-found number and an invalid entry, you would need the following:
1- To check if the input is numeric or if it contains any other symbols, you can use the following:
if number.isdigit():
print("Is a number!")
else:
print("Not a number!")
2- To check for the length, you can simply use:
if len(number) == 10:
print("is 10 digits!")
else:
print("Not 10 digits")

Python simple loop doesnt work as intended

i just dont undersand why it dosent work and what i need to do to fix it. the goal is to make a counting game so i any tips one a restart button would be great aswell. there is no error i just dosent get out of the first loop.
import random
secrectnumber = random.randint(1,100)
nummberguess = 5
print("guess a Number between 1 and 100")
number = False
wrongguess = True
while wrongguess and nummberguess>0:
guess=input()
print( "writte a number")
if guess.isdigit():
guess=int(guess)
number = True
wrongguess = False
else:
print("invalid input")
while number:
nummberguess=nummberguess-1
if guess== secrectnumber:
print("you did it")
break
elif secrectnumber>guess:
print("the number is higeher")
wrongguess = True
elif secrectnumber<guess:
print("the number is lower")
wrongguess = True
There's 2 things wrong with your code based on what you wrote:
If input is not a digit, the loop will run forever. This is because the first part of the condition, while wrongguess is always true and nummberguess>0 is also always true because you're not decrementing/incrementing it. What is that supposed to do? Terminate if number_of_guess ≥ 5? You need to add a counter to actually terminate the first loop after max number of guesses is reached or whatever the desired output may be.
The second while loop is redundant. It'll print the same number in guess if the number is not the intended secret number.
To rectify your code, your second chunk of the code should be within the first, without the while loop. Something like this:
import random
secrectnumber = random.randint(1,100)
nummberguess = 5
print("guess a Number between 1 and 100")
number = False
wrongguess = True
while wrongguess and nummberguess>0:
guess=input()
print( "writte a number")
if guess.isdigit():
# this won't work for input = 31, you need to iterate the string instead and check if all characters are digits, something like this:
# sum([x.isdigit() for x in str(guess)]) == len(guess) <-- Number, this won't work for floating point numbers because '3', '.', '1', '4' (3, 1, 4 is digit, but '.' isn't). Just something to think about
guess=int(guess)
number = True
wrongguess = False
else:
print("invalid input")
nummberguess -= 1
if guess== secrectnumber:
print("you did it")
break
elif secrectnumber>guess:
print("the number is higeher")
wrongguess = True
elif secrectnumber<guess:
print("the number is lower")
wrongguess = True
It can be done very simply as :
import random
secrectnumber = random.randint(1, 100)
nummberguess = 5
print("guess a Number between 1 and 100")
for i in range(nummberguess):
guess = input()
if guess.isdigit():
guess = int(guess)
if guess == secrectnumber:
print("you did it")
break
elif secrectnumber > guess:
print("the number is higeher.", end="")
if i == nummberguess -1:
print(" Exhausted !!!")
else:
print(" Try again !!!")
elif secrectnumber < guess:
print("the number is lower.", end="")
if i == nummberguess -1:
print("Exhausted !!!")
else:
print("Try again !!!")

How to check correct digit positioning?

I made a program that generates a random number between 100 and 999. The user needs to input an integer to guess the random number. The game will only end if the user inputs 0 or has 5 incorrect tries.
How would I modify it such that when the user inputs the answer, the program will tell you whether the integer entered is at the correct position or the correct digit at the wrong position? Like in this example: https://imgur.com/a/CSa3ntd
import random
num = random.randint(100,999)
attempts = 1
while attempts < 6:
guess = int(input("Try #{} - Please enter your guess: ".format(attempts)))
if guess == num:
print("Great! You have gotten the correct number!")
else:
print("Your guess is incorrect")
attempts = attempts + 1
else:
print("The correct number is {}, The game has ended.".format(num))
This code will tell the users which position are correct in case the number and the guess are different.
import random
num = random.randint(100,999)
attempts = 1
print(num)
while attempts < 6:
guess = int(input("Try #{} - Please enter your guess: ".format(attempts)))
if guess == num:
print("Great! You have gotten the correct number!")
break
else:
guess_str = str(guess)
for i, val in enumerate(str(num)):
if guess_str[i] == val:
print("The position num {} is correct".format(i + 1))
print("Your guess is incorrect")
attempts = attempts + 1
else:
print("The correct number is {}, The game has ended.".format(num))
You have two ways of doing this. You may convert your input to a string using str(my_num) and check if str(digit) in str(my_num) and to check if it is in the correct position use str(digit) == str(my_num)[correct_position]
The second way is using divisions and modulu. using (my num // (10 ** position)) % 10 will give you the digit in the position so you could easily compare.
Modify your else statement as :
num = str(num)
guess = str(guess)
correct_digit = 0
correct_digit_position = 0
for i in guess:
if i in num:
correct_digit += 1
if num.index('i') == guess.index('i') :
correct_position += 1
correct_digit -= 1
print(f"Try #{attempts} - {correct_position} correct digit and position, {correct_digit} correct digit but wrong position ")

How to break while loop when two conditions are true - Calculator

I'm building my first calculator. Trying to implement While loop to get a number through user input. I want the While to break once user put a number.
num1 = raw_input("Add mumber one: " )
try:
input = int(num1)
except ValueError:
print "This is not a number"
attempt = 0
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
print "You are not putting number. So, goodbuy"
operation = raw_input("Add Operator: ")
Try this:
for _ in range(5):
num1 = unicode(raw_input("Add number one: "))
if num1.isnumeric():
break
Another method you can try is to have num1 and do the following in the while loop:
if type(num1) is int:
break
What this does is check the type of the variable num1. If it is an integer, int, then it breaks out of the while loop.
I want the While to break once user put a number.
You already are doing that in the condition for your while loop by having type(num) != int so your while loop should stop after the user enters an integer.
You have several errors here:
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
The break statement shoud be inside the loop, but the indentation is wrong. As you write, it is after the loop (hence useless). Also, when you read from standard input, you always get a string even if it is a number. So when you check type(num1) != int this is always false. You must convert num1 with int() each time you read from standard input, not only the first time:
while True:
num1 = raw_input("Add Number one again: " )
try:
input = int(num1)
break
except ValueError:
print "This is not a number"
if attempt == 5:
break
attempt += 1
Here I try to convert to an integer the string read from stdin. If it works, I break the loop immediately. If it does not work (the except clause) I check how many attempts have been done, and break the loop if the attempts are equal to 5.

How to insert loop counter into my definition

number = 7
def magicnumber (guess):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
return magicnumber
Above is my code for my magic number guessing program. My question is how to insert a loop counter. I did some research on loop counter integration, and many people have said to use the enumerate function, problem is I have no idea how to use such a function and if it is appropriate in my case. Normally, I jus declare a counter variable as 0 then use the += function to add 1 to that variable but in my case this does not work as I cant declare the variable before the def magicnumber (guess) line and if I were to declare it, the counter would revert back to 0 after the return. I am therefore enquiring how to add a loop count as I only want the user to have 5 guesses.
Thanks
counter = 5
while counter > 0:
guess = int(raw_input())
if magicnumber(guess) == number:
break
counter -= 1
Another approach:
for i in range(5):
guess = int(raw_input())
if magicnumber(guess) == number:
break
Try using the answer from here: That's what static variables are for (among other things).
That would result in the following code
number = 7
def magicnumber (guess):
magicnumber.counter += 1
if(magicnumber.counter <= 5):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
magicnumber.counter = 0#If you want to reset the counter
return
else:
print "Out of trials!"
return
magicnumber.counter = 0

Categories