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!
Related
We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')
I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.
So, I'm working on Hand Cricket script & i want to stop "for" loop from iterating when a user's choice of number & CPU's choice of number are equal & if it's unequal it should keep iterating until it doesnt reach the final range's value
for i in range(1,7):
print("Ball %d"%i)
user_choice =int(input("Enter a number between 1 to 6 --> "))
cpu_choice=random.randint(1,6)
if user_choice < 7:
print("CPU picked --> ",cpu_choice)
run=cpu_choice+run
if user_choice == cpu_choice:
print("User is OUT!!")
run -= cpu_choice
print("Runs = %d \t Over = %d.%d\n"%(run,i//6,i%6))
break
print("Runs = %d \t Over = %d.%d\n"%(run,i//6,i%6))
else:
print("\nWRONG CHOICE!! %d ball is cancelled.\n"%i)
break
I might be missing something in your question, but it looks like you've already got it. break will force the for loop to exit. So if you wrap your break-statement in a conditional gate (if statement), you can set the criteria that must be met for the break.
Something like this comes to mind:
# Calculate the CPU's Random Integer ONCE
cpu_choice=random.randint(1,6)
# Iteratively Ask User for Input and Validate
for i in range(1,7):
# Capture Input from User
user_choice =int(input("Enter a number between 1 to 6 --> "))
# Verify Input in Specific Range
if user_choice not in range(1,7):
print("{} is not in the valid range. Try again.".format(user_choice))
else:
# Check if User Input Matches CPU's Selection
if user_choice == cpu_choice:
print("You've got the right number! The number was: {}".format(user_choice))
break # break out of the `for` loop!
# Not Correct Input from User
else:
print("{} is not the correct number. Try again.".format(user_choice))
Again, it seems like you've already come to this answer in a way. Are you asking something else instead?
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.
So this is a prompt for user input, and it works just fine. I was printing some names and associated (1 based) numbers to the console for the user to choose one. I am also giving the option to quit by entering q.
The condition for the number to be valid is a) it is a number and b) it is smaller or equal than the number of names and greater than 0.
while True:
number = str(input("Enter number, or q to quit. \n"))
if number == "q":
sys.exit()
try:
number = int(number)
except:
continue
if number <= len(list_of_names) and number > 0:
name = list_of_names[number-1]
break
There is no problem with this code, except I find it hard to read, and not very beautiful. Since I am new to python I would like to ask you guys, how would you code this prompt more cleanly? To be more specific: How do I ask the user for input that can be either a string, or an integer?
A bit simpler:
while True:
choice = str(input("Enter number, or q to quit. \n"))
if choice.lower() == "q":
sys.exit()
elif choice.isdigit() and (0 < int(choice) <= len(list_of_names)):
name = list_of_names[int(choice)-1]
break
Just downcase it.
number = str(input("Enter number, or q to quit. \n"))
number = number.lower()
That will make the q lower case so it doesn't matter if they press it with shift if they press something else just make a if statement that sets a while loop true.