I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)
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}!')
Python beginner here. Practicing user input control.
Trying to make user input loop to the beginning if anything but a whole number between 1 and 10 is used. Been trying for hours, tried using Try and Except commands but couldn't do it correctly. What am i doing wrong? Thank you.
Edit:
Thank you very much for your help everyone, however the problem is still not solved (but very close!) I'm trying to figure out how to loop back to the beginning if anything BUT a whole number is typed. Agent Biscuit (above) gave a great answer for floating numbers, but any word or letter that is typed still produces an error. I´m trying to understand how to loop when anything random (except whole numbers between 1 and 10) is typed. None of the above examples produced corrcct results. Thank you for your help
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
else number != (> 0 and < 10):
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
I have identified some problems.
First, the input statement you are using would just raise an error if a float value is entered, because the int at the start requires all elements of the input to be a number, and . is not a number.
Second; your else statement. else is just left as else:, and takes no arguments or parameters afterwards.
Now, how to check if the number is not whole? Try this:
while True:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
This accepts a float value, but only accepts it if it is equal to a whole number, hence the (round(number)==number).
Hope that answers your question.
First of all, you can't use a condition in a else statement. Also, you need to use or operator instead of and if one of the conditions is acceptable.
So, your code needs to be like this
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
elif number < 0 or number >10:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
Thanks to ack (above) for pointing me to a useful link. By studying another thread, I found the solution. It may not be perfect code, but it works 100%:
while True:
try:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("\n")
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
continue
except ValueError:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0
Code:
loop = 0
def main():
while loop == 0:
Num = input("Please Enter The Number Of People That Need The Cocktails ")
print()
print(" Type END if you want to end the program ")
print()
for count in range (Num):
with open("Cocktails.txt",mode="w",encoding="utf-8") as myFile:
print()
User = input("Please Enter What Cocktails You Would Like ")
if User == "END":
print(Num, "Has Been Written To The File ")
exit()
else:
myFile.write(User+"/n")
myFile.write(Num+"/n")
print()
print(User, "Has Been Written To The File ")
Error:
line 9, in main for count in range (Num): TypeError: 'str' object
cannot be interpreted as an integer
I'm trying to set the variable as the number of times it will repeat how many cocktails they would like.
Example:
How many cocktails ? 6
The script should then ask the user to enter what cocktails he wants six times.
In Python, input() returns a string by default. Change Num to:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
Also
MyFile.write(Num + "\n")
should read:
MyFile.write(str(Num) + "\n")
And just for the record, you can replace:
loop = 0
while (loop == 0):
with:
while True:
Cast int() on your input to make Num a workable integer. This has to be done because in Python 3, input always returns a string:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
With your code in it's current state, you are trying to construct a range from a string, which will not work at all as range() requires an integer.
EDIT:
Now you must replace:
myFile.write(Num+"/n")
with:
myFile.write(str(Num)+"/n")
Num is an integer at this point, so you must explicitly make a string to concatenate it with a newline character.
I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)