--Python
What's wrong in this code?
a=int(input('enter a number'))
b=list(range(1,11))
if a not in b:
int(input('enter a number'))
else :
print('ok')
output:
enter a number 89
enter a number 8
Please explain a bit further what it is you're trying to do, if you're trying to output "OK" for the second input of '8', then you need to change the logic of this code.
a=int(input('enter a number'))
this line prints "enter a number"
then your if statement checks if its within b
but if it's not it prints "enter a number" again without doing anything with it, as seen in the next line:
int(input('enter a number'))
try using a for loop or while loop if you want your code to run through the if-else blocks more than once.
also, notice that you didn't put the input inside variable a again.
EDIT: try this code:
print('enter a number')
a=int(input())
while a not in range(1,11):
print('enter a number')
a=int(input())
else :
print('ok')
Related
This question already has answers here:
Why does my input always display none in python? [closed]
(2 answers)
Closed 23 days ago.
I wrote a simple program to track household items and output to a text file, with a while loop to have it keep running till "exit" is entered. I get the word "None" on the line below the input line when I haven't written it to do so. Here is my code.
HouseHoldItems = open('C:\\_PythonClass\\Assignment03\\HouseHoldItemsAndValue.txt', mode='a')
Items = ''
Value = ''
# while loop to keep program running until user enters "Exit"
while(True):
# Items is the primary variable, determines if user is entering new household item or wants to end the program
Items = input(print("Enter an Item (Or type 'Exit' to quit) : "))
# If statement to determine if user wants to end program
if(Items.lower() == "exit"):
break
# Else statement to write household items to the file, followed by value of items
else:
HouseHoldItems.write(Items + ', ')
Value = input(print("Enter an estimated Value: "))
HouseHoldItems.write(Value + '\n')
HouseHoldItems.close()
Here is a snip of the way the code looks as I input data items. (https://i.stack.imgur.com/CHOWk.png)
Is it part of the while(true) piece that is making it do this? Thanks for the help in advance.
You do not need to use the print function when using the input function.
Use:
Items = input("Enter an Item (Or type 'Exit' to quit) : ")
and:
Value = input("Enter an estimated Value: ")
While we're at it, in test conditions for while and if statements while your code works as is, it is not considered 'pythonic'. The pythonic way is to not use parentheses. ie
While True:
and:
if Items.lower() == "exit":
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I try to validate user input if is integer not in a function.
while True:
try:
number = int(input('Enter the number: '))
except ValueError:
print('Try again. Input phone number, must containing digits. ')
break
print (number)
If I enter number it works prints the number (however Pycharm tells me that variable number in last line might ve undefined) however when it crash instead asking for enter again:
Enter the number: s
Try again. Input phone number, must containing digits.
Traceback (most recent call last):
line 9, in <module>
print (number)
NameError: name 'number' is not defined
In a function it seems easier to make but in this case I'm lost.
break means you leave the loop, even if you've had the ValueError, despite number not being assigned yet.
Instead of putting the break outside the try, have you considered putting it inside, so it only triggers if number gets assigned successfully?
while True:
try:
number = int(input('Enter the number: '))
break
except ValueError:
print('Try again. Input phone number, must containing digits. ')
print(number)
Basically, after I have made an input, it prints the text on a new line. I want it to print the text after the user input on the same line. I don't want to get an input then print it back to the user, I want to just have an input that does nothing but lets the user type something. (I am new to python, so please keep it simple)
This is for a little choice game i'm making for fun. I've tried to do input("Blah", end = " ") but it just tells me input() takes no keywords.
import time
def type(str):
for letter in str:
print(letter, end='')
time.sleep(0.02)
type("My card number is ")
input()
time.sleep(0.5)
type(" and the expiry date is ")
input()
time.sleep(0.5)
type(". Finally,")
time.sleep(0.5)
type(" the three numbers on the back are ")
input()
print(".")
I wanted it to end up like this:
My card number is 1234 and the expiry date is 1234. Finally, the three
numbers on the back are 123.
Instead I got:
My card number is 1234
and the expiry date is 1234
. Finally, the three numbers on the back are 123
.
I am trying to create a multiple choice quiz that takes questions from an external .txt file and prints it in python. The text file is laid out like this:
1,Who was the first man to walk on the moon?,A.Michael Jackson,B.Buzz Lightyear,C.Neil Armstrong,D.Nobody,C
When I run the code and input the right answer it still says incorrect but continues to say the answer I inputted.
In the code I split each line in the text file by a ',' so the correct answer in the text file is always detail[6]. In the code I have put:
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I thought this would work as it is checking the inputted answer against detail[6] but it always comes out as incorrect.
import random
score=0
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
questions = random.sample(quiz, 10)
for question in questions:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
answer=input("Answer: ")
while True:
if answer.upper() not in ('A','B','C','D'):
print("Answer not valid, try again")
else:
break
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I would like the code to be able to check if the inputted answer is correct by checking it against detail[6] within the text file, instead of always coming out as incorrect, the correct answer is detail[6].
The problem is that readlines() retains the newline character at the end of each line.
Your detail[6] is something like 'C\n' rather than 'C' itself. To fix that, use
detail = question.strip().split(",")
I need to use string (or int, bool, etc.) which will be same as everything. So this code:
user_input = input()
if user_input in *magic_string_same_as_everything*:
return True
should return True everythine, no matter what will user type into console.
Thanks for your help
Edit:
I see, that I've asked verry badly.
I'm trying to get 3 user input in this for cycle:
user_input = ["", "", ""] # Name, class, difficulty
allowed_input = ["", ["mage", "hunter"], ["e", "m", "h"]]
difficulty = {"e": 1, "m": 2, "h": 3}
message = ["Please enter your heroic name",
"Choose character (mage/hunter)",
"Tell me how difficult your journey should be? (e / m / h)"]
print("Welcome to Dungeons and Pythons\n" + 31 * "_")
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if user_input[i] in allowed_input[i]:
break
Choose of name is without restrictions.
I hope, that now my question makes a sense.
You could just get rid of the if-statement and return True without the check or (if you really want to use the if-statement) you type if(True) and it will always be true.
You want True for non empty string?
Just use user_input as bool.
user_input = input()
if user_input:
return True
In your question Name is special case, just check it like this and for the rest of input you can use range(1,3).
Alternatively switch to using regular expressions
allowed_input = ["\A\S+", "\A(mage|hunter)\Z", "\A[emh]\Z"]
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if re.match(allowed_input[i], user_input[i]) :
break
Initial response
This one liner should work.
If user inputs anything, it counts as an input & prints 'True', but if user just hits 'Enter' without typing anything, it returns 'No input'
print ("True" if input("Type something:") else 'No input')
After your edited question
To achieve what you want, you can define a function that checks for the user input values & corrects them if incorrect.
import re
# for user input, a single line of code is sufficient
# Below code takes 3 inputs from user and saves them as a list. Second and third inputs are converted to lowercase to allow case insensitivity
user_input = [str(input("Welcome to Dungeons & Pythons!\n\nPlease enter username: ")), str(input("Choose character (mage/hunter): ").lower()), str(input("Choose difficulty (e/m/h):").lower())]
print (user_input) # Optional check
def input_check(user_input):
if user_input[0] != '':
print ("Your username is: ", user_input[0])
else:
user_input[0] = str(input("No username entered, please enter a valid username: "))
if re.search('mage|hunter', user_input[1]):
print ("Your character is a : ", user_input[1])
else:
user_input[1] = str(input("Incorrect character entered, please enter a valid character (mage/hunter): ").lower())
if re.search('e|m|h',user_input[2]):
print ("You have selected difficulty level {}".format('easy' if user_input[2]=='e' else 'medium' if user_input[2]=='m' else 'hard'))
else:
user_input[2] = str(input("Incorrect difficulty level selected, please choose from 'e/m/h': "))
return (user_input)
check = input_check(user_input)
print (check) # Optional check
In each of the if-else statements, the function checks each element and if no input/ incorrect input (spelling mistakes, etc.) are found, it asks the user to correct them & finally returns the updated list.
Test Output
With correct entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username: dfhj4
Choose character (mage/hunter): mage
Choose difficulty (e/m/h):h
['dfhj4', 'mage', 'h']
Your username is: dfhj4
Your character is a : mage
You have selected difficulty level hard
['dfhj4', 'mage', 'h']
With incorrect entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username:
Choose character (mage/hunter): sniper
Choose difficulty (e/m/h):d
['', 'sniper', 'd']
No username entered, please enter a valid username: fhk3
Incorrect character entered, please enter a valid character (mage/hunter): Hunter
Incorrect difficulty level selected, please choose from 'e/m/h': m
['fhk3', 'hunter', 'm']