Adding onto an input prompt after the user inputs - python

I'm trying to make a "pi-practicing' program in python, and I want the user's input, if correct, to be placed next to the "3.".
I have:
numbers = [1,4,1,5,9,2,6,5]
def sequence():
i = input("3.")
y = int(i)
if y == numbers[0]:
print ("Good job!")
#??????
numbers.pop(0)
sequence()
else:
print("nope")
sequence()
sequence()
So when prompted, if the user enters 1 as the first number, I want the next input prompt to be 3.1, so the user has to enter 4, and so on.
Thank you in advance!
-rt

You don't need recursion a simple while loop would do. It's generally not good practice to leverage global variables:
def sequence():
numbers = [1,4,1,5,9,2,6,5]
prompt = '3.'
while numbers:
i = input(prompt)
y = int(i)
if y == numbers[0]:
print ("Good job!")
prompt += i
numbers.pop(0)
else:
print("nope")
sequence()

Related

How to convert Celsius to Fahrenheit and vice-versa in python

I'm trying to create a program that will convert Celsius to Fahrenheit and vice-versa.
The first thing the program will do is ask the user what the user wants to convert either Celsius or Fahrenheit. If the input is invalid, print invalid and ask to try again.
Then will ask the user to input the start, end, and interval separated by an asterisk. For example 0102. This means that the start of the conversion will be from 0 to 10 with an interval of 2, thus the value to be converted will be 0, 3, 6, 9
If the start<end, then the interval should be 0<interval otherwise, your program will display an error and ask to try again
Or
If the start>end, then the interval should be 0>interval otherwise, your program will display an error and ask to try again.
If the user inputs has only one value, like 10. This means that the start is equal to 1 which will be the default value for start, up to 10, and the interval is 2 which will be the default value of the interval if start<end.
If the user input has two values like 10*2, this means that the start is equal to 10 up to 2. The interval is set to the default value which is equal to -2 since start>end.
This is my code, it doesn't work and I'm stuck.
And how am I gonna use for loop here?
while True:
pick = input("Enter your input either in Celsius or Fahrenheit: ")
if pick == "Celsius":
pass
elif pick == "Fahrenheit":
pass
else:
print("Invalid input. Try again.")
continue
while True:
sei = input("Enter the start, range, and interval separated by an asterisk(*): ").split("*")
if len(sei) == 3:
if int(sei[0].isdigit()) < int(sei[1].isdigit()) and 0 < int(sei[2].isdigit()):
pass
elif int(sei[0].isdigit()) > int(sei[1].isdigit()) and 0 > int(sei[2].isdigit()):
pass
else:
print("Error. Try again.")
continue
else:
print("Error. Try again")
Input :0 * 100 * 3
Output:
!
Then the program will ask the user to try again. If yes, the program will run from the very start.
If no, it'll print "Thank you" and the number of invalid inputs in the whole program and the number of times the user successfully converts temperature.
Here is my solution (inefficient maybe, I'm a beginner too) to your problem.
temperatureValues = []
while True:
pick = input("Enter your input either in Celsius or Fahrenheit: ")
if pick == "Celsius":
pass
elif pick == "Fahrenheit":
pass
else:
print("Invalid input. Try again.")
continue
while True:
sei = input("Enter the start, range, and interval separated by an asterisk(*): ").split("*")
if len(sei) == 3:
if int(sei[0]) < int(sei[1]) and 0 < int(sei[2]): # normal case
for i in range(int(sei[0]), int(sei[1]), int(sei[2])):
temperatureValues.append(i)
break
elif int(sei[0]) > int(sei[1]) and 0 > int(sei[2]): # reverse case
for i in range(int(sei[1]), int(sei[0]), int(sei[2])):
temperatureValues.append(i)
break
else:
print("Error. Try again.")
continue
elif len(sei) == 2:
for i in range(int(sei[0]), int(sei[1]), 2):
temperatureValues.append(i)
break
elif len(sei) == 1:
for i in range(1, int(sei[0]), 2):
temperatureValues.append(i)
break
else:
print("Error. Try Again.")
continue
print(temperatureValues)
# Implement your conversion here, by performing the conversion operation on each value of the temperatureValues list.
I would also advise you to do comparison in values by writing the variable first. Like int(sei[0]) > 0, instead of writing this in reverse. Makes the code more readable.
Best of luck!

Python while loop ask more than once for input

I've been trying to solve the issue with guessing the number program,
The first number the program has to print Ans which is (Startlow + Starthigh)/2 and then Ans gets updated depends on the input
I can't figure out why my while loop keeps waiting for the input for at least 2 times until it prints the results even if I press l or h (unless I press c) which breaks the loop
Startlow = 0
Starthigh = 100
Ans = (Startlow + Starthigh)/2
print("Please think of a number between 0 and 100!")
while True:
print("Is your secret number " + str(int(Ans)))
if input() == "c":
print("Game over,Your secret number was: "+str(int(Ans)))
break
elif input() == "l":
Startlow = Ans
Ans = (Startlow + Starthigh)/2
elif input() == "h":
Starthigh = Ans
Ans = (Startlow + Starthigh)/2
else:
print("Sorry, I did not understand your input.")
any help appreciated :)
You should be asking for input once in the loop, and then comparing that answer to the items you want.
You are instead requesting a (potentially different) answer at each of your conditionals.
The number of questions asked depends on how many conditionals you fall through.
Just do:
x = input()
if x == "c":
#And so on...

