Python variable checking - python-3.x

How would I get Python to check a variable to see if it is an integer and below a specific number then carry on depending on the result perhaps breaking from a loop.
so something roughly like this:
x = input
if x is integer AND below 10:
print ("X is a number below 10")
break from loop
elif x is NOT an integer:
print ("X is not an integer try again")
ask again
Else:
print ("Error")
ask again

pretty sure this works :D thanks
while True:
x = input("Enter Something: ") #user input
if x.isdigit() == True:
if (int(x)>=1) and (int(x)<=2): #if it is 1 or 2
print (x)
break
elif (int(x)>2): #or if its above 2
print ("To Large")
else:
print ("Else")
elif x.isdigit() == False: #data non integer
print ("please try again")
else:
print ("ERROR") #error with input
print ("Hello") #show the loop broke correctly

Related

Code running despite no input being given (python)

When the user enters nothing, it is supposed to loop back and ask the question again. It performs correctly with every other type of input.
Here is the code:
string = ""
def str_analysis(string):
while True:
if string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
break
else:
print(str(string)+ " is a smaller number than expected")
break
elif string.isalpha():
print(string + " is an alphabetical character")
break
elif string == "":
print("")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
print(str_analysis(input("Enter word or integer: ")))
There are a few things in your code that make no sense.
1:
print(str_analysis(input("Enter word or integer: ")))
You are trying to print the output of a function that has no return value
2:
It cant loop back and ask the question again, because the input is not taken inside of the function.
3:
If the string is empty you dont break the code but constantly print newlines.
Here is some code wich I think should do what you wanted:
def str_analasys():
while True:
string = input("Enter word or integer: ")
if string == '':
continue
elif string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
else:
print(str(string)+ " is a smaller number than expected")
elif string.isalpha():
print(string + " is an alphabetical character")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
str_analasys()
This because when string is empty you are just printing an empty ""
elif string == "":
print("")
# break it here or take input again
# break or string = input()

How to make variable accept strings

I want to make this code keep going? I tried put an x == to str, but I think that could not be the answer.
while True:
x = int(input("Please enter an integer:
"))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
x == str :
input("please enter a string")
The first line of your loop can have one of two effects: either x is guaranteed to be an int, or you'll raise a ValueError. Catch the error and restart the loop, or continue with the body knowing that x is an int
while True:
x_str = input("Please enter an integer: ")
try:
x = int(x)
except ValueError:
print("{} is not an integer; please try again".format(x))
continue
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
I'll try to guess what you wanted. I think you wanted a function that is like input, but with a strange twist: if what is entered (x) can be interpreted as an integer, then it returns the integer itself, not x. For example, if the user enters -72, it returns -72, not '-72'. Of course, if the user enters something that cannot be interpreted as an integer, the function returns it without modification.
Of course, being strongly typed, Python doesn't provide such a function, but it's easy to write one. And you don't even need try if you just intend to accept "ordinary"-looking integers.
def intput(prompt=''):
entered = input(prompt)
if entered[entered.startswith('-'):].isdigit(): return int(entered)
else: return entered
while True:
x = intput('Please enter an integer: ')
if x < 0:
x = 0
print('Negative input changed to zero')
elif x == 0: print('Zero')
elif x == 1: print('Single')
elif isinstance(x, str): print('You have entered a string that cannot be '
'easily interpreted as an integer.')

We are getting an error with this while loop but cannot see why

The error we are getting is that it is looping infinitely and does not appear to be picking a number to be the correct choice
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 0
print ("Guess!")
guess = int( input())
while guessTaken < 6:
guess != guess+1
print ("Wrong!, guess again")
if guess == input():
print ("Correct")
print ( )
The loop's termination is based on the value of guessTaken; since that is never changed, once the loop is entered, it will never end.
Your code has many mistakes but I will try my best to fix them here:
First of all guess != guess+1 serves no purpose you are checking if guess is not equal to guess+1 (it isn't) which means that this line is always returning True and you aren't event doing anything with it.
I believe you meant to write:
guessTaken += 1
Which increments the number of guesses taken by 1
Next you will need to convert the second input to an int to compare it to guess so I recommend doing:
if guess == int(input()):
instead of
if guess == input():
Finally I suspect you want to exit the loop once the number has been guessed so I would add a break statement in the if condition as such:
if guess == int(input()):
print ("Correct")
break
You have many mistakes in your code. Not sure what you need, but you can try below:
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 0
wrong = True
print (number)
guess = int( input())
while guessTaken < 6: #Maximum guesses are 6
if guess != number:
print ("Wrong!, guess again")
guess = int( input())
else:
print ("Correct")
break #remember to put break when found correct number
guessTaken += 1
if guessTaken == 6:
print ("Maximum guessed")
I have tried to modify your code:
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 1
while guessTaken < 6:
if guessTaken == 1:
print('Guess!')
guess = input()
else:
print('Guess Again')
guess = input()
if int(guess) == number:
print('Correct')
break
else:
print('Wrong')
guessTaken = guessTaken + 1 #counter

Variable not Defined in Python 3.5.1

I am a new coder with Python and I was wondering how I can fix this bug. Every time i put in the correct input in the code that I have, it spits out an error message, like so.
The code
total = 12
print ("I will play a game, you will choose 1, 2, or 3, and I will do the same, and I should always win, do you want to play?")
yesnoA = input("Yes or No?")
if yesnoA == yes:
print ("Yay, your turn!")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
yesnoB = input("Ok, you sure?")
if yesnoB == yes:
print ("Yay, your turn")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
print ("Well, goodbye")
The Output
Yes or No?yes
Traceback (most recent call last):
File "C:/Users/*user*/Desktop/Code/Python/Nim Game.py", line 5, in <module>
if yesnoA == yes:
NameError: name 'yes' is not defined
This is in version 3.5.1
You need to either declare a variable yes with a value 'yes', or compare your variable yesnoA with a string 'yes'. Maybe something like this:
if yesnoA.lower() == 'yes': # using lower(), so that user's input is case insensitive
# do the rest of your work
Your code afterwards has some more issues. I will give you a clue. input always returns the user's input as string. So if you need integer from user, you will have to convert the user input into integer using int(your_int_as_string) like so:
turnAA = int(input('Your First Move'))
# turnAA is now an integer, provided the user entered valid integer value
Your take from this question on SO:
Look at the Traceback. It says clearly which line the error is in, and also what the error is. In your case it is NameError
Take a look at docs for NameError
Study this tutorial. It will help you get used to with some basic errors commonly encountered.
You have not defined the variable yes. You should do something like:
yes = "Yes"
At the start of the code
You're attempting to compare yesnoA to a variable named yes, which, indeed was not defined, instead of the string literal 'yes' (note the quotes!). Add the quotes and you should be fine:
if yesnoA == 'yes':
# Here --^---^

python 3 try/except exiting rather than looping

I'm not sure what I'm doing wrong here. I'm trying to limit user input to 1-6 (dice game). The logic is working but when a ValueError() is raised it doesn't prompt the user again.
try:
while True:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
Because you're exiting your loop at Exception. You should write a code like this:
while True:
try:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
Use while loop before try code which will keep looping try and catch block like this
while True:
try:
# Your Code
except ValueError:
# Your Code

Resources