If/else statement in Python 3x [duplicate] - python

This question already has answers here:
Python - User input data type
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am very new to programming and Python. To get started I'm working on a little game that will ask the user for some input and then do "something" with it. My problem is I've seem to account for if the user types in an int lower or high than my parameters BUT i can't seem to find a way to re-prompt the user if they type in anything but an int.
With my limited knowledge I thought that when using an if/elif/else statement if you didn't define what the if/elif is looking for than the else statement was there for everything else that you didn't account for?
Looking for some more insight on how to master this fundamental concept
Thank you in advance!
prompt = True
while prompt == True:
user_input = input("Please give me a number that is greater than 0 but less than 10 \n >")
if user_input > 0 and user_input <= 10:
print("Good job " + str(user_input) + " is a great number")
break
elif (user_input > 10):
print("Hey dummy " + str(user_input) + " is greater than 10")
elif (user_input <= 0):
print("Hey dummy " + str(user_input) + " is less than 0")
else:
print("I have no idea what you typed, try again!")

How about something like this?
a = -1
while a < 0 or a > 10:
try:
a = int(input("Enter a number between 0 and 10: "))
except ValueError:
continue
This will only allow the user to enter an int from 0 to 10, this will also remove the need to print those messages if the number is outside of this range, if you would like to keep those messages I could make adjustments and show you how to handle that as well

Related

How can I return to the top of a file after an else statement? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 months ago.
I'm trying to understand how to return to the top of a Python script from an else statement.
print('lets do some math!')
math_operation = input('Which would you like to start with, addition, subtraction or division? ')
if math_operation == "addition":
input_add1 = int(input('First number please '))
input_add2 = int(input('Second number please '))
result = input_add1 + input_add2
print(f'{input_add1} + {input_add2} = {result}')
elif math_operation == "subtraction":
input_sub1 = int(input('First number please '))
input_sub2 = int(input('Second number please '))
result = input_sub1 - input_sub2
print(f'{input_sub1} - {input_sub2} = {result}')
else:
print('I did not quite get that, lets try again')
input_div = int(input('now provide a number that is divisible from the answer'))
answer = result / input_div
print(answer)
You need to put this inside a loop,
math_operation= None
print('lets do some math!')
while math_operation != 'quit':
math_operation = input('Which would you like to start with, addition, subtraction or division? or quit')
... your code ...

