as you can see down it's not giving the value of input to the if! why? and how i can make the value of input be stored to Variable (number)
number = input(f"Enter a Number? ")
if number == (1):
print("one")
if number == (2):
print("two or greater")
else:
print("negative number")
Enter a Number? 1
negative number
There are some issues, usually when you use input and expect a number to be submitted, you want to use int() before it to make sure the input is understood as a number (type int). Furthemore, when you want to state an "else-if" statement you should use elif. Finally, the parenthesis are not necessary in your if statement. The following should work:
number = int(input("Enter a Number? "))
if number == 1:
print("one")
elif number >= 2: #I've changed this syntax, because two or greater is written like this
print("two or greater")
else:
print("negative number")
Here is the output I'm trying:
Enter a Number? 3
two or greater
Related
I have ran into some problems while trying to combine while loop and ValueError.
Initially I wanted my program to add numbers together. When the sum of numbers has exceeded X, I would like my program to continue to else statement. At first I didn't focus on the fact that input could also be (for example) string.
number = 1
while number < 10:
add = int(raw_input("Enter a number to add: "))
number += add
print number
else:
print "Number is greater than 10"
I tried combining the first code with try/except and ValueError to accept integers as the only inputs. Second code will not continue to else statement when sum of numbers exceeds X. Could someone please explain why this is not working?
number = 1
while number < 10:
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
except ValueError:
print "Please enter a number"
else:
print "Number is greater than 10"
Thank You.
there's an extra while True: loop resulting in an infinte loop.
Remove it and your code will work fine.
Another example where while(condition) (with condition not True) leads to mistakes: you have to ensure that the loop will be entered once, sometimes by initalizing your condition artificially. I would write that instead
number = 1
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
if number>10:
break
except ValueError:
print "Please enter a number"
print "Number is greater than 10"
I am a beginner in Python and I was trying to write a small program that asks the user to enter an integer that is greater than 0. The function should keep on asking the user for the number until it is valid.
I tried something like below, however I am getting the wrong results. Can you please help me understand my error?
num = input('please enter a number: ' )
n = int(num)
while n < 0:
num = input('please enter a number: ' )
if n >= 0:
print('Valid number')
else:
print('Invalid number')
Is it possible to start the code without an input function? (like to start with num = int())
Thank You for Your Time
There's an error with the logic behind your code.
You firstly ask the user for a number and if he inputs a number which is greater than or equal to 0, the while-loop will never start (in your script: while n < 0:), which, I assume is fine, because the goal of your program is, as you said, to make "the user to enter an integer that is greater than 0".
If the user inputs a number that is smaller than or equal to 0, the while-loop will start, but will never break because inside of it, the value of variable n never changes, only does the value of num.
This is an appropriate script considering that you want to make the user input a number greater than 0, and that you want to give feedback regarding their input.
n = None
while n <= 0:
n = int(input('please enter a number: '))
if n <= 0:
print('Invalid number')
else:
pass # the loop will break at this point
# because n <= 0 is False
print('Valid number')
The code has the user stuck in a loop until they write a number that's greater than 0.
Another solution would be to, inside the loop, check whether int(num) is greater than 0 and if it is, print 'Valid number' and do break to stop the loop; if it's not, print 'Invalid number' (though then the loop doesn't need to be defined by while n < 0:; rather by while True:.
Also, what do you mean by this:
Is it possible to start the code without an input function? (like to start with num = int())
Please clarify this part.
If your problem is the code not terminating, writing Invalid number all the time it's because you are not updating the value of n. You assigned it just once. The solution to your problem is as follows:
n = -1
while n < 0:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
By the way you get rid of starting the code without an input function.
Edit:
As you just said - you want to keep the input reading despite passing an negative integer into the command line. This should help you accomplish this:
while True:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
This loop will go forever until you exit the program lets say with ctrl + C. while True: is as you see an forever ongoing loop, because the True argument will never be false.
I am just starting out programming and reading thru C++ Programming Principles and Practice. I am currently doing the Chapter 3 exercises and do not understand why this code I wrote works. Please help explain.
#include "std_lib_facilities.h"
int main() {
cout<<"Hello, User\n""Please enter a number (Followed by the 'Enter' key):";
int number=0;
cin>> number;
if (number%2) {
cout<<"Your number is an odd number!";
} else {
cout<<"Your number is an even number\n";
}
return 0;
}
When number is odd, number%2 is 1.
if (number%2) {
is equivalent to
if (1) {
Hence, you get the output from the line
cout<<"Your number is an odd number!";
When number is even, number%2 is 0.
if (number%2) {
is equivalent to
if (0) {
Hence, you get the output from the line
cout<<"Your number is an even number\n";
The modulus operator simply determines the remainder of the corresponding division problem. For instance, 2 % 2 returns 0 as 2 / 2 is 1 with a remainder of 0.
In your code, any even number entered will return a 0 as all even numbers are, by definition, divisible by 2 (meaning <any even number> % 2 == 0)
Likewise, any odd number entered will return 1 (for instance, 7 % 2 == 1 as 7 / 2 has a remainder of 1).
In c++, like in many programming languages, numeral values can be treated as booleans such that 0 relates to false while other numbers (depending on the language) relate to true (1 is, as far as I know, universally true no matter the programming language).
In other words, an odd number input would evaluate number % 2 to 1, meaning true. So if (number % 2), we know that the input number is odd. Otherwise, number % 2 must be false, meaning 0, which means that the input number is even.
"if" statements works on boolean values. Let's remember that boolean values are represented by "false" and "true", but in reality, it's all about the binary set of Z2 containing {0, 1}. "false" represents "0" and "true" represents "1" (or some people in electronics interpret them as "off/on")
So, yeah, behind the curtains, "if" statements are looking for 0 or 1. The modulus operator returns the rest of a / b. When you input any number and divide it by 2, you are gonna get a rest of 0 or 1 being it pair or an odd number.
So that's why it works, you will always get a result of 0 or 1 which are false and true by doing that operation that way.
think of modulus in terms of this:
while (integer A is bigger than integer B,)
A = A - B;
return A
for example, 9%2 -> 9-2=7-2=5-2=3-2=1
9%2=1;
the statement if (number%2) is what is called a boolean comparison (true false). Another way to write this statement identically is if(number%2 != 0) or if(number%2 != false) since false and zero are equivocal. You're taking the return value of the modulus operator function (a template object we will assume is an integer) and inserting it into an if statement that executes if the input does not equal zero. If statements execute if the input is -5,9999999,1-- anything but zero. So, if (2) would be true. if(-5) would also be true. if(0) would be false. if(5%2) would be 1 = true. if(4%2) would be if(0) = false. If it is true, the code in the body of the if statement is executed.
The Question:
5.Now write the function is_odd(n) that returns True when n is odd and False otherwise.
Finally, modify it so that it uses a call to is_even to determine if its argument is an odd integer.
I had to write a function for is_even(n) that returns True when n even and False otherwise. Here is my code:
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n):
print "This is an even integer."
else:
print "This is an odd integer."
return n % 2 != 0
My Question:
I am a total beginner and find programming very hard but I love it for some reason, but why does this not work? I defined the function is_even(n) and is_odd(n), put is_even(n) into the is_odd(n) function, wrote and if/else else statement making if the function is_even is equal to true it should print out it is an even integer... When I put in is_odd(3); it prints out "This is an even integer" and returns True even though it should print out "This is an odd integer."
Update:
I changed my code to this and works fine.
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n) == False:
print "This is an odd integer."
return n % 2 != 0
You're encountering IndentationError because you're being inconsistent with your indentation. As soon as you indent in Python, you have created a new block. You do this after block-introducing keywords, like if, while, for, etc. Python doesn't care how many spaces or tabs or whatever you use before your first block, but once you make the choice the first time, you must keep using the same number. I've added a line to your posted code to show you:
See how the r in return aligns with the f in if? It needs to align with the i. In this example your if is not at the proper indentation level relative to the first block, producing the error in question.
I am trying to write a program that converts a percentage received in a class into a GPA format then eventually find the overall GPA. I want it to first prompt the user to input the amount of classes, then input the percentages. I am running into some trouble getting the program to convert the percentage into the GPA format (90 or greater equals 4, 80 to 89 equals 3, ect...). This is what I have so far
class_number = int(raw_input("How many classes do you have? "))
total_grade = list((raw_input("Enter Percentage: ")) for i in range(class_number))
a = total_grade
def alter(x):
if x >= 90:
return 4
elif x >= 80:
return 3
a = map(alter,a)
print a
The problem is that this only seems to output 4s no matter the original percentage.
Any help would be greatly appreciated! Thanks!
That's because x is actually a string. I think a string will always be greater than a number. You need to convert each item in total_grade to an int:
total_grade = list(int(raw_input("Enter Percentage: ")) for i in range(class_number))
Also, you can just use a list comprehension:
total_grade = [int(raw_input("Enter Percentage: ")) for i in range(class_number)]