I'm working on a number guessing game and can't seem to get my loop to work while utilizing a function. I was manually typing out conversion under each if/elif in the block, but that was tedious and only checking for integers - string inputs couldn't read and broke the system.
I tried creating a conversion function to check the values and determine if it was an integer or string and change the variable type accordingly. However this results in an infinite loop fo line 18.
Can someone point out what I'm doing wrong here?
Heads up, I do have the random.py script from Python.org and am importing it so the game plays differently each time.
from random import randint
print 'Hello, my name is Skynet. What\'s yours?'
myName = raw_input()
print 'Good to meet you, ' + myName + '! Let\'s play a game.'
print 'I\'m thinking of a number between between 1 and 20, can you guess it?'
pcNum = randint(1,20)
myNum = raw_input()
def checkNum(myNum):
try:
int(myNum)
except ValueError:
returnVAL = 'That\'s not a number I know, try again.'
else:
returnVAL = int(myNum)
return returnVAL
while myNum != pcNum:
if myNum > pcNum:
print 'That\'s too high! Try again.'
myNum = raw_input()
checkNum(myNum)
else:
print 'That\'s too low! Try again.'
myNum = raw_input()
checkNum(myNum)
if myNum == pcNum:
print 'Good job, my number was ' + str(pcNum) + ' too! Good job, ' + myName
Any input is appreciated. I did some browsing here and got some a better idea of how to pull this off, or so I thought, and now here I am asking. First post!
print "I'm thinking of a number between between 1 and 20, can you guess it?"
while True:
guess = raw_input("What's your guess? ")
try:
guess = int(guess, 10)
except ValueError:
print "That's not a number I know, try again."
continue
if guess == pcNum:
...
break
elif guess > pcNum:
...
else:
...
Don't mix responsibilities. It is wrong to have myNum be both a number and an error message.
Also, think what you want to do when a user enters a non-number. In your case, the user's guess is "That's not a number I know, try again.", and it's being compared to pcNum; this makes no sense. If it was me, I would want the user to enter the number again. So rather than checkNum, I want input_valid_integer:
def input_valid_integer():
result = None
while result is None:
text = raw_input()
try:
result = int(text)
except ValueError:
print 'That\'s not a number I know, try again.'
return result
Related
I'm working on LPTHW ex 41, where we modify a bunch of print statements to use a docstring style and then use a runner to print them.
The code originally was like this:
Function()
Print "Several lines of printed material"
Revised, the functions begin:
Function()
"""doc comment"""
A runner connects all the functions ("rooms") like so, with the goal being to print doc comments instead of print commands.
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
def runner(map, start):
next = start
while True:
room = map[next]
print "\n----------------"
print room._doc_
next = room()
runner(ROOMS, 'central_corridor')
But I keep getting the error
'function" object has no attribute '_doc_'
Example room:
def central_corridor():
"""You wanna blow thing up.
You running toward place for to get bomb.
Emeny approach!
1 = shoot at enemy
2 = avoid emenemeny
3 = use bad pick up line on emenie
4 = hint"""
#print(_doc_)
action = int(raw_input("> "))
if action == 1:
print "He shoot you first."
return 'death'
elif action == 2:
print "No he still gots you."
return 'death'
elif action == 3:
print "Oh yeah sexy boy."
print "You get past laughing enemy."
return 'laser_weapon_armory'
elif action == 4:
print "Emeny like good joke."
return 'central_corridor'
else:
print "You enter wrong input"
return 'central_corridor'
Can anyone tell me how to get the doc comments to print? Thanks!
Noticed doc needs two underscores. Fixed
_doc_
__doc__
I am new to python.
My Issue- need to terminate the raw_input if no input is passed
I am basically asking user for number of key-value pairs to be added to dictionary. Then adding the key-value pairs in dictionary. Later querying the dictionary which should result value if key exist, else print Not found.
I searched the Stack Overflow and found solution in terms of timer but I am trying to use ord function to get ascii value of string and check it against null that is ascii value of 0. My code does not seem to terminate, please advice on necessary changes in code.
Please find the code that I am using in the program:
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input().rstrip())
phonebook = dict(raw_input().split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input()
temp=convert_to_ascii(choice)
print temp
if temp != '0':
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print 'Not found'
You should have the empty string '' instead of '0' as your check. This code worked for me. I also added some prints in the raw_inputs to help me look through your code, but the only change that matters is the '0' to '':
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input('How many entries in your phonebook?\n').rstrip())
phonebook = dict(raw_input('Please enter "[name] [number]" for entry '+str(i+1)+':\n').split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input('Who do you want to choose?\n')
temp=convert_to_ascii(choice)
if temp != '': #<-- changed to empty string from '0'
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print word,'was not found'
I wrote a program where you guess a randomly generated number between 1 and 100:
from random import randint
play='y'
print 'Guess a number between 1 and 100'
while play=='y':
x = randint(1,100)
guess=1000
while guess != x:
guess=input('Guess: ')
if guess < x:
print 'Higher'
if guess > x:
print 'Lower'
print 'You got it! Good Job! The number was ' + str(x)
play=raw_input('Would you like to play again(y/n)?: ')
raw_input("Press <enter> to exit")
when the user enters a guess that is not an integer how do I print That is not a number, then allow them to continue guessing?
Use a while True loop to repeat the question until it breaks. Only way to break the loop is if try does not raise a ValueError. int() raises an error when it gets something like 'hello' or '1.2'.
Also, use raw_input instead of input (note: raw_input assigns a string to guess).
while True:
guess=raw_input('Guess: ')
try:
int(guess)
break
except ValueError:
print '\nNot an int, try again.'
More specifically, insert this after while guess != x: and before if guess < x.
[Running on Xubuntu 12.04 LTS, Python 2.7]
Hey. I am struggling a bit with this assignment. It is from book about learning Python but I am probably missing something here. I do not require complete answer but a hint what should I do would be much better than copy/paste it.
My goal now is to create code that counts Smallest number so far from all the user inputs. I know that it has to do something with an impossibility of using min() and "for loops" for float numbers/single numbers as it is necessary to have some list but I do not have any idea what to do now..
Count = 0
Total = 0
Smallest = None #Or maybe I should use something like Smallest = []?
while True:
user = raw_input("Enter number, when you are finished enter done or press enter: ")
if len (user) < 1: break
if user == "done":
print "Done entered, program executed!"
break
try:
fuser = float(user)
print "Valid input.", "Your input:", fuser
except:
print "Invalid input.", "Your input:", user
continue
Count = Count + 1
Total = Total + fuser
#Smallest = None
#for i in [Total]:
#if Smallest is None or itervar < Smallest:
#Smallest = i
# As you can see I've been simply trying to find some way (code with # obviously doesn't work at all...)
#print "Min: ", Smallest
print "Count: ",Count
print "Total number: ",Total
try:
print "Average:", Total/Count
except:
print "NOT AVAILABLE"
Thank you very much for tips and hints on what to do next.
The easiest way may be:
Smallest = []
...
Smallest.append( float( user ) )
and then the total is sum( Smallest ), the smallest is min( Smallest ) and the number is len( Smallest ). You are storing all the intermediate values, which is not really necessary, but I think here is the simplest.
I would like
to check if a string can be a float before I attempt to convert it to a float. This way, if the
string is not float, we can print an error message and exit instead of crashing the
program.
so when the user inputs something, I wanna see if its a float so it will print "true" if its not then it will print"false" rather than crashing. I don't want to use built in functions for this. I need to make my own function for this.
I tried :
import types
def isFloat():
x = raw_input("Enter: ")
if(x) == float:
print("true")
if(x) == str:
print("false")
isFloat()
I don't know if its true or not but it wont work it wont print anything either
The recommended thing to do here is to try it:
try:
f = float(x)
print("true")
except ValueError:
# handle error here
print("false")
This underscores the Python philosophy "It's better to ask for forgiveness than for permission".
The only reliable way to figure out whether a string represents a float is to try to convert it. You could check first and convert then, but why should you? You'd do it twice, without need.
Consider this code:
def read_float():
"""
return a floating-point number, or None
"""
while True:
s = raw_input('Enter a float: ').strip()
if not s:
return None
try:
return float(s)
except ValueError:
print 'Not a valid number: %r' % s
num = read_float()
while num is not None:
... do something ...
print 'Try again?'
num = read_float()