Python Variable Understanding - python

I was writing this code and I can't seem to get it to work correctly.
There's no Syntax errors so I'm clear on that.
It just is not giving me the correct output I want.
Here's the code :
This is the out put I get when x = 5 :
Big!
Done!
This is the output I get when x = 1
Small!
Done!
This is what I get when x = anything other than 1 or 5
Done!
What I want it to do is when x = anything between 1-5 to output Small! then Done!
Or if it is between 5-infinity to output Big! then Done! but if the number is not 1 or 5 it just outputs Done!
What changes should I do to my code?

As pointed by a user in the previous answer, what you need to implement is an if-else ladder and use logical operator for the case when your output is specifically either 1 OR 5
x=6 # You can replace this by a user defined input using input()
if x==5 or x==1:
print("Done!")
elif x<5:
print("Small!")
print("Done!")
elif x>5:
print("Big!")
print("Done!")
else:
print("Enter a valid number!")
I checked with various test cases like 1, 5 , numbers between 1 and 5 and numbers greater than 5 and all seem to work fine.
Here's a sample output

x = 5
if x in range(6):
print('Small')
elif x >=6 :
print('Big')
print('Done')
Try this. The range function checks if the number is in between 0 and 6 i.e 0 to 5. Anything lesser than 0 will be ignored
The problem with your code is that you're just checking two conditions if x== 5 and if x == 1. The print statements will be executed only if this condition is satisfied.
Cheers

You can create a if-else ladder to achieve this
def determine_size(inp):
if inp == 1 or inp == 5:
print("Done")
elif 0 <= inp < 5:
print("Small")
print("Done")
elif inp > 6:
print("Big")
print("Done")
else:
print("Negative Input")
>>> determine_size(0)
Small
Done
>>> determine_size(100)
Big
Done
>>> determine_size(60)
Big
Done
>>>
>>> determine_size(3)
Small
Done
>>> determine_size(4)
Small
Done
You can also play around with the if-else statements per your objectives

x = 40
# at first check if x is greater than 1 and less than 5.
# Only then it is between 1 and 5.
if x >=1 and x<=5:
print('Small!')
# Now chek if x is greater than 5
elif x>5:
print('Big!')
print('Done!')

if you meant the above mentioned scenario mentioned in comment
try:
x=int(input("enter a number: "))
if x >=0 or x<=5:
print("Small")
print("Done")
elif x>=6:
print("big")
print("Done")
except ValueError:
print("Done")
here the block of code is written in try block, why i have written in try block if someone enter something which is not number then program will not crash and raise a exception.
if you are not familiar with elif syntax, we can have simple construction like this :-
try:
x=int(input("enter a number: "))
if x >=0 and x<=5:
print("Small")
print("Done")
else:
print("big")
print("Done")
except ValueError:
print("Done")
Here all I have done is to change the logical operator from or to and.

Related

Keep asking for numbers and find the average when user enters -1

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)

creating a python program which ask the user for a number - even odd

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

Write a simple looping program

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.

Syntax error on the "N" on line 18