How to return to the top of a loop if the else statement is reached

I hope the title is explanation enough. Basically, the user inputs a number and the number has to be between 1 and 147. If it is, the next required input is reached(num_guess). But we need to have the user try again if the number is not within the parameters. But I cannot figure out how to do this. Thanks in advance.
word_correct = False
def length_check(x):
while (word_correct == False):
if x >= 1 and x <= 147:
return word_correct == True
break
else:
print("Try another number")
# print(input("Please enter a word length: ")) ## ignore me
word_length = input("Please enter a word length: ")
length_check(word_length)
num_guess = raw_input("Please enter an amount of guesses: ")
try this
word_correct = False
def length_check(x):
while (word_correct == False):
if x >= 1 and x <= 147:
return word_correct == True
else:
print("Try another number")
new_word= input("Please enter a word length: ")
length_check(new_word)
word_length = input("Please enter a word length: ")
length_check(word_length)
num_guess = raw_input("Please enter an amount of guesses: ")
I would not try to put the loop inside word_check. Separate the responsibility for checking the length from the control flow & printing messages.
You can use an infinite loop, that is only broken out of when a valid value is input.
Also don't forget to convert to int. I am presuming you are using python 3? There is the possibility for the user to enter something that is not a valid integer (e.g. "abc"), so use an exception to handle that. If you are using python 2, swap input for raw_input.
def length_check(x):
return x >= 1 and x <= 147
while True:
try:
word_length = int(input("Please enter a word length: "))
except ValueError:
print('please enter a valid number')
continue
if(length_check(word_length)):
break
print("Try another number")
Notice that this method involves only a single instance of input. This will make life easier later. For example, if you want to change the message and you don't have to remember to change it in two places or assign it to some string variable.
Basically you don't need a break after return.Once the compiler encounters return,it doesn't go through the next statements.
What's the error in your code?
The implementation is not proper.
Use of break or return not in desired place
The code for your requirement can be implemented as follows -
def length_check(x):
while(1):
temp = input()
if temp >= 1 and temp <= 147:
return
else:
print 'Enter proper length'
This should solve your problem.
This strategy is much more concise, and utilizes recursion. No while loop is needed for what you are trying to do:
def main(warning=''):
if warning:
print(warning)
word_length = input("Please enter a word length: ")
if word_length >= 1 and word_length <= 147:
num_guess = raw_input("Please enter an amount of guesses: ")
else:
main(warning="Try another number")
#... now do something with num_guess
You may try this
word_correct = False
def length_check(x):
while (word_correct == False):
if x >= 1 and x <= 147:
word_correct == True
break
else:
x = input("Try another number")
# print(input("Please enter a word length: ")) ## ignore me
return
word_length = input("Please enter a word length: ")
length_check(word_length)
This might work:
else:
word_length = input("Try another number")
length_check(word_length)
In the event of a wrong guess (the else) you ask the user for another input to word_length and then run the checking function length_check again. User can go through this as many times as they like (ie keep taking the else branch by entering a wrong value) until they get the number correct, and satisfy the if condition.
You might be able to get away without using break if you use this.
A while True with break in block works like a do{} until() in other language, so as below program to satisfy the problem statement. Another point is to take care of recursion limit there is no hard limit in code to break out.
hint = "Please enter a word length: "
while True:
x = int(raw_input(hint).strip())
if 1 <= x <= 147:
break
else:
hint = "Try another number"
num_guess = int(raw_input("Please enter an amount of guesses: ").strip())

