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

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":

Related

I'm having problems with how to print multiple outputs from user input

Im new to programming and was set a task where I had to ask the user for there name and a number. I had to print the name where each individual letter is printed on a separate line. The second part is that I had to ask the user to enter a number and that it would repeat the same output by the number given by the user
My code:
name = input("Please enter your name:")
num = input("Please enter a number:")
for index,letter in enumerate(name,1):
for num in range(0,9):
print(letter)
My desired result was this:
Please enter your name: Taki
Please enter a number: 3
T
a
k
i
T
a
k
i
T
a
k
i
the result was this:
Please enter your name: Taki
Please enter a number:3
T
T
T
T
T
T
T
T
T
a
a
a
a
a
a
a
a
a
k
k
k
k
k
k
k
k
k
i
i
i
i
i
i
i
i
i
Plz help
A brute force approach is
name = input('Enter a name: ')
num = int(input('Enter a number: '))
for i in range(num):
for j in name:
print(j)
Here, name is a string which is iterated over each character in the j-loop.
In your code, the num loop from 0 to 9 is wrong. You need to print for num times, not 9 times (0-9). So the range has to be i in range(num). This is why each character was being printed 9 times in your output.
Also, remember to type cast num variable to int while taking the input as Python treats all inputs as string by default.
You have your loops in the wrong order. And your range should be to num not 9
name = input("Please enter your name:")
num = input("Please enter a number:")
for i in range(num):
for letter in name:
print(letter)
name = input("Please enter your name:")
num = input("Please enter a number:")
result = [char for char in name] * int(num)
print('\n'.join(result))
Another way to get it done, using itertools:
import itertools
count = 0
name = input("Please enter your name:")
num = int(input("Please enter a number:"))
for i in itertools.cycle(name):
if count > num * len(name)-1:
break
else:
print(i, end = "\n")
count += 1

While loop 2 int values [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am trying to write a function to get 2 int values from a user until their sum is 21, Simple!!
The aim is to keep prompting the user to pass 2 int values until the condition is met. I am not sure where the code breaks as it stops when either conditions is met, both if true or false.
def check_for_21(n1,n2):
result = 0
while True:
while result != 21:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
except:
if n1+n2 == 21:
print("You got it! ")
else:
break
break
This is what you are looking for you had multiple logical errors! However, the idea was there but wrongly formatted. In this program, it runs continuously until you enter two numbers and their sum is 21
def check_for_21():
while True:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
check_for_21()
Try this. This will meet your requirment.
a = 5
while (a<6):
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 == 21:
print("You got it ")
break
else:
print("You did not get to 21! ")
Take the input, check for result, if you get 21, break the loop.
def check_for_21(n1,n2):
result = 0
while True:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
except:
pass
Below is the test result of the code that worked for me:

sum of two numbers using raw_input in python

I want to perform this:
Read two integers from STDIN and print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.
Can someone help me on this?
Start slow and break it down
# Get your data from the user, use input
num_one = input("Please enter the first number: ")
num_two = input("Please enter the second number: ")
# Create the sum, diff, and product, casting as integer
sum = int(num_one) + int(num_two)
diff = int(num_one) - int(num_two)
product = int(num_one) * int(num_two)
# Print each output casting as a string since we can't concatenate a string to an integer
print("The sum is: "+str(sum))
print("The difference is: "+str(diff))
print("The product is: "+str(product))
Now you should also do some error checking here incase the user doesn't enter anything:
# Get your data from the user, use input
num_one = input("Please enter the first number: ")
num_two = input("Please enter the second number: ")
if(num_one == "" or num_two == ""):
print("You did not enter enter two numbers. Exiting...")
exit
else:
# Create the sum, diff, and product, casting as integer
sum = int(num_one) + int(num_two)
diff = int(num_one) - int(num_two)
product = int(num_one) * int(num_two)
# Print each output casting as a string since we can't concatenate a
string to an integer
print("The sum is: "+str(sum))
print("The difference is: "+str(diff))
print("The product is: "+str(product))
Python 2.7
raw_input to read the input, int to convert string to integer, print to print the output
a = int(raw_input("numebr 1: "))
b = int(raw_input("numebr 2: "))
print a + b
print a - b
print a * b
Python 3.7
input to read the input, int to convert string to integer, print to print the output
a = int(input("numebr 1: "))
b = int(input("numebr 2: "))
print (a + b)
print (a - b)
print (a * b)
a = int(input())
b = int(input())
from operator import add, sub, mul
operators = [add, sub, mul]
for operator in operators:
print(operator(a, b))

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 elif statement not working

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.

Categories

Resources