'None' appears out of nowhere in my code - python

print("text")
print("text")
name=str(input("text"))
name=name.capitalize()
tutorial=str(input(print(name,"do you know the rules? (YES/NO)",sep=", ")))
tutorial=tutorial.upper()
I can't find the error in my code. Everytime I run it a "None" keeps coming out of nowhere. (replaced some parts of the code so it can be read more easily)
Name? >>>HAL 9000
Hal 9000, do you know the rules? (YES/NO)
None #This I want to erase

Your problem is in this line:
tutorial=str(input(print(name,"do you know the rules? (YES/NO)",sep=", ")))
You are getting that None because you have an unnecessary print inside your input. Your input is using the return of that print, which does not return anything, so by default is None. You are still seeing what is inside print because of the obvious functionality of print to output what you are sending inside the print method.
View this example that replicates your problem:
>>> input(print('bob'))
bob
None
''
>>>
To fix this problem, remove that print. Also, change the string in your input to use string format:
tutorial=str(input("{} do you know the rules? (YES/NO)".format(name)))

print doesn't return a value, so it's treated as returning None. Which means that you're effectively calling input(None) which prints out "None" before prompting you for input.

Related

Why is my function returning blank strings, but works as expected in the python console?

Apologies for the poor title, I don't know how else to describe my situation.
I wrote a small pattern matching function.
def substrings(input_str):
'''Generate all leading substrings of an input string'''
for i in range(len(input_str)):
return input_str[:i]
It should return a series of slices of a string. If the input was ABCD, it should output ABCD, ABC, AB and A.
When I tested this function in the python console (shown below), it behaves correctly and outputs all the expected strings.
for i in range(len(input_str)):
print(input_str[:i])
But when used in the body of my program its returning nothing at all. For example;
test1 = substrings('ABCD')
print(test1)
Outputs blank lines and I'm struggling to figure out why.
In the console, your loop first prints out a blank string when i==0. Then it continues to loop and print out each of the characters in the string.
In the function, you are returning up to the 0th element in the array, which is the same blank string the console printed on the first time through the loop.
To see better what is happening in the console, you might print the index too:
for i in range(len(input_str)):
print('{0} {1}'.format(i, input_str[:i]))
That's because the first thing your functions returns is empty string ''. So you are exiting loop after first iteration for i = 0 and your variable is empty string because of the fact that:
>>> s = 'ABCD'
>>> s[:0]
''
You are returning in a loop. So the return is the last statement that would execute in a function. That is when a return statement is reached, the control leaves the function. So in the very first iteration i=0, the control returns '' and exits the function irrespective of for-loop. In console the output is obtained because I'm console each line is interpreted one-by-one unlike the program being compiled at once. So console shows the output. Hope this answer helps you
The issue is occurring because you are trying to return information in a loop. When the return statement is called, it exits the function. What you should do is use the yield keyword. Try doing this
def substrings(input_str):
for i in range(len(input_str)):
yield input_str[:i]
# Then iterate through the function like so
function = substrings()
for i in function:
print(i)
Your code should be working fine now!

How to print the input string as a float (1 into 1.0) python

Working on a program for class. I have the following code, however, even though the code works fine; I have a formatting issue.
This here is the correct output that I am trying to get
This is what I currently have; and is wrong
Below is the current code I have:
num_rods = input ( "Input rods: You input " )
num_rods = float ( num_rods )
print ("rods.")
What is the error here? and how can I make my code look like the example; thanks.
Try
print('{} rods.'.format(num_rods))
or
print('rods: ',num_rods)
Also, be careful with statements of this type. Check what happens to the code if, instead of inputting an int or float, you pass the character 'a' for example.
You're seeing a line break, which cannot be avoided
Possible to get user input without inserting a new line?
But you can work around it
entered = input ( "Input rods: You input " ) # literally type "1.0 rods."
amount, _ = entered.split()
...
print ("Minutes to walk {:.1f} rods:".format(amount)) # but you're already printing this