Alternative to Goto, Label in Python?

I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.
So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:
x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
What would you do?
There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:
import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
continue jumps to the next iteration of the loop, and break terminates the loop altogether.
(Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)
Python does not support goto or anything equivalent.
You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the control flow page for more information.
x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
In many other cases, you'll want to use a function to handle the logic you want to use a goto statement for.
You can use infinite loop, and also explicit break if necessary.
x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break

Returning to menu after command? Python

I know all my questions are really easy but I'm a beginner so here it is...
I have been developing the guessing number thing after everyones help, but I want to then return to a menu which has just been left. Here's the code:
import time
import random
animalmenu()
def animalmenu():
print()
print()
print()
print()
print('Welcome to the menu. I am thinking of a menu. Select the option\'s below to try and guess my animal.')
print()
print('a) No. of Legs')
print('b) Type of animal')
print('c) Preffered Climate')
print('d) Size')
print('e) Colour')
print('f) Diet')
print('g) Habitat')
print('h) Can be kept as pet')
print('i) Guess animal')
print()
print('When in a menu, type in \'555\' to return here')
AniChoice = input('Choose your option: ')
if AniChoice == 'a':
loop = 10
while loop == 10:
print()
print('')
print()
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
print('r = Return to menu, g = guess again.')
rg = input()
if rg == 'g':
print('Loading...')
elif rg == 'r':
loop = 0
time.sleep(1)
print('Returning to menu...')
time.sleep(1)
animalmenu()
everytime I run it, I type in a number as the code asks but then, instead of asking if I want to return to the menu it just asks the question again and again, 'Guess the number of legs: '. I know this is something to do with my looping method but I do not understand and because of the integer setting I cannot just make another if, like so:
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
elif guessleg == 'back':
loop = 0
animalmenu()
And I do not see any other way of doing it as neither way seems to work? How would you suggest returning to animalmenu()?
As the message is telling you, 'back' is not an integer, but you are comparing it to a variable into which you have put an integer value. Specifically, your line:
guessleg = int(input('Guess the number of legs: '))
puts an integer value into guessleg (or more properly tries to) from the user's input.
One approach to resolve this is to capture the user's input in a string variable, compare that string to 'back' first, and then convert to an integer if needed.
Another approach is to wrap a try/except around the integer conversion and proceed with the integer check if the conversion is successful and with the check against 'back' if the exception is encountered. This is probably preferred these days and I've put it into code:
inp_val = raw_input('Guess the number of legs: ')
try:
guess_num = int(inp_val)
if guess_num == leg:
print('True')
else:
print('False')
except ValueError:
if inp_val == 'back':
loop = 0
else:
print 'Invalid entry'
animalmenu()
because the you convert your input into integer and store it into guessleg which means guessleg is also an integer. However, 'back' is a string. You can't compare the string with integer. the 3 == 'back'means nothing.
and syntax error may because of your indent.
UPDATE:
if you want to return to the top menu, you can do something like:
def animalmenu():
while True:
print your menu here
and do something....
while ...:
get input and do something...
if get the input of 'back to menu':
break
UPDATE again:
I don't think you shall use input() here, try readline() or raw_input() instead.

Categories