My First Ever Python Program - python

Hello friends of the internet,
I just began working in Python a few days ago and I am trying to create a starter program. All I am looking to do is create something that can take an input set of numbers (non-negative), from the user, and print the value of the highest number in the set.
I have read a few things about recursion functions that may be able to accomplish this task, but like I said, I'm a newby! If any of you professionals can show me something that can do just that I would be incredibly grateful.
def Max(list):
if len(list) == 1:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]
def main():
list = eval(raw_input(" please enter a list of numbers: "))
print("the largest number is: ", Max(list))
main()

You have few issues in the code:
Don't use Python keywords like list as variable names
Don't use eval() when taking input from user
You can use built-in max() unless you want to create the function for educational purposes
So heres a better version of your code:
def main():
my_list = raw_input(" please enter a list of numbers: ").split()
my_list = map(int, my_list) # convert each item to int
print("the largest number is: ", max(my_list))
main()
If you are using Python3 change raw_input() to input() and if you are using Python2 change print('item1', 'item2') to print 'item1', 'item2'
EDIT:
You can use a generator expression with max() to do that too as the following:
def main():
my_list = raw_input(" please enter a list of numbers: ").split()
max_num = max(int(x) for x in my_list)
print("the largest number is: {}".format(max_num))
main()

Single line answer:
print (max(list(map(int,input().split()))))
Explanation:
a=raw_input() #Take input in string.
b=a.split() #Split string by space.
c=map(int,b) # Convert each token into int.
d=max(c) #Evalute max element from list using max function.
print (d)
Edit:
print (max(map(int,input().split())))

Related

How can I average several inputs?

I'm trying to code a calculator with several options, just for the leraning experience, and one of these options is 'average', I want the user to be able to input as many values as he wants to, but it's not working yet, what should I change?
This is my code for the average so far:
elif ui1 == subop1_2:
1 = [input("Input your values, separate with a comma").split(',')]
result = sum(1) / float(len(1))
print("The average is {}".format(result))
time.sleep(10)
Since there were a lot of things pointed out, here goes an answer.
num_list = input("Input your values, separate with a comma: ").split(',')
num_list = [float(elem) for elem in num_list]
result = sum(num_list) / float(len(num_list))
This will fail if the user enters an empty string or characters...
Every thing you wrote was perfectly fine except a few mistakes...
1) Change all 1s to a valid variable name. Lets say, a.
2) Remove the square brackets around the input() function
3) Add a this line before the line where you assign the variable, result.
a = [int(x) for x in a]
Here is the code,
a = input("Input your values, separate with a comma").split(',')
a = [int(x) for x in a]
result = sum(a) / float(len(a))
print("The average is {}".format(result))
first of all u cannot name a variable:1 change that to "a" or something and it should work out
I would do it like this:
inp = input("Input your values, separate with a comma")
values = list(map(float,inp.split(',')))
avg = sum(values)/len(values)
print("The average is {}".format(avg))

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

How to add elements to a List in python?

