your program produce no output [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to the field. simple program, all I need to do is to find the smallest number.
number1 = input ('')
number2= input('')
number3 = input('')
number1 = input ('')
number2= input('')
number3 = input('')
if (number1<number2) and (number1<number3):
smallest=number1
elif (number2<number1) and (number2 < number3):
smallest=number2
else:
smallest=number3
print(smallest)

This occurs because input() returns a string:
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Because of this, all checks amongst the input values won't be between integers, as you want, but strings, leading to comparisons being based upon lexicographical ordering rather than value. This can be solved by converting the inputs to integers:
number1 = int(input(''))
number2 = int(input(''))
number3 = int(input(''))
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print(smallest)

simply use min() and max()
n1,n2,n3 = 1,2,3
print("min:", min(n1,n2,n3) )
print("max:", max(n1,n2,n3))
output:
> min: 1
> max: 3

When you enter "7", "15", and "3", your program compares those three values as strings, which means that it will find the one that is "smallest" alphabetically -- the first character is compared first, which makes "15" come first in the ordering (then "3", then "7").
To fix this, you need to convert the values to ints:
number1 = int(input())
You may be getting blank strings ("") in some cases because you copied and pasted the input lines, which means you're getting prompted six times and only the last three times count.
Overall the fixed version of your code would look like:
number1 = int(input())
number2 = int(input())
number3 = int(input())
if number1 < number2 and number1 < number3:
smallest = number1
elif number2 < number3:
smallest = number2
else:
smallest = number3
print(smallest)
Note that you don't need to pass an empty string to input() (it defaults to an empty string), and you don't need the parentheses around your comparison operations (because < already takes precedence over and).
A shortened version of this code that uses min and a loop would be:
print(min(int(input()) for _ in range(3)))
In this line of code, the expression int(input()) for _ in range(3) generates three inputs (one per number in range(3)), and the min function finds the minimum value from that generator. The nice thing about using a loop like this is that you can easily make it work for any number of inputs without having to write a bunch more if ... < ... checks!

When you use input(''), it takes the number from terminal (at the running time), so your code is OK, just to understand how it works, run your modified code below, some added strings can help you find your problem better.
number1 = input('Please insert the first number ?')
number2 = input('Please insert the second number ?')
number3 = input('Please insert the third number ?')
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print("result is : ", smallest)

Related

Why i am unable to use (or) operator on the code given below in python 3.7 [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
try:
x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
y = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
I know I am wrong, I was just wondering why I am unable to use it. As I am not getting any errors. When I try to put float value inside the input it returns me to my second case, which is Error, Invalid Input. I am using (or) operator so that I can validate integer and float values in one place. (or) the operator should execute the code when one of the conditions is true right? But why cannot we use Or operator with an integer? The code will work if you remove int from the code.
While you can use the or operator to select the the first truthy value between to values (or the latter, if the first one is falsy), it doesn't work in this case because trying to convert into int a string which represents a float value doesn't return a falsy value, it raises an Exception, which is why you go into your except clause
A logically sound way to write your code would be
x = input("Enter Your Number first = ")
try:
num = int(x)
except:
num = float(x)
Not the best way to do it, but it works
Another example:
x = 10/0 or 3 #ZeroDivisionError
x = 0/10 or 3 # x is 3 because 0 is a falsy value
Generally, we use or case to check some conditions. For example if x<3 or x>5: This if block works of both cases. However, in your situation you are trying to get some input from user and using x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = ")). So, when I enter a value it gets number as string and when you write int(input()) it convert it to integer and assign to x. So OR is not logically suitable for here. What will computer work it this situation? What you want to achieve? If you want take argument as float just write float(input()) because when you enter integer it can be taken as float also.
try:
x = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
y = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
operators = input("Choose operations (*, -, +, /)")
if operators == "*":
print(float(x*y)) or print(int(x*y))
elif operators == "-":
print(float(x-y)) or print(int(x-y))
elif operators == "+":
print(float(x+y)) or print(int(x+y))
elif operators == "/":
print(float(x/y)) or print(int(x/y))
well, i just figured it out,

Output smiley faces based on number input [duplicate]

This question already has answers here:
How to print something a specific number of times based on user input?
(3 answers)
Closed 1 year ago.
The code is supposed to print :) based on the number inputted (an integer 1 to 10). With any positive integer, the code is supposed to print that many smiley faces (ex. if 5 is entered, 5 smiley faces should be printed).
It's required that the code should use += to add onto the end of a string and should also decrement to count down and use a loop.
x = input("enter number 1 to 10: ")
for i in len(x):
print(":) " * x)
I don't think you can multiply int values and str values, and I can't find another way to do this.
First things first, input() function returns a string. You want x to be an integer, use the int() function:
x = int(input("enter number 1 to 10: "))
Second You can either use a for loop or the multiplication operator to print n number of smileys.
# Using for loop to print n smileys :
x = int(input("enter number 1 to 10: "))
for i in range(x):
print(":) ",end="")
# Using multiplication operator :
x = int(input("enter number 1 to 10: "))
print(":) "*x)
# x should be an integer
x = int(input("enter number 1 to 10: "))
# define "s" as an empty string
s = ''
# increment ":)" to "s" x times
for _ in range(x):
s += ':)'
print(s)
You're almost there! In fact, you can multiply string and integer values. This code does what you described:
print(':) '*int(input("Enter number 1 to 10: ")))
If you really want to use a for loop and +=, you could also do this
x, s = input("enter number 1 to 10: "), ''
for i in range(x):
s += ':) '
print(s)
Answer: How to print a string x times based on user input
Credits to: NoobCoder33333
times = input('Enter number from 1 to 10: ')
word = ":-)"
print('\n'.join([word] * int(times)))

How to break out of continue statement after certain amount of tries?

Apologies if the question to this is worded a bit poorly, but I can't seem to find help on this exercise anywhere. I am writing a basic Python script which sums two numbers together, but if both numbers inputted are the same the sum will not be calculated.
while True:
print('Please enter a number ')
num1 = input()
print('Please enter a second number ')
num2 = input()
if num1 == num2:
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
If both numbers are equal I want the script to loop back once more and if the numbers inputted are equal again I want the program to end. With the code I have provided the issue I am having is that when I enter two equal numbers it keeps constantly looping until I enter two different numbers.
You would likely want to have a variable keeping track of the number of times that the numbers were matching. Then do something if that counter (keeping track of the matching) is over a certain threshold. Try something like
matches = 0
while True:
num1 = input('Please enter a number: ')
num2 = input('Please enter a second number: ')
if num1 == num2 and matches < 1:
matches += 1
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
You can add give input code again inside first if statement or use some other dummy variable for loop so that you can break the loop, for e.g. use while j == 0 and increase it j += 1when you are inside the first if statement
continue skips the execution of everything else in the loop. I don't see it much useful in your example. If you want to print the sum then just remove it.
How continue works can be demonstrated by this sample (taken from python docs)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Result
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

How to print variables depending on an operator in python?

I am trying to code a simple calculator but I am having a problem. I can't seem to add, subtract, multiply, or divide two variables and print them. I am trying to code so the user can input the numbers along with the operator. Any ideas?
Thanks,
SanguineL
number1 = raw_input ("What is the first number?")
operator = raw_input ("What is the operator?")
number2 = raw_input ("What is the second number?")
elif operator == +
answer = number1 + number2
elif operator == -
answer = number1 - number2
elif operator == *
answer = number1 * number2
elif operator == /
answer = number1 / number2
print answer
You need to distinguish the string you get from raw_input from the function an operator represents.
if operator == "+":
answer = number1 + number2
elif ...
The operator module lets you build a dictionary that abstracts away the lookup process:
import operator
number1 = raw_input ("What is the first number?")
op = raw_input ("What is the operator?")
number2 = raw_input ("What is the second number?")
funcs = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}
try:
f = funcs[op]
except KeyError:
raise ValueError("Undefined operator %s" % (op,))
answer = f(number1, number2)
So there's a couple issues with your code, the first issue is that raw_input will always assume the input is a string and so your number1, operator, and number2 objects will be strings (and I assume you only want the operator variable to be a string). If you want to convert your numbers to floats, then you need to write something like number1 = float(raw_input ("What is the first number?"))
The second issue is that you need to start an if block with an if statement not an elif statement. elif statements come only after the if statement since it stands for "else if" - i.e. in the form if something else if something.
The third issue is that you didn't put quotes around your operators in your conditional statements. Python will not automatically assume they are strings. Python will assume they are variables which you haven't declared yet. You should have a statement like elif operator == '-' in order to make the comparison valid.
The fourth and last issue (that I see) is that since you are using raw_input it appears you are using python 2. Python 2 has a weird behavior when using the division operator / - namely it floors the division if the inputs to it are ints or longs. That behavior can cause a lot of headaches if you are not aware of it. You should probably include a from __future__ import division line at the beginning of your code so dividing doesn't floor the answer.
Don't know what does raw_input ("What is the first number?") mean (assume that is some kind of form input or sdt_in), but lower part might be (don't forget to convert your inputs like this number1 = int(number1)):
if operator == '+'
answer = number1 + number2
elif operator == '-'
answer = number1 - number2
elif operator == '*'
answer = number1 * number2
elif operator == '/'
answer = number1 / number2
print(answer)