I've been working on this simple program in Python just so I can start experimenting with Python and become more knowledgeable of Python and other programming languages in general by designing them in a way in which others can use them in an efficient manner without getting caught on the parts which make this code work. I've been doing this by having a simple program calculate "Angles in a triangle" as it's a simple subject. Recently, I replaced def(): commands with if statements as it cuts down typing to a minimum and making it generally easier for others however, when I try to run this code I get a syntax error message with N becoming highlighted on line 17.
def triangle():
N = int(input("Please enter the number of angles you currently have between 1 and 3: "))
if N == 1:
a = int(input("What's one of the angles?"))
b = int(input("What's the other angle in the triangle?"))
c = a + b
f = 180 - c
print(f)
print("If you'd like to continue, please type in triangle()")
elif N == 2:
a = int(input("What's the value of angle 1?"))
b = 180 - a
c = b /2
print(c)
print("If you'd like to continue, please type in triangle()")
else N == 3:
a = 180
b = 180 / 3
print(b)
print("If you'd like to continue, please type in triangle()")
But I'm getting a syntax error returned on elif N == 3:
Any tips would be great.
else does not have a condition.. remove it to just say
else:
or make it says
elif N == 3:
You have else N == 3:. That is not how the if..elif..else structure works - the else is a catch-all branch that is entered if none of the preceding if or elif conditions are satisfied. If you want to check specifically for N == 3 and no other values, use elif N == 3. If you want a catch-all condition, simply use else:.
elif N == 3:
Either you meant elif (which is Python for else..if), or else
If you meant plain else, it doesn't take a condition.
If you want to annotate that an else implies a certain condition is met, then I use a comment:
else: # N == 3
But that's considered bad style: only do that if you're sure N cannot have any other value than 1,2,3. In your case the user could also input any number 4,5,..,9 (or indeed 10 or larger, or indeed 0 or any negative number), and that will wrongly get handled by the N==3 branch.
Whereas if your last branch if elif N == 3, with no else-clause, invalid numbers will silently fail every branch in your tree.
So for completeness and sanity-checking, you might prefer to do:
...
elif N ==3:
# Handle N == 3 case
else:
print "Invalid number!"

python while loop unexpected behavior

I'm relatively new to Python, and I don't understand the following code produces the subsequently unexpected output:
x = input("6 divided by 2 is")
while x != 3:
print("Incorrect. Please try again.")
x = input("6 divided by 2 is")
print(x)
the output of which is:
6 divided by 2 is 3
Incorrect. Please try again.
6 divided by 2 is 3
3
Incorrect. Please try again.
6 divided by 2 is
Why is the while loop still being executed even though x is equal to 3?
input() returns a string, which you are comparing to an integer. This will always return false.
You'll have to wrap input() in a call to int() for a valid comparison.
x = int(input("6 divided by 2 is"))
while x != 3:
print("Incorrect. Please try again.")
x = int(input("6 divided by 2 is"))
print(x)
Read more on int() here.
You are getting this error is because you are not parsing the input like so:
x = int(input("6 divided by 2 is"))
If you replace your inputer statement with that, it'll work.
input method gives the string. So you need to typecast to int as:
x = int(input("6 divided by 2 is"))
Here is my answer to your question
Guesses = 0
while(Guesses < 101):
try:
x = int(input("6 divided by 2 is: "))
if(x == 3):
print("Correct! 6 divide by 2 is", x)
break
else:
print("Incorrect. try again")
Guesses += 1
except ValueError:
print("That is not a number. Try again.")
Guesses += 1
else:
print("Out of guesses.")
I am assuming you wanted the user to input a number so i put your code into a while\else loop containing a try\except loop. The try\except loop ensures that if the users inputs a number, a ValueError will appear and it will inform them that what they inputted was not a number. The while\else loop ensures that the user will be inputted the question if the Guesses limit is no higher than 100. This code will ensure that if the user guesses the answer which is 3, the user will be prompted that they got the answer right and the loop will end; if the users guesses anything besides 3 (Number wise) the answer will be incorrect and the user will be prompted the question again; if the user guesses a string it will be classified as a ValueError and they will be notified that their answer wasn't a number and that the user has to try again.
Considering this was asked a long time ago, I'm assuming your probably forgot about this or you figured out the answer but if not try this and tell me if you like this answer. Thank :)
I actually tried this myself now with python 2.6, and did get an int without converting to int. For example, when I try the following:
x = input("6 divided by 2 is")
print "Your input is %s, %s" % (x, type(x))
I get the following:
6 divided by 2 is 2
Your input is 2, <type 'int'>
So is this a version issue? Or maybe an environment issue (I'm using OS X)?
What I do conclude is that it should be a good practice using previous recommendations using int().

Categories