Python elif statement not working - python

I don't understand why my following piece of code does not work:
running = True
name = input("Whats your name?: ")
print ("Hi", name, "Which Program Would You Like to Use")
print ("1. Upper to Lower Case converter")
print ("2. Lower to Upper Case converter")
print ("3. Character Count")
x = input("Enter the Number: ")
if x==1:
print ("You have selected the Upper to Lower Case converter")
y = input("Enter the text you would like converted: ")
print (y.lower())
elif x==2:
pass print ("You have selected the Lower to Upper Case converter")
z = input("Enter the text you would like converted: ")
print (z.lower()
running = False

you need here:
x = int(input("Enter the Number: "))
input takes as string
if x==1: you were comparing string with integer

You probably are missing a closing bracket here: print (z.lower()
In this statement if x==1:, you are comparing x, which is a string, with an int, and, as you already might have understood, you cannot do it.
One solution for this problem is to convert x to and int directly when you get the input from the user:
x = int(input("Enter a number: "))
Or comparing the x with a string number:
if x== "1":
# do stuff
It depends of course in what you want to do.

Related

How do I stop my python code from printing none after it prints the string? [duplicate]

This question already has answers here:
Why is this printing 'None' in the output? [duplicate]
(2 answers)
Closed 1 year ago.
str = input("Please enter y to start the program: ")
while str == 'y':
def printNTimes(s, n):
for i in range(n):
print(s)
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Output:
Please enter y to start the program: y
Enter a string: Hi
Enter a positive number: 3
Hi
Hi
Hi
None
Please enter y if you want to continue:
You don't need print(allTogether), or the variable itself, because when you print it, you get an extra None (because the function returns None i.e, it does not return anything).
Also, put the function outside the while loop so that it is easier to read.
def printNTimes(s, n):
for i in range(n):
print(s)
str = input("Please enter y to start the program: ")
while str == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
printNTimes(phrase, number)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Just call the function. You could use return and then print the function, but this might be easier.
The problem is the function printNtime is actually being used as a subroutine, meaning it doesn't RETURN any values.
I am not sure what you want as a final output so here's two solution.
IF USED AS SUBROUTINE: just remove the print(allTogether)
IF USED AS A FUNCTION: you need to create a string variable in the function and return it.
def printNTimes(s, n):
mystring = ""
for i in range(n):
mystring = mystring + s + "\n"
return mystring
The issue you're seeing is because your routine, printNTimes(), returns a None value. You say:
allTogether = printNTimes(phrase, number)
print(allTogether)
allTogether is set to None because printNTimes does not return a value. When you call print(allTogether), that's what is printing the None.
It sounds like you intended your printNTimes() routine to assemble one big string of all the output and return it, which you would then print out via the print(allTogether) call. But your printNTimes() routine is calling the print() method and outputing the text then. So, you need to rewrite your printNTimes() method. Also, note that defining that function inside the loop is not necessary. Once is sufficient. So something like this should suffice:
def printNTimes(s, n):
s_out = ""
for i in range(n):
s_out += s + '\n'
return s_out
str_ = input("Please enter y to start the program: ")
while str_ == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str_ = input("Please enter y if you want to continue: ")
print("DONE")
Also note that I renamed your str variable to str_. str is a Python type, a reserved word that should not be reused.

My python code wont go through the elif statements [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
Hello I'm making a random program and right now I have it asking a user if they want to add, subtract, multiply, or divide and that's going well but the if statement wont go through all the options. Whatever is in the first of the nested if statement is what the function preforms.
Here's the code:
#Test2.py
import random
x = input("Hello what is the issue? ").capitalize()
if x == "Can't decide what to do":
y = input("How many choices are there? (please type as numbers in a row) ")
yl = list(y)
print("Number ", random.choice(yl) ," is your choice.")
elif x == "I need help with math":
m = input("Okay, are you adding, subtracting, multiplying, dividing, or something else? ").capitalize()
if m == "Adding" or "Add" or "Addition":
q = input("Okay what is the first number? ")
w = input("What is the second number? ")
r = input("Enter the third number: (if there isnt another number please enter 0)")
t = input("Enter the fourth number: (if there isnt another number please enter 0) ")
u = input("Enter the fifth number: (if there isnt another number please enter 0) ")
m1 = int(q)+int(w)+int(r)+int(t)+int(u)
print("The answer is: ", m1)
elif m == "Subtracting" or "Subtract" or "Subtraction":
i = input("Okay what is the first number? ")
o = input("What is the second number? ")
p = input("Enter the third number: (if there isnt another number please enter 0) ")
a = input("Enter the fourth number: (if there isnt another number please enter 0) ")
s = input("Enter the fifth number: (if there isnt another number please enter 0) ")
m2 = float(i) - float(o) - float(p) - float(a) - float(s)
print("The answer is: ", m2)
elif m == "Multiplying" or "Multiply" or "Multiplication":
d = input("Okay what is the first number? ")
f = input("What is the second number? ")
g = input("Enter the third number: (if there isnt another number please enter 1) ")
h = input("Enter the fourth number: (if there isnt another number please enter 1) ")
j = input("Enter the fifth number: (if there isnt another number please enter 1) ")
m3 = float(d) * float(f) * float(g) * float(h) * float(j)
print("The answer is: ", m3)
elif m == "Dividing" or "Divide" or "Division":
k = input("Okay what is the first number? ")
l = input("What is the second number? ")
z = input("Enter the third number: (if there isnt another number please enter 1) ")
x = input("Enter the fourth number: (if there isnt another number please enter 1) ")
c = input("Enter the fifth number: (if there isnt another number please enter 1) ")
m4 = float(k)%float(l)%float(z)%float(x)%float(c)
print("The answer is: ", m4)
else:
quit
Thank you for any and all help, have a great day!
You need to put "m ==" after every "or". Python doesn't know what to compare to, if you don't give it the variable to compare to after every "or" or "and" logic operator.
For example:
elif m == "Subtracting" or m == "Subtract" or m == "Subtraction":

creating a code that use .isdigit

I'm new to python. I was creating a code that use .isdigit. It goes like this:
a = int(input("Enter 1st number: "))
if 'a'.isdigit():
b = int(input("Enter 2nd number: "))
else:
print "Your input is invalid."
But when I enter an alphabet, it doesn't come out the "Your input is invalid.
And if I entered a digit, it doesn't show the b, 'Enter 2nd number'.
Is there anyway anyone out there can help me see what's the issue with my code.
That will be a great help. Thanks.
You are assigning the input to a variable a, but when you try to query it with isdigit() you're actually querying a string 'a', not the variable you created.
Also, you are forcing a conversion to an int before you've even checked if it's an int. If you need to convert it to an int, you should do that after you run the .isdigit() check:
a = raw_input("Enter 1st number: ")
if a.isdigit():
a = int(a)
b = int(raw_input("Enter 2nd number: "))
else:
print("Your input is invalid.")
Try to convert your a variable to string type, like this:
a = int(input("Enter 1st number: "))
if str(a).isdigit():
b = int(input("Enter 2nd number: "))
else:
print("Your input is invalid.")

How do i have my python program restart to a certain line?

print ("Enter the object you are tyring to find.")
print ("1 = Radius")
print ("2 = Arch Length")
print ("3 = Degree")
print ("4 = Area")
x = int(input("(1,2,3,4):"))
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
if x == 2:
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
I am making a basic math program but i want it to repeat infinitely. This is not the complete code but i want to do the same thing for the rest of the "if" statements. i want it to end after each function is completed and repeat back to the first line. thanks!
Put a
while True:
at the spot you want to restart from; indent all following lines four spaces each.
At every point in which you want to restart from just after the while, add the statement:
continue
properly indented also, of course.
If you also want to offer the user a chance to end the program cleanly (e.g with yet another choice besides the 4 you're now offering), then at that spot have a conditional statement (again properly indented):
if whateverexitcondition:
break
You will need to add a way to let the user quit and break the loop but a while True will loop as long as you want.
while True:
# let user decide if they want to continue or quit
x = input("Pick a number from (1,2,3,4) or enter 'q' to quit:")
if x == "q":
print("Goodbye")
break
x = int(x)
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
elif x == 2: # use elif, x cannot be 1 and 2
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
elif x == 3:
.....
elif x == 4:
.....
If you are going to use a loop you can also verify that the user inputs only valid input using a try/except:
while True:
try:
x = int(input("(1,2,3,4):"))
except ValueError:
print("not a number")
continue

Python 2.7 getting user input and manipulating as string without quotations

I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.

Categories

Resources