I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.
Related
number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)
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!
I am completing an assignment where we have to make a list of classes you plan to take in Python. The max amount of classes you can have in the list is 5. When the sixth class is entered, it should ask you to drop another class in already in the list to add the next entry. I have my code so far below. When it runs, it is an endless loop, rather than stopping and displaying the message when it reaches 6. What can I do to fix this?
courseList = []
#sets beginning of loop to 0
course = 0
courses = "none"
#input to enter course name
while (courses != "Exit"):
courses = str(input("What is the name of the course? "))
courseList.append(courses)
course = course + 1
if (courses == "Exit"):
course = course - 1
#input to drop course
while (course >= 6):
print(courseList)
x = int(input("What course # will you drop? "))
if(1<= x <=6):
courseList.pop(x-1)
course = course -1
print(courseList)
#error message
else:
print("Please select a # between 1-6. ")
I have merged the two while loops together and added some if else
Try this:
CourseList = []
while True:
# Input to enter course name.
course = input("What is the name of the course?\n")
# Check if user wants to exit.
if course == "Exit":
break
# Check the length of the list. If greater than 5, the user selects soemthing to drop.
elif len(CourseList) >= 5:
CourseList.append(course)
# Show user the courses in the list
print(CourseList)
x = input("What course # will you drop?\n")
# Check if x is a number or in range, if not, let the user input again.
while x.isdigit() == False or x < '1' or x > '6':
print("Please choose a number between 1 and 6")
x = input("What course # will you drop?\n")
x = int(x)
CourseList.pop(x - 1)
print(CourseList)
# If none of above, append the course
else:
CourseList.append(course)
The reason the loop does not stop even if you add more than 6 values is that, the condition of the first 'while' loop requires it to stop only if you input "exit".
Which means really that you dont get the first while loop to end for any other reason.
To solve this issue, you should consider what youre trying to do, our initial response is "if the user tries to add more than 5 courses, he should be prompted to remove an existing course". And it becomes apparent that an if condition is sufficient here.
But then we realise, what if the user tries to remove course that does not exist (input is not between 1 and 6). So then we think "while the 6th course is being added, keep prompting for removing a course, until successfully removed". (This issue can be handled in a clean way, such that our intuitive first response is seen in the code, Read till the end)
Having read the reasoning above;
Consider the following:
courseList = []
#sets beginning of loop to 0
course = 0
courses = "none"
#input to enter course name
while (courses != "Exit"):
courses = str(input("What is the name of the course? "))
# Move this to the top, since if user is trying to exit the loop, nothing else needs to be done but that
if (courses == "Exit"):
break
### Add this ###
while course >= 5: # This is essentially also implying if course >= 5 if you think about it
print(courseList)
x = int(input("What course # will you drop? "))
if 1 <= x <= 5:
courseList.pop(x-1)
course = course - 1
else:
print("Please select a # between 1-5. ")
### END ###
courseList.append(courses)
course = course + 1
Now, I also want to add that the second while loop within the first may come off as not clean. For that reason you may want to move it into a function.
def removeCourse(lst, course):
while course >= 5:
print(courseList)
x = int(input("What course # will you drop? "))
if 1 <= x <= 5:
courseList.pop(x-1)
course = course - 1
else:
print("Please select a # between 1-5. ")
which then makes the code become:
while (courses != "Exit"):
courses = str(input("What is the name of the course? "))
if (courses == "Exit"):
break
if course >= 5: # Note how we change this to the if condition now, which was our initial response to the problem, because the function handles the case where the input is not valid
removeCourse(courseList, course)
courseList.append(courses)
course = course + 1
I'm making a number guessing game and can someone tell me why it wont work properly?
import random
import time
time.time()
count=0
a = random.randint(0,100)
b = int(input("What number will you guess?"))
while b != a:
if b > a:
print("TOO BIG")
count = count + 1
elif b < a:
print("TOO SMALL")
count = count + 1
else b == a:
print("YOU WIN")
count = count + 1
time=time.time()
print("You took",count,"tries")
print("It took you",time,"second")
The reason this isn't working properly is because you're calling b = input outside of your while loop. As it stands, the user will be asked a single time what their guess is, then the loop will just move infinitely, because b is never being modified.
This loop will accomplish more what you want:
a = random.randint(0,100)
b = -1
while b != a:
b = int(input("What number will you guess?"))
A few notes, though:
Firstly, as Lee Daniel Crocker points out, the user will actually never see "YOU WIN", because you've structured your if-elif-else statement incorrectly. else by definition cannot have a condition - it exists purely in exclusion to all other conditionals in the same block. Additionally, your else statement is the opposite of your while condition. When that else becomes true, the loop exits. You'll need to handle printing "YOU WIN" somewhere else.
Second, you're not validating the user's input in any way - if they enter 'a', the program will crash, because you can't cast 'a' to an int. Either add an exception handler (for ValueError) or using isdigit() on the string, then casting it.
Third, you're not using time.time() correctly - you need to subtract the time at which the user wins from the time at which they started, then represent that value, which is in seconds, in some meaningful way. As it stands you're telling each player that they took the number of seconds since the beginning of the UNIX epoch to complete the game.
Also, for usability reasons, you should probably provide the user some way to break out - a string like "QUIT" - because as it stands, the only way to restart/quit is to either close the application or KeyboardInterrupt.
You need to accept input in the loop. Move the line b = int(input("What number will you guess?")) within the loop.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'False':
guess = guess - int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'Correct':
print 'Success!, your number is approximately equal to:', guess
oracle()
What I am trying to do now is get this sequence of if/ elif/ else commands to loop until the user enters 'Correct', i.e. when the number stated by the program is approximately equal to the users number, however if I do not know the users number I cannot think how I could implement and if statement, and my attempts to use 'while' also do not work.
As an alternative to #Mark Byers' approach, you can use while True:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Your code won't work because you haven't assigned anything to n before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.
Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.