Python - Run for loop 3 times [duplicate]

This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 3 months ago.
So I have this assignment and I have a question about a part I don't know how to do, can you guys help me?
def main():
# Please see the comments
largest = 0
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
number3 = int(input("Please enter the third number: "))
# insert call to function find_largest after this comment.
# find_largest will take in three parameters and will return the largest of the 3 numbers
result = find_largest(number1, number2, number3)
# insert the statement to print the three numbers entered and the largest number after this comment.
print("The numbers you entered were, \n", [number1, number2, number3])
print ("The largest of the numbers you entered is", result)
def find_largest(a, b, c):
# insert parameters in the parenthesis
# Write the code for this function here.
# find_largest will take in three parameters and will return the largest of the 3 numbers
# These three numbers are passed in as parameters from the main function
# Hint: if and elif - no loop needed here
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest
main() # this is the call to main() that will make the program run
So, my question is the part:
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
I don't know what to add so the loop run 2 more times after it has found the largest number
The loop you have makes the first two iterations of the loop pointless, as each time you loop, you are reassigning new numbers to the three number variables. As a result, only the numbers entered in the last iteration of the loop are ever used for anything. I think this would make more sense:
numbers = []
for i in range(3):
input = int(input("Enter number: "))
numbers.append(input)
This will give you a list called numbers with 3 numbers in it entered by the user. Then you can do what you want with them. Having said that, you really don't need a for loop to do this. As Craig Burgler mentioned.
Alternatively(though this doesn't use range...):
number1 = 0
number2 = 0
number3 = 0
for i in (number1, number2, number3):
i = int(input("Enter number: "))
The code as written will ask for three numbers three times, overwriting the first and second set of numbers that the user enters. If the assignment is to get three numbers from the user and tell the user which is largest, then you do not need the for loop. The three input statements will do the trick.

Categories

Resources