I'm working on this task in python, but I'm not sure if I'm adding the elements to a list the right way. So basically I'm suppose to create a create_list function the takes the size of the list and prompt the user for that many values and store each value into the list. The create_list function should return this newly created list. Finally the main() function should prompt the user for the number of values to be entered, pass that value to the create_list function to set up the list, and then call the get_total function to print the total of the list. Please tell me what I'm missing or doing wrong. Thank you so much in advance.
def main():
# create a list
myList = []
number_of_values = input('Please enter number of values: ')
# Display the total of the list elements.
print('the list is: ', create_list(number_of_values))
print('the total is ', get_total(myList))
# The get_total function accepts a list as an
# argument returns the total sum of the values in
# the list
def get_total(value_list):
total = 0
# calculate the total of the list elements
for num in value_list:
total += num
#Return the total.
return total
def create_list(number_of_values):
myList = []
for num in range(number_of_values):
num = input('Please enter number: ')
myList.append(num)
return myList
main()
In main you created empty list, but didn't assign create_list result to it. Also you should cast user input to int:
def main():
number_of_values = int(input('Please enter number of values: ')) # int
myList = create_list(number_of_values) # myList = function result
total = get_total(myList)
print('the list is: ', myList)
print('the total is ', total)
def get_total(value_list):
total = 0
for num in value_list:
total += num
return total
def create_list(number_of_values):
myList = []
for _ in range(number_of_values): # no need to use num in loop here
num = int(input('Please enter number: ')) # int
myList.append(num)
return myList
if __name__ == '__main__': # it's better to add this line as suggested
main()
You must convert inputs to integer. input() returns a string object. Just do
number_of_values = int(input('Please enter number of values: '))
And with every input you want to use as integer.
First Problem is you are not passing myList to create_list function, so myList inside of main is not going to get updated.
If you want to create a list inside the function and return it, and then get a total for that list, you need to first store the list somewhere. parse the inputs as integer, also, always do if __name__ == '__main__':. The Following code should work and print the correct result :)
def main():
number_of_values = int(input('Please enter number of values: '))
myList = create_list(number_of_values)
print('the list is: ', myList)
print('the total is ', get_total(myList))
def get_total(value_list):
total = 0
for num in value_list:
total += num
return total
def create_list(number_of_values):
myList = []
for num in range(number_of_values):
num = int(input('Please enter number: '))
myList.append(num)
return myList
if __name__ == '__main__':
main()
An alternative method to the posted solutions could be to have one function that creates your said list and finds the total of that list. In the solution, the map function goes through all the values given to it and only keeps the integers (The split method is used to remove commas and spaces from the values). This solution will print your list and values, but will not return any said value, so it will produce a NoneType, if you were to examine the function at the end.
def main():
aListAndTotal()
#Creates list through finding the integers and removing the commas
#For loop iterates through list and finds the total
#Does not return a value, but prints what's stored in the variables
def aListAndTotal():
myList = map(int, input("Please enter number of values: ").split(","))
total = 0
for num in myList:
total += num
print ("The list is: ", myList)
print ("The total is: ", total)
if __name__ == "__main__":
main()
List is one of the most important data structure in python where you can add any type of element to the list.
a=[1,"abc",3.26,'d']
To add an element to the list, we can use 3 built in functions:
a) insert(index,object)
This method can be used to insert the object at the preferred index position.For eg, to add an element '20' at the index 1:
a.index(1,20)
Now , a=[1,20,'abc',3.26,'d']
b)append(object)
This will add the object at the end of the list.For eg, to add an element "python" at the end of the list:
a.append("python")
Now, a=[1,20,'abc',3.26,'d','python']
c)extend(object/s)
This is used to add the object or objects to the end of the list.For eg, to add a tuple of elements to the end of the list:
b=(1.2, 3.4, 4.5)
a.extend(b)
Now , a=[1,20,'abc',3.26,'d','python',1.2, 3.4, 4.5]
If in the above case , instead of using extend, append is used ,then:
a.append(b)
Now , a=[1,20,'abc',3.26,'d','python',(1.2, 3.4, 4.5)]
Because append takes only one object as argument and it considers the above tuple to be a single argument that needs to be appended to the end of the list.
You need to assign the return value of create_list() to a variable and pass that into get_total()
myList = create_list()
total = get_total(myList)
print("list " + str(myList))
print("total " + str(total))
Adding an element to an existing list in python is trivial.
Assume who have a list names list1
>>> list1 = ["one" , "two"]
>>> list1 = list1 + "three"
this last command will add the element "three" to the list. This is really simple, because lists are objects in python. When you print list1 you get:
["one" , "two" , "three"]
Done

How to read a specific number of integers and store it in a list in python?

Lets suppose I want to first input the total number of integers I am going to enter.
N = 5, I must be able to read exactly 5 integers and store it in a list
for i in range(5):
lst = map(int, raw_input().split())
doesn't do the job
In most primitive way, you can do it in following way.
n = int(raw_input())
numbers = map(int, raw_input().split())[:n]
We can help more if you tell us the context in which you are asking the problem. I doubt if you are using it for some competitive programming problem.
Actually, problem in your code is that you are reading a line and making list from it. But you are doing this FIVE times. Also, you can read lot more than five numbers if they are in single line.
Sa far as I understand, you need the following
lst=[]
for n in range(5):
lst.append(int(raw_input("Input a number: ").split()))
print repr(lst)
inp = raw_input # Python 2.x
# inp = input # Python 3.x
def get_n_ints(prompt, n):
while True: # repeat until we get acceptable input
s = inp(prompt)
try:
vals = [int(i) for i in s.split()]
if len(vals) == n:
return vals
else:
print("Please enter exactly {} values".format(n))
except ValueError:
# a string couldn't be converted to int
print("Values need to be integers!")

Adding up the sum of digits

I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]

Categories

Resources