Input function help (python) [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I was trying to play around with the input function. However, it seems that this code is not correct, I looked to see examples online but they tend to be basic and what i was trying to do was slightly above basic. Also, is it possible to put the return function instead of the print one? if not why? I'm new to this so if these all sound stupid please forgive me.
cheers!
def user_data(x):
age = input("how old are you?")
if age == 20:
print("you win")
else:
print("you lose")

input returns a string, while you are comparing age (a string) to an integer.
You have to either compare age to a string (so age == "20"), or convert age to an int (so int(age) == 20).
See docs to find out how input works.

def user_data(age):
if age == 20:
print("you win")
else:
print("you lose")
age = int(input("how old are you?"))
user_data(age)

Related

Lists function not working in if condition [duplicate]

This question already has answers here:
Fastest way to check if a value exists in a list
(11 answers)
Closed 2 years ago.
Hi I am new to programming and I like to try to make the code work different way.
Unfortunately, variable called unlucky cant be read when printing.
So when the user enter the listed value [7 6 5], it doesnt print out as "You have selected unlucky number". I have include the image and copy of my code :
option = int(input("Guess the correct number between 0 to 10 : \nYour choice :"))
unlucky_number= [7,6,5] # Unlucky numbers, listed
if option == unlucky_number: # should print somewhere close when user enters list number
print("You have selected a unlucky number")
elif option== 6: # only 6 is correct
print ("Correct Guess")
elif option in range (0,4):
print("Not close")
else:
print ("Not in the range, choose between 1 to 10")
Please tell me whats wrong with it and how can I make a better version of it.
Thank you enter image description here
if option == unlucky_number
This line is causing you troubles. Your "option" holds a singular number, but your "unlucky_number" is a list. List can not be equal to a number, they are completely different animals. What you want is:
if option in unlucky_number

I have a problem with a math quiz in python

I am very new at python and i just wanted to make a pprogramm with a question how much is 23*10? and if the user answers 230 it will print true but if not it would print false and i dont know how to ... this is my first attempt
Question = input("How much is 23 * 10? ") if Question == "230":print("True")
It is pretty much what you made, lacking indentation and the else. Also, I'm adding int() before input() because otherwise, the value provided will be considered as a string instead of a number. It doesn't make much difference if you are then comparing it with a string "230" but I just thought I'll change it a bit to show you another perspective.
question = int(input("How much is 23 * 10? "))
if question == 230:
print("True")
else:
print("False")
As I explained before, if you do not wish to use int then you must compare the value to a string:
question = input("How much is 23 * 10? ")
if question == "230":
print("True")
else:
print("False")

Variable error in function [duplicate]

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 5 years ago.
I wanted to make a number guesser game, and I wrote this code:
from random import randint as rand
number=rand(-1,1001)
tries=0
def numguess():
guess=int(input("The chosen number is between 0 to 1000.\nEnter your guess : "))
tries=tries+1
numguess()
while True:
if number==guess:
print ("You won. My number was effectively" ,number,". \n It took you ",tries, "to guess the number.")
break
elif number<guess:
print ("The number I chose is lower than your guess")
numguess()
else:
print ("The number I chose is higher than your guess")
numguess()
When I run it, it asks me for input then raises a UnboundLocalError. Is there something I am doing wrong? I tried searching but I don't understand. Thank you.
your tries variable is treated locally - since you assign value to it, use:
global tries
tries = tries +1
in your function

Continue to ask for input until correct answer is given(Python) (Non number values) [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I'm trying to write a piece of code with that repeats the question until the correct answer is given, with a few different responses for likely answers. This is what I have so far, but after it responds to the input given, the program moves on. I can't figure out how to do this with a while loop since it ends with a specific answer and not with else.
answer = input("What is your favorite eldest daughter's name? ").lower()
if answer == "a" or answer == "al":
print("Of course, we all knew that")
elif answer == "c" or answer == "chris":
print("""Oh she must be standing right there.
But that\'s not it, try again.""")
elif answer == "e" or answer == "ed":
print("Not even the right gender. Try again.")
elif answer == "n" or answer == "nic":
print("Only biological children please.")
else:
print("I'm sorry. Only children. Were you thinking of the dogs?")
break is what you want. Use it like so:
while 1:
answer = input("What is your favorite eldest daughter's name? ").lower()
if answer == "a" or answer == "al": #assuming this is the right answer
print("Of course, we all knew that")
break
elif answer == "c" or answer == "chris":
print("""Oh she must be standing right there.
But that\'s not it, try again.""")
elif answer == "e" or answer == "ed":
print("Not even the right gender. Try again.")
elif answer == "n" or answer == "nic":
print("Only biological children please.")
else:
print("I'm sorry. Only children. Were you thinking of the dogs?")
You basically need to keep repeating the question until the answer is considered to be acceptable by the program.
Code
#!/usr/bin/python3 -B
answers = ['alice', 'chris', 'bob']
answer = None
while answer not in answers:
answer = input('Enter your answer: ')
print('Your answer was: {}'.format(answer))
Basically the code here has a list of acceptable answers and it initializes the user's answer to None. Then it enters a while loop that keeps repeating itself until the user's answer is found within the list of acceptable answers.
Output
➜ ~ ./script.py
Enter your answer: alice
Your answer was: alice
➜ ~ ./script.py
Enter your answer: no
Enter your answer: no
Enter your answer: yes
Enter your answer: bob
Your answer was: bob
Improving the Code
You can now adapt the code to use the messages of your choice. Note, too, that if you want to provide a different response for any of the acceptable entries, you could use a dictionary and update the code slightly.
For example, you could have something like this:
answers = {
'bob': 'This was the best choice',
'alice': 'Everyone picks the hot gal',
# ... and so on
}
Then you'd keep iterating just like before by checking the keys of the answers dictionary (e.g. while answer not in answers.keys():).
When the loop exits with an acceptable answer, you'd simply
print(answers[answer])
If answers == 'alice', then the program would print Everyone picks the hot gal.
It would significantly simplify your code and make it easier for you to understand and work with :)
Use the while loop, and the break statement:
while True:
# . . .
if correct_answer:
break

How do I make a type check function as a while loop? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
Ptarget = int(input("What is your target amount of points to achieve?"))
while Ptarget != int:
print("You have not provided a valid input, please try again.")
Ptarget = int(input("What is your target amount of points to achieve?"))
How do I make it so the while loop functions, by asking the user for another input if the previous was not an integer, without breaking the program?
Use an exception
while True:
try:
Ptarget = int(input("What is your target amount of points to achieve?"))
break
except:
print("You have not provided a valid input, please try again.")

Categories