Python If Statements - Display numeric Results - python

I am writing a python code that returns me the larger of two inputs.
def bigger_num(a, b):
if a < b:
print ("First number is smaller than the second number.")
elif a > b:
print ("First number is greater than the second number.")
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
print(bigger_num(a, b))
Result:
Enter first number: 19
Enter second number : 9
First number is greater than the second number.
None
How do I display the numeric result (a/b) in the print?
Ideal solution example: First number, 19 is greater than the second number
Also, is there a way to remove none from the print result?

You can use the format() method or simply concatenate the number to display it. To remove the None, just call the function without the wrapping it with a print() because you print the output inside the function
def bigger_num(a, b):
if a < b:
print ("First number, {0} is smaller than the second number.".format(a))
elif a > b:
print ("First number, {0} is greater than the second number.".format(a))
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
bigger_num(a, b)

Related

How do I calculate the sum of the individual digits of an integer and also print the original integer at the end?

I wish to create a Function in Python to calculate the sum of the individual digits of a given number
passed to it as a parameter.
My code is as follows:
number = int(input("Enter a number: "))
sum = 0
while(number > 0):
remainder = number % 10
sum = sum + remainder
number = number //10
print("The sum of the digits of the number ",number," is: ", sum)
This code works up until the last print command where I need to print the original number + the statement + the sum. The problem is that the original number changes to 0 every time (the sum is correct).
How do I calculate this but also show the original number in the print command?
Keep another variable to store the original number.
number = int(input("Enter a number: "))
original = number
# rest of the code here
Another approach to solve it:
You don't have to parse the number into int, treat it as a str as returned from input() function. Then iterate each character (digit) and add them.
number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)
You can do it completely without a conversion to int:
ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)
It will compute garbage, it someone enters not a number
number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)
As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.

Greatest of 3 numbers code not working for specific numbers

I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
if (a > b) and (a > c):
lnum = a
elif (b > a) and (b > c):
lnum = b
else:
lnum = c
print("The largest number is", lnum)
Can anyone help me to understand why the output is showing 20 as greatest instead of 100?
Your variables are strings, you must convert them to ints like this:
a = int(input('Enter 1st value'))
a = input("Enter 1st value") stores string into a you should convert it into integer by using int() method.
a = int(input("Enter 1st value")) or try a= input("Enter 1st value") then a=int(a).
you have to convert your inputs to int:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
print("The largest number is", max(map(int, (a, b, c))))
You could do this easier with max(list) when you store your values in a list. Example:
values = []
values.append(int(input('Enter 1st value ')))
values.append(int(input('Enter 2st value ')))
values.append(int(input('Enter 3st value ')))
lnum = max(values)
print("The largest number is", lnum)
Your inputs are strings and are sorted by comparing the characters left to right.
Comparing "100" against "20" first compares "1" and "2". "1" is smaller so your code picks "20" as the larger value.
As others have mentioned if you convert the input to integer using int(input('Enter 1st value ') then it will work as you intended and there is a max() function you can use.
Note: There still is another mistake in your code:
Enter 1st value20
Enter 2nd value20
Enter 3rd value10
('The largest number is', 10)
The check for (b > a) is wrong and causes you to output c if a == b.

how to add a string to the same string multiple number of times

Given that there are two inputs- a String and a number.
I wish to append the string with the same .
Eg:
Input:
a 10
Output:
add a to the String 'a' such that it appears 10 times.
aaaaaaaaaa
another example:
Input:
ab 5
OUTPUT:
ababababab
You can have a function like below:
In [1389]: def myfunc(string, number):
...: s = string * number
...: return s
In [1391]: string = input("Enter string:")
In [1392]: number = input("Enter number:")
In [1396]: myfunc(string, number)
Out[1396]: 'aaaaaaaaaa'
Python multiplies the string to number if given like 'a' * 2.
It will Help You
num = int(input()) #for how many times we want to print string
string = input() # String which we want to print
for i in range(num): # loop will run for num (User Input) times which come from input
print(string)
if you want to print in a single line
print(string , end = " ")
Think Twice , Code Once
Simply You can do with using * operator
n = int(input("Enter a number"))
string = input("Enter a String")
print(string*n) # it prints your string n times
With Function
def num_multi(n , s):
return n*s
number = int(input("Enter a number"))
string = input("Enter a String")
print(number*string)
Python 3.x:
def printstring(string,number):
print(string * number)
return
number1 = int(input("Enter here: "))
string1= input("enter a number")
print(printstring(string1,number1))

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))

Python function using appends with lists not very efficient

Trying to write a function which takes input of 4 digit numbers and compares them, output of Ys and Ns to try and check if they are the same. EG 1234 and 1235 would output YYYN. At the minute it's very inefficient to keep using all these append commands. How could I simplify that?
def func():
results=[]
firstn= str(input("Please enter a 4 digit number: "))
secondn= str(input("Please enter a 4 digit number: "))
listone= list(firstn)
listtwo= list(secondn)
if listone[0]==listtwo[0]:
results.append("Y")
else:
results.append("N")
if listone[1]==listtwo[1]:
results.append("Y")
else:
results.append("N")
if listone[2]==listtwo[2]:
results.append("Y")
else:
results.append("N")
if listone[3]==listtwo[3]:
results.append("Y")
else:
results.append("N")
print(results)
Furthermore, how can I validate this to just 4 digits for length and type IE. Nothing more or less than a length of four / only numerical input? I have been researching into the len function but don't know how I can apply this to validate the input itself?
For the validation, you can write a function that will ask repeatedly for a number until it gets one that has len 4 and is all digits (using the isdigit() string method).
The actual comparison can be done in one line using a list comprehension.
def get_number(digits):
while True:
a = input('Please enter a {} digit number: '.format(digits))
if len(a) == digits and a.isdigit():
return a
print('That was not a {} digit number. Please try again.'.format(digits))
def compare_numbers(a, b):
return ['Y' if digit_a == digit_b else 'N' for digit_a, digit_b in zip(a, b)]
first = get_number(4)
second = get_number(4)
print(compare_numbers(first, second))
I think this should work.
def compare(a,b):
a,b = str(a),str(b)
truthvalue = {True:"Y",False:"N"}
return "".join([truthvalue[a[idx]==b[idx]] for idx,digit in enumerate(a)])
print(compare(311,321)) #Returns YNY
print(compare(321312,725322)) #Returns NYNYNY
def two_fourDigits():
results = []
firstn = input("Please enter the first 4 digit number: ")
while firstn.isnumeric() == False and len(firstn) != 4:
firstn= input("Please enter the second 4 digit number: ")
secondn = input("Please enter a 4 digit number: ")
while secondn.isnumeric() == False and len(secondn) != 4:
secondn= input("Please enter a 4 digit number: ")
for i in range(0, len(firstn)):
if firstn[i] == secondn[i]:
results.append("Y")
else:
results.append("N")
print(results)
You don't need to convert the input to a string, the input() function automatically takes in the values as a string.
Second, I added in input validation for firstn and secondn to check that they were numeric, and to check if they are the correct length (4). Also, there is no need to change the input to a list, because you can search through the strings.
I tried to do your function like this. Basically, the function uses the length of the first string to iterate through all the values of each list, and return Y if they are the same and N if they are not.
Because you don't make it a global variable which can be used from out of the function. Here is an example:
my_list = []
def my_func():
global my_list
my_list.append(0)
return "Something..."
my_list.append(1)
print my_list

Categories

Resources