I'm trying to create a game that is kind of along the lines of the game mastermind.
I have a section where the user has to either guess the number or type "exit" to stop the game. How do i make it so that the code allows both an integer and string input?
The code is:
PlayerNum = int(input("Type your number in here:"))
if PlayerNum == "exit":
print "The number was:",RandNum1,RandNum2,RandNum3,RandNum4
print "Thanks for playing!
exit()
If anyone could help that would be great.
Thanks. :D
you can use isdigit() function to check whether input is int or string.
Let user has input "32" then "32".isdigit() will return True but if user has input "exit" then "exit".isdigit() will return False.
player_input = input("enter the number")
if player_input.isdigit():
# Do stuff for integer
else:
# Do stuff for string
PlayerNum = input("Type your number in here:")
Well You can remove the int so that it takes both integet and string as input
Integer and String classifications are specific to Python (they are functions). When the user types in their response, that would be interpreted by the system as stdin (standard input).
Once the stdin is entered by the user and allocated under the PlayerNum variable, you are free to convert it to an int/str/bytes as you please.
Related
I am very new to Python (literally just started learning last week). My group got an assignment to code a program to compute system that calculate total price with several conditions. But we are stuck because the user input returns as string but we need it to link with the variable. And also we aren't allowed to use IF, ELSE method and everyone is new to this so we are at dead end. Please help :')
This is what we have coded in the last hour.
min_price=30
oak_type=15
pine_type=0
black=0
white=0
gold_leaf=15
print("Welcome to Mark Daniels Carpenting Service!")
import random
order_num=random.randint(1000,1999)
print("\nYour order number is", (order_num))
cust_name=input("Enter name:")
print("Type of wood available:")
print("1 oak_type \n2 pine_type")
wood_type=input("Enter choice of wood:")
And when we tried to total up the price it comes up as error because the wood_type returns as string while the other data returns as integer.
How to make input from wood_type link to oak_type or pine_type value?
wood_type=input("Enter choice of wood:")
You can use wood_type=int(input("Enter choice of wood:"))
Use integer_x = int(input("Enter... ")) for integer and float_x = float(input("Enter... ")) for float.
You can add the type of your input at the beginning of your input syntax.
So for your case, it will be :
wood_type = int(input("Enter choice of wood:"))
im trying to make it so in a part of my code where a user enters their name that they cant enter a number, without the program crashing. I am also trying to do the same with some other parts of my code aswell
I havent tried anything as of now
enter code here
myName = str(input('Hello! What is your name?')) #Asks the user to input their name
myName = str(myName.capitalize()) #Capitalises the first letter of their name if not already
level = int(input('Please select a level between 1 and 3. 1 being the easiest and 3 being the hardest'))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
again = int(input("Would you like to play again? Input 1 for yes or 2 for no?" ))
# Is asking the user if they want to play again.
if again == 1:
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
You should post the code of guessNumber().
kinda difficult to understand question anyway I'd do this.
To accept a string and if the value entered is int it'd give the message but you can't differentiate as int cant be str but str can be a number.
try:
myName=str(input("Enter name\n"))
except ValueError as okok:
print("Please Enter proper value")
else:
printvalue=f"{myName}"
print(printvalue)
Im in my first couple of weeks of programming. I am trying to make a function that asks for a users input, checks whether or not that input is alphabetic, if it is alphabetic then i want to break the while loop.
If I run the script and enter the correct types in the input it breaks and works fine. If I intentionally put a number in the input field it doesn't break out of the loop when I reenter the correct type.
any ideas on what im doing wrong?
def wallType():
wall_type = input("What type of wall was the route on? ")
while wall_type:
#if there is text in the input,instead of an alphanumeric, then tell them they must put in a number.
if str.isalpha(wall_type):
return wall_type
else:
print("You entered a number, you must enter a word. Try again. ")
wallType()
Put your code in a while True loop. When input received is alphabetic, use break to break out of while loop. Else loop again to ask for input.
def wallType():
while True:
wall_type = input("What type of wall was the route on? ")
# string is alphabetic, break out of loop
if str.isalpha(wall_type):
break
else:
print("Please reenter an alphabetic word. Try again. ")
Here is my code:
from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
now, that works fine, if I happen to get the unlucky number.
else :
print("You entered a room.")
doorNum = randint(1, 3)
This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.
I am new to programming in Python, I spent most of my time as a web developer.
UPDATE:
Thanks #rawing, I can not yet upvote (newbie), so will put it here.
If you are using python3, then input returns a string and comparing a string to an int is always false, thus your exit() function can never run.
Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like print(type(doorInp)) after your input line.
To fix it, just enclose the input statement inside int() like:doorInp = int(input("...."))
In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.
I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:
from random import randint
while True:
doorNum = randint(1, 3)
doorInp = int(input("Please Enter A Door Number Between 1 and 3: "))
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
break
print("You entered a room.")
See also: Asking the user for input until they give a valid response
I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.