Learning the basics of python and I am running across a problem. I'm sure it is a simple fix. I'm trying to get my program to get 20 different inputs before calculating the min, max, etc.
def main():
number = valueInput()
display(number)
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
def display(number):
print("The lowest number is:", min(number))
print("The highest number is:", max(number))
print("The sum of the numbers is:", sum(number))
print("The average number is:", sum(number)/len(number))
main()
I can get it to work by repeating this line:
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
to the 20th number but there must be a way that makes it shorter and cleaner. Again I am a beginner so any explanation would be much appreciated.
All you have to do to fix your program is remove four spaces:
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
The last line in the block above has been unindented by one level. Instead of returning after the first time through the loop, it lets the loop complete, and then returns the resulting list.
Also you can change your:
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
part with:
values = [int(input("Enter a random number " + str(x + 1) + ": ")) for x in list(range(20))]
return values
You can check out build in functions
Related
the problem says to print "that's a really really ... big number" with one "really" for every extra digit that the number has (so 15 would be "that's a really big number", 150 would be "that's a really really big number", 1500 would be "that's a really really really big number", and so on.)
the input is an integer, and the only requirements listed are that the code should run correctly with any integer, should use a while loop to keep dividing the number by 10 and should use += to add onto the end of a string
x = input(("input an integer: "))
count = len(x)
y = int(x / 10)
countx = count - 1
print("that's a " + count("really") + " big number")
i don't really know what i did, but i can tell it's not correct
Try this one. Uses while loop to divide number by 10 and += to add onto the string. You will need to take a string variable and then append to it as count increases. Loop will run until number >= 10 as conditions you mentioned.
x = int(input(("input an integer: ")))
str=""
while x>=10:
x=x//10
str+="really "
print("that's a " + str + "big number")
Added the while loop as you stated in your question
strVar = ""
y = 0
length = 0
cnt = 0
finished = False
num = input("Type a number: ")
while not finished:
y = int(num)//10
length = int(len(str(y)))
if length <= cnt:
finished = True
else:
strVar += " really"
cnt += 1
print("That's a" + strVar + " big number!")
Give this a try. It finds how many trailing zeroes there are in a given number and based on that creates a certain amount of really's.
x = input(("input an integer: "))
count = int(len(x) - len(x.rstrip('0')))
if count == 0:count = 1
really = "really "*count
print(f"that's a {really} big number")
Try this
x = int(input("enter an integer"))
print("that's a " + 'really '*(len(str(x))-1) + " big number")
If you want to correct your function use this
x = input(("input an integer: "))
count = len(x)
y = int(x) / 10
countx = count - 1
print("that's a " + countx*" really" + " big number")
I am writing a program that calculates the factorial of a number, I am able to display the correct answer, however along with the answer I need the actual calculation to display, I am having trouble with that. So for example, when the user enters 4, I need it to display as:
I have been trying to figure out the right code, but do not know what to do.
Here is the code I have so far
number = int(input("Enter a number to take the factorial of: "))
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print (factorial)
Right now, it displays the correct answer, however I need for it to include the equation as well as follows: 4! = 1 x 2 x 3 x 4 = 24
The simplest approach is to construct the string as you are iterating:
equation = str(number) + "! = "
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
equation += str(i) + "x"
equation = equation[:-1] + " = " + str(factorial)
print(equation)
Note that this method appends an unwanted 'x' after the last factor. This is removed by equation[:-1].
Alternatively, you could append this one-line solution to the end of your code. It uses the join method of the string class to concatenate an array of strings:
print(str(number) + "! = " + "x".join(str(n) for n in range(1, number + 1)) + " = " + str(factorial))
As you loop through the numbers to be multiplied, you can append each number's character to a string containing the equation, e.g ans, and print it at last. At the end of the code, I omitted the last letter because I didn't want an extra 'x' to be displayed.
def fact(number):
num_string=str(number)
factorial = 1
ans=num_string+"!="
for i in range(1, number + 1):
factorial = factorial * i
ans+=str(i)+"x"
ans=ans[:-1]
print(ans)
return factorial
fact(4)
You can append each value to the list and then print the equation using the f-string:
num = 5
l = []
f = 1
for i in range(1, num + 1):
f *= i
l.append(i)
print(f"{num}! = {' x '.join(map(str, l))} = {f}")
# 5! = 1 x 2 x 3 x 4 x 5 = 120
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = first + second
print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.
Thanks
Keep your variables as numbers and let print do the formatting:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print "You have rolled a", first, "and a", second, ", for a total score of", total, "."
Or you could do some formatting using str.format to have more control over the default inter-parameter spacing in the above:
print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)
There are two ways to address your problem (and more still!). Firstly, you need to make sure you keep your integers as type int when adding them together, and then cast them to a string when you print them out.
You can do this like the below, using the str() casting method and + concatenation.
def die1():
"""Roll and print two dice using concat."""
first = randint(1, 6) # keep these as integers
second = randint(1, 6)
total = first + second # so addition works
# but now cast to str when printing
print "You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + "."
But a handier way is to use the str.format() method to put placeholders in your string, and then let python cast and format the integer values for you. If you have big numbers with 4 or more digits, an advantage of this would be that you can use a string formatting code like "my big number: {0:d,}".format(1000000) to make your string output like "my big number: 1,000,000", which is much more readable.
def die2():
"""Roll and print two dice using str.format()."""
first = randint(1, 6)
second = randint(1, 6)
total = first + second
# or use the str.format() method, which does this for you
print "You have rolled a {0} and a {1}, for a total score of {3}.".format(first, second, total)
You can use casting to change the structure of the var. You can either use them as strings and for total use this line:
total = int(first) + int(second)
or use them as int and cast them to string in the print by using str(first) and str(second)
Best
print "You have rolled a " + str(first)
This would convert the int to a string, hence concatenating it.
Also, you can do
total = int(first) + int(second) to address the first issue.
You have two solutions:
Convert the numbers back to int before adding them:
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = str(int(first) + int(second))
print ("You have rolled a " + first + " and a " + second + ", for a total score of " + total + ".")
Convert the numbers into str before printing them:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + ".")
Either solution will work perfectly fine.
This would also work. Don't convert first and second to str until after you perform sum on them. Then remember to cast them as str in your print statement.
def die():
first = randint(1, 6)
second = randint(1, 6)
total = str(first + second)
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + total + ".")
I am trying to ask the user for several values for temperatures of several month by the "monthtemp" input and then add all the values to a list and in the end print out the average for the whole year.
count = 1
loops = int(input("How many years?: "))
listofmonthtemperatures= list()
while count < loops:
for i in range(1,loops+1):
count += 1
year = input("Which is the " + str(i) + ": year?: ")
for j in range (1,13):
monthtemp= int(input("Month " + str(j) + ": "))
listofmonthtemperatures.append(monthtemp)
total= sum(listofmonthtemperatures)
averagetempforyear= total / 12
print("The average temperature for", year, "is", averagetempforyear)
But I get the message year is not defined, but haven't I defined it as whatever the user inputs? And second, will this work? Why can't append simply append the value to listofmonthtemperatures?
I copy/pasted your code and it worked just fine. Maybe this was a typo but your for loops weren't properly indented. I'm running 3.4.3 btw.
count = 1
loops = int(input("How many years?: "))
listofmonthtemperatures= list()
while count < loops:
for i in range(1,loops+1):
count += 1
year = input("Which is the " + str(i) + ": year?: ")
for j in range (1,13):
monthtemp= int(input("Month " + str(j) + ": "))
listofmonthtemperatures.append(monthtemp)
total= sum(listofmonthtemperatures)
averagetempforyear= total / 12
print("The average temperature for", year, "is", averagetempforyear)
Above is the working code with the proper indentation.
I'm new to programming. I have a bit of problem with python coding (with def function).
So basically the code has to give the smaller number out of 2 numbers.
Question:
Write codes to perform the following tasks:
Define a function smaller_num that takes in two numbers to
determine and return the smaller number of the two.
Ask user for two numbers
Use the function to determine the smaller number and display the result
So I had user input instead of calling the function and adding value inside the variable.
This is how my code looks like:
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num))
How do I correct it? For now it's not working because "x" is not defined. But I feel that I defined them clearly both in def function and input function. So how do I fix this?
Thanks for those who respond to this question.
You never actually defined x and y globally. You only defined it in the function when you did def smaller_num(x, y).
When you do smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
, you aren't creating variables called x and y, you are just creating parameters for your function.
In order to fix your code, create the variable x and y before you call your function:
def smaller_num(x, y): ## Can be rephrased to def smaller_num(x, y):
if x > y: ## if x > y:
number = y ## return y
else: ## else:
number = x ## return x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
result = smaller_num(x, y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(result))
The other reason your code is not working is because you're not assigning the returned value of the function back into a variable. When you return something from a function, and again when you call the function, you need to assign the value to a variable, like I have: result = smaller_num(x, y).
When you called your function, you never assigned the value to a variable, so it has been wasted.
Also, are you using Python 3 or 2.7? In python 3 using input() will return a string, and to convert this to an integer, you can call int() around the input() function.
This will work:
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
smaller = smaller_num(x,y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller))
this should work:
def smaller_num(x,y):
if x>y:
number = y
else:
number = x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num(x,y)))
def smaller_num(x,y):
if x>=y:
number = y
else:
number = x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num(x,y)))
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
k=smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
print("The smaller number between x & y is ", k)
def smaller_num():
x=int(input('Enter the first number: '))
y=int(input('Enter the second number: '))
if x<y:
return x
else:
return y
print('The smaller number is: ',smaller_num())