Input and if/else statements not processing correct input [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I'm putting together a small program for a friend that requires an input from the user, and depending on the input it does a certain function
Heres my code:
value = input ("Enter Number")
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")
However, even entering 1 or 2, it always prints "hmmm".
I've tried everything including making a new function and passing the input into it and still it doesn't take. Any advice?
That's because you are taking input as a string not an integer.
Because of it your value is string and when it is compared with integer 1 or 2 it's coming false and the else condition gets satisfied.
Correct code:
value = int(input ("Enter Number"))
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")

While loop until the input is a number. Python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 2 years ago.
What's poppin my coding gang. So atm I'm learning Python and I'm a totally a newbie and I face this problem. So I created a unit converting program and I was successful to make a while loop for unit and everything with the code below works just fine:
weight = int(input("Weight: "))
unit = input("(K)g or (L)bs ? ")
while unit.upper != ("K" or "L"):
if unit.upper()=="L":
converted = weight*0.45
print(f"You are {round(converted)} kilos")
break
elif unit.upper()=="K":
converted=weight//0.45
print(f"You are {converted} pounds")
break
else:
print("Invalid unit. Please type K or L: ")
unit=input()
continue
But I also wanted to experiment more and I also wanted to create a while loop for a weight input, so that it will go forever until you type any positive float or integer number, because when I run the program and in weight input I would accidently type a letter - a big red error would appear on my screen saying:
Exception has occurred: ValueError
invalid literal for int() with base 10: 'a'
line 1, in <module>
weight = int(input("Weight: "))
So when I tried to change it to a while loop, it didn't work and my final result looked like this:
weight = int(input("Weight: "))
while weight != int():
if weight==int():
break
else:
print("Invalid unit. Please type a number: ")
weight=int(input())
continue
unit = input("(K)g or (L)bs ? ")
while unit.upper != ("K" or "L"):
if unit.upper()=="L":
converted = weight*0.45
print(f"You are {round(converted)} kilos")
break
elif unit.upper()=="K":
converted=weight//0.45
print(f"You are {converted} pounds")
break
else:
print("Invalid unit. Please type K or L: ")
unit=input()
continue
I know it's shit and at this point I'm stuck, it's just constantly typing me "Invalid unit. Please type a number: " and I can't get out of that loop. I don't even know what to type or what to do anymore so I decided to come here for a help.
I want to make with this code that until you type a number in weight input - you won't be allowed to go further, but after you type correctly - the program will continue to a unit input. Thx
The or operator does not work as you expect.
I suggest to replace it by:
while unit.upper() in "KL":
✅ Tested - I think you need to check the input for weight like this:
weight = input("Weight: ")
while not weight.isdigit():
print("Invalid unit. Please type a number... ")
weight= input("Weight: ")

How can I tell the program only a certain type of input its allowed? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
Im working on a program that asks the user to enter input twelve times. Those inputs must be included in a list in which there are included the first twelve letters of the alphabet.
letters=("A","B","C","D","E","F","G","H","I","J","K","L")
def gen_():
s = []
for i in range(1, 13):
in_ = input("Input the note number " + str(i) + ", please\n", )
if in_ in letters:
s.append(in_)
print(" \n"+str(s)+"\n " )
else:
print("not valid")
gen_()
I would like to tell the program that if a certain input is not valid, it should ask the user to try again and enter a valid input on that same instance. I tried setting "i" back to the value in which the input was not valid, by subtracting 1 to i, but it didn´t work.
How can I code this? Thanks
You need a while loop to continuously verify if the entered input is valid. Please check this solution:
def gen():
s = []
for i in range(12):
in_ = input("Input the note number {i}, please: ".format(i=i))
while len(in_) != 1 or ord(in_) < 65 or ord(in_) > 76:
in_ = input("Invalid input, please enter again: ")
s.append(in_)
return s
I made some tweaks in the while loop to check for the ASCII values of the character entered instead of looking in a predefined tuple/list.
The reason why subtracting 1 from i probably didn't work is because python doesn't work like other programming languages where you can modify the index variable inside the for loop and it will react accordingly. To put it very simple since I don't want to get into details, any changes you make to i inside the loop won't change what value i will have in the next iteration.
One way to do what you're trying to do is to write a while loop that repeats as long as the user is giving an invalid input. Something like this:
in_ = input("Input the note number " + str(i) + ", please\n", )
while in_ not in letters:
print("not valid")
in_ = input("Input the note number " + str(i) + ", please\n")
s.append(in_)
print(" \n"+str(s)+"\n " )

Exception handling on 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'm new here, and I'm also new in coding.
I'm actually learning Python, and I have a question, because I already tried everything, but I was unable to resolve it.
I have this code from a little game I saw in a tutorial. The objective is to the user guess the number. What I was trying to do is to handle the exception if the user enters a letter, then show an error message and go back to the loop. If someone helps me, I will be grateful.
import random
highest = 200
answer = random.randrange(highest)
guess = raw_input("Guess a number from 0 to %d:" %highest)
while(int(guess)!=answer):
if (int(guess) < answer):
print "Answer if higher"
else:
print "Answer is lower"
guess=raw_input("Guess a number from 0 to %d: " %highest)
raw_input ("You're a winner Face!!!")
This is how i would do it:
import random
highest = 200
answer = random.randrange(highest)
while True:
try:
guess = int(input("Guess a number from 0 to %d: " %highest))
if guess < answer:
print("Answer if higher")
elif guess > answer:
print("Answer is lower")
else:
print("You're a winner Face!!!")
break
except:
print('Input not valid!')
continue
I have a dummy condition on the while and i am directing the flow from inside the loop using continue and break. I wrapped the whole guess checking procedure in a try-except block but the only thing that is really tried is the conversion of the input to integer. Everything else could also be moved after the except bit.

Categories

Resources