Why is this python code using eval function not producing an error?

I am a beginner in python. Found this while solving exercise in the book Think Python. In this code eval_loop function iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result.
It should continue until the user enters 'done', and then return the value of the last expression it evaluated. My doubt is:
Eval must have a string as its argument, but this code works even when we input non string like 5+4, it prints 9. Since we are not converting the input into a string anywhere, Please tell me how is it not producing an error?
def eval_loop():
result=0
while True:
s = input('>>>')
if s == 'done':
break
result = eval(s)
print(result)
print(result)
eval_loop()
Update:
OK I get it now, the function input returns a string. But now I have one more doubt:
If input function returns a string then why does it produce an error when I give input as - hello, without any inverted commas around it. It gives NameError: name 'hello' is not defined. If input returns a string shouldn't hello be converted to a string too?
Someone please help me out, this is getting very confusing. :(
eval() serve a evaluate a string as a python expression
print eval("3 + 2")
#5
a = 9
print eval("a == 9")
#true
and you can also use raw_input() instead of input() for reading a string

Python 2.7: Handling wrong input which is not a string

I am writing a program which is supposed to contain a way of informing the user that the input for one of the variables is not a string, if entered as a name by user.
E.g. program expects a user input of any string, and if it is a string which is contained within dictionary, it will print out its value, if not, it will print out an error message.
ageofdeath.getage('JesusChrist')
33
ageofdeath.getage('John McCena')
This is not a bible character. Please enter a name of a character from the bible.
but, the program should at least throw an error message when confronted with wrong user input such as
ageofdeat.getage(JesusChrist)
ideally popping up a message along the lines of "This is not a string please input a string". Instead, no matter whether i try to use if = or isinstance, it always shows typical python name is not defined error. Is there a way of going round this or not really, as it is a default way of python shell handling the input?
Your program isn't even getting to the part where it executes your getage() method. It is failing far earlier.
You're using input() instead of raw_input(). Thus JesusChrist is taken as the name of a variable because input() evaluates what the user types as a Python expression. JesusChrist is a legal Python variable name, it just hasn't been defined, so Python tells you that. And because it knows you can't do anything with a value that doesn't exist, it stops.
Now you could catch that error by wrapping your input() in a try/except block, but that's just trying to compensate for making the wrong decision in the first place. The right answer is to use raw_input() to get input from your user and it will always be a string.

Suggestions on improving my code.

Hello I am a fairly novice programmer. And I have a simple code
name=raw_input("Hello I am Bob. What is your name?")
print("It is very nice to meet you,", name)
response=raw_input("what do you want to do today?")
if response == "price match":
However on the fourth line I get SyntaxError: unexpected EOF while parsing error and I did look into it and I found that using the raw_input for inputted strings is much better than using the input function.I don't know why the error keeps popping up. Could I get some help and perhaps some suggestions as to how I can improve the code.
You have to do something in the if statement. For example, print a price:
if response == "price match":
print "Yes, we can do that for you".
But, you can't just leave a block (the stuff that is indented after a :) empty, or Python will give you an error.
In rare cases (and not in your case here), you may want to do absolutely nothing, but still have a block (e.g. if required to by an except:). In that case, you still have to put something in the block, but you can use the word pass which does nothing. (This is almost never used in an if block).
I'm no Python expert.. But it looks like your problem is here:
response=raw_input("what do you want to do today?") if response == "price match":
You are defining an if statement, but if this value is true, how do you handle it?
I'm guessing you would need something like:
if response == "price match":
print('Match')
else:
print('Did not match')
Hope this helps a little
If you need a placeholder for just having valid syntax before putting in the body of your if/else/functions/etc, use pass.
http://docs.python.org/release/2.5.2/ref/pass.html
As for your code, a valid if statement must always have a body. So put some code there or use pass.

Categories