python code has a name error in a while loop [duplicate] - python

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 7 years ago.
this is all of my code so far. the function works if I input x manually. I'm also just starting out so any general info on how to generally make it more pythonic would be apreciated
def iseven(x):
if x % 2 == 0:
return x," is even"
else:
return x," is odd"
it = (1)
while it >= 0:
number = input("What number: ")
print iseven(number)
new_num = input("another number? answer (Y/N):")
if new_num == "Y":
it += 1
else:
it = 0
this is the error
NameError: name 'Y' is not defined

You may want to avoid input in such cases where you're processing general input and prefer raw_input:
https://docs.python.org/2/library/functions.html#raw_input
This avoid the eval that's taking place that's causing your error - it's looking in the program's scope for something named "Y". If you type "it", here, for example, it will evaluate the code, which is generally unsafe (though fairly benign here I suppose).
https://docs.python.org/2/library/functions.html#eval

Just change the line:
new_num = input("another number? answer (Y/N):")
to:
new_num = raw_input("another number? answer (Y/N):")
You need to change: while it >= 0: to while it: as well so that you can be able to exit the loop if you select N on prompt.

Related

New to python, Do I need a while loop statement [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 12 months ago.
I'm new to python and I am trying to figure out how do I enter an error message if the user inputs a number less than zero.
Here is my code to give you a better understanding and I thank you all in advance for any advice.
# Python Program printing a square in star patterns.
length = int(input("Enter the side of the square : "))
for k in range(length):
for s in range(length):
if(k == 0 or k == length - 1 or s == 0 or s == length - 1):
print('*', end = ' ')
else:
print('*', end = ' ')
print()
Here is a simple and straight forward way to use a while loop to achieve this. Simple setting an integer object of check to 0. Then the while loop will evaluate check's value, then take user input, if the user input is greater than 0, let's set out check object to 1, so when we get back to the top of the loop, it will end.
Otherwise, if the if check fails, it will print a quick try again message and execute at the top of the loop again.
check = 0
while check == 0:
length = int(input("Enter the side of the square : "))
if length > 0:
check = 1
else:
print("Please try again.")
You can use this code after the input statement and before for loop.
if length < 0 :
Print("invalid length")
Break

unwanted result from a function and if else [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
I'm trying to create a simple program using function and if else. Even though there is no errors, my program doesn't give expected result
value1 = float(input("Enter your first number:"))
value2 = float(input("Enter your second number:"))
question= input("choose mode:" )
add = True
def nor_cal(num1, num2):
if question == add:
total = num1+num2
print("the total is: ")
print(total)
else:
print("Invalid operator")
result1 = nor_cal(value1, value2)
print(result1)
when i run the program, it shows like this:
Enter your first number:2
Enter your second number:3
choose mode:add
Invalid operator
None
I don't know where i'm wrong please help !
The bug is in the line if question == add:, what you're asking the program to do is to compare the variable question (which is "add") to the variable add (which is True).
You're going to want to use if question == "add": instead.

Not equal statement, not working [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I am making a small quiz that has different difficulties, when doing my easy section my if statement always prints incorrect even with the correct answer - i am still new to python it might be a very easy thing to solve
How can I know if this is a duplicate if i don't know what is wrong
here is my code
def easy():
score = 0
print("Welcome to the easy section!")
print("****************************")
print("Random Access Memory(1)")
print("Radical Amazonian Mandem(2)")
qe1 = input("What does RAM stand for?: ")
if qe1 == 1:
score = score + 1
print("Well done, next question:")
if qe1 != 1:
print("Incorrect, next question:")
else:
easy()
input function return a string, you should cast it to int:
qe1 = int(input("What does RAM stand for?: "))

Starting from a certain line in python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am using the newest python software and I am really stumped on printing a certain line in the code.
name = input("Before we begin, what is your name? ")
print("Cool, nice to meet you "+name+"!")
score = 0
score = int(score)
count = 0
answer1 = "dogs"
answer01 = "dog"
question1 = ""
while question1 != answer1 and count < 2:
count = count + 1
question1 = input("What animal barks? ") #Asks the user a question
if question1.lower()== answer1:
print("Correct! Off to a great start, the right answer is dogs!")
score = score + 1
break
elif question1.lower()== answer01:
print("Correct! Off to a great start, the right answer is dogs!")
score = score + 1
break
elif count == 1:
print("That is wrong",name,"but you can try again. Hint: They like bones. ")
if count == 2 and question1 != answer1:
print("Incorrect again, sorry! The right answer was dogs.")
Please do correct me if that looks wrong, I am new to python. Anyway all I want to do is print the question again without repeating the introduction (start). My actual code is much longer and is an entire quiz and I need to repeat certain sections of code from different parts of the code. Please help! Plus I am sorry if the code didn't print properly when I pasted it into the my post.
So, the problem is that your questions are hardcoded, so they repeat etc. Instead, you could provide a data structure, storing all your questions, wrong ang right answers, which you would pass to some parsing logic. For example:
questions = ['What animal barks?', ...]
answers = [('dogs', 'dog'), ...]
hints = ['They like bones', ...]
def dialog(qst, ans, hnt):
score = 0
for question, answers, hint in zip(qst, ans, hnt):
incorrects = 0
while True:
usr_ans = input(question)
iscorrect = any(usr_ans.strip().casefold() == answ.strip().casefold() for answ in answers)
if incorrects < 5 or not iscorrect:
print('That is wrong, {}, but you can try again. Hint: {}'.format(name, hint))
incorrects += 1
elif incorrects >= 5:
print('Incorrect again, sorry! The right answer was {}.'.format(' or '.join(answers))
break
else:
print('Correct! Off to a great start, the right answer is {}!'.format(usr_ans))
score += 1
break
return score
It may look a bit complicated as you're starting to learn. I recommend not to code complete things, until the point in time, where you'd already known the basics. For a great start, try official Python Tutorial, and I'd recommend Lutz's Learning Python

python quiz validation not working

The validation doesnt work. im not sure why, is there a way to validate a string. The questions asked are endless i need 10 questions to be asked
import random
name=(input("Please enter your name"))
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10)
numbers=random.randint(1,10)
arith=random.choice("+" "-" "/")
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
if arith=="-":
print(number,arith,numbers)
answer=number-numbers
if arith=="/":
print(number,arith,numbers)
answer=number/numbers
while True:
try:
usersanswer= int(input())
except ValueError:
print ("That is not a valid answer")
continue
if usersanswer==answer:
print("correct")
break
else:
print("incorrct")
The validation doesnt work. im not sure why, is there a way to validate a string
I've taking silentphoenix's answer and made it somewhat more pythonic and six'ed.
You should almost never use python2's input, because on top of being massive security hole, it sometimes does things that can be...rather unexpected.
import random
import operator # contains the python operators as functions
try:
input = raw_input # rebind raw_input to input, if it exists
# so I can just use input :P
except NameError:
pass
name = input("Hi, what is your name?\n")
print("Hi {} let's get started! Question 1".format(name))
#Get out of the habit of using string concatenation and use string
#formatting whenever possible. Strings are *immutable*;
#concatenation has to produce a lot temporary strings and is *slow*
#str.join and str.format are almost always better ideas.
#Python does not have a switch-case, so emulating one with a dictionary
operator_mapping = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
#'/': operator.truediv, #hey, division exists.
#But if you want division to actually work, you'll
#have to introduce a fudge factor :P
}
for i in range(10): # If you're just going for 10 iterations, it should be a for loop
# Brevity :P This is a list comprehension
first_number, second_number = [random.randint(1,10) for _ in range(2)]
oper = random.choice(list(operator_mapping))
answer = operator_mapping[oper](first_number, second_number)
while int(input("{} {} {} = ".format(first_number, oper, second_number))) != answer:
#while abs(float(input("{} {} {} = ".format(first_number, oper, second_number)))-answer) < 0.001: if you want truediv.
print('Wrong answer! try again!')
#If I've left the loop, user has given correct (enough) answer
if i <9: # all but last
print('Well done! Now onto question number {0}'.format(i+2))
print('Well done! You are done!')
In the third line, you ask for input. But a name is a string, so you need raw_input. raw_input takes strings, input only takes numerical values.
Python 2.7 getting user input and manipulating as string without quotations
Nowhere in your code do you update the variable questions, which I am guessing is a counter. You have to update that whenever a question is asked, using question += 1.
Finally, your code at the end does not really make sense. Based off the code, it checks for whether or not it is a string, but then compares it to the answer regardless. The if statement needs to be within the try.
The else statement does not match any outer indentation.
Finally, because of the while True: your code will never exit the loop unless the answer is wrong. At the point the entire program terminates. I see what kind of program you are trying to write, but the parameters for random number generation have to be within some kind of a while question <= 10 loop. As of now, only two lines in the program are being affected by that first while loop.
EDIT: I am working on a good example code. Hopefully this answer will help until I can finish it.
EDIT: Here is code that shows how it works within a while loop.
import random
from random import randint
name = raw_input("Hi, what is your name?\n") # Asks for name
print "Hi " +name+ " let's get started!"
score_count = 0
question_count = 0 # creates counter
while question_count <= 10: # Everything MUST BE WITHIN THIS LOOP
# makes numbers and operator
first_number = randint(1,10)
second_number = randint(1,10)
oper = random.choice("+""-""*")
# determines the problem
if oper == "+":
answer = first_number + second_number
print first_number,second_number,oper
elif oper == "-":
answer = first_number - second_number
print first_number,second_number,oper
elif oper == "*":
answer = first_number*second_number
print first_number, second_number, oper
user_answer = int(raw_input("Your answer: "))
if user_answer != answer:
print 'Wrong answer! try again!'
user_answer = int(raw_input('Your answer: '))
if user_answer == answer: # exits the while loop when the correct answer is given
if question_count < 10:
print 'Well done! Now onto question number {0}'.format(question_count+1)
score_count += 1
elif question_count == 10:
print 'Well done! You are done!'
score_count += 1
else:
print 'Something is wrong.'
question_count += 1 # updates the variable
# GOES BACK TO THE BEGINNING UNTIL question_count IS GREATER THAN OR EQUAL TO 10
print "Your score was: {}".format(score_count)
Happy coding! and best of luck!
hi im Nathan and I saw this post I am 5 years to late but I figured if someone on here is knew to python I have a much easier (in my opinion) way to do this in python 3, the code is below:
import random #random module automatically downloaded when you install python
name = input("Please enter your name ")
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10) #creating a random number
numbers=random.randint(1,10) #creating a random number
list = ["+","-","/"] #creating a list (or sometimes called array)
arith=random.choice(list) #getting random operators from list (+,-,/)
question += 1 #basically means add one to question variable each time in loop
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
elif arith=="-":
print(number,arith,numbers)
answer=number-numbers
elif arith=="/":
print(number,arith,numbers)
answer=number/numbers
answer = int(answer)
#from HERE
useranswer = "initialising this variable"
while useranswer == "initialising this variable":
try:
usersanswer= int(input())
if usersanswer==answer:
print("correct")
break
else:
print("incorrect")
except ValueError:
print ("That is not a valid answer")
#to HERE it is input validation this takes a while to explain in just commenting
#but if you dont know what this is then copy this link https://youtu.be/EG69-5U2AfU
#and paste into google for a detailed video !!!!!!
I hope this helps and is a more simplified commented bit of code to help you on your journey to code in python

Categories