Here is the question proposed by the text.
Write an improved version of the Chaos program from Chapter 1 that allows a user to input two initial values and the number of iterations and then prints a nicely formatted table showing how the values change over time. for example, if the starting values were .25 and .26 with 10 iterations, the table would look like so:
following this is a table with a index 0.25 0.26 as headers and then the 10 iterations in two columns.
here is my initial Chaos program.
# File: chaos.py
def main ():
print ("This program illustrates a chaotic function")
x=eval (input("enter a number between 0 and 1: "))
for i in range (10):
x = 3.9 * x * (1-x)
print (x)
main()
my question is how do i change it to fulfil the above question..
Please if answering take in mind this is my first programming class ever.
You really just have to duplicate the functionality you already have. Instead of just asking the user for an x value, also ask for a y value.
x= float(input("enter a number between 0 and 1: "))
y= float(input("enter another number between 0 and 1: "))
Then in your loop you need to do the same thing you did with the x value to the y value. When you print, remember that you can print two values (x and y) at once by separating them with a comma.
Also, as PiotrLegnica said, you should use float(input(...)) instead of eval(input(...)). Since you know that the user should enter a floating point number (between 0 and 1) you don't have to call eval. Calling eval could be dangerous as it will execute any instruction given to it. That might not matter right now, but it's better to not get in the habit of using it.
Related
num=int(input("what is your number"))
total=int(input("how many times do you want this number to appear"))
new_num=0
for i in range (total):
new_num=num*10
new_num=new_num+num
print (new_num)
I keep getting 33, even when i changed my range to (total+1). What must I do to get 333
When you have a problem like this use a debugger (python includes one in pdb) to step through the code and see how variables change.
In simple cases just use print. In this case put a print(new_num) after each time you assign to new_num.
In this case you will notice where new_num gets set to the wrong value.
You keep assigning new_num=num*10 instead of multiplying new_num by 10
As I understood from your question, the value of num you are taking as 3. And for total as well the same 3.
Note: Always try to provide some examples while posting your problem so that the answerers could read, understand & suggest, help.
I have a quick solution for you here, just try and try to modify for other purposes.
int(f'{num}' * total) is sufficient to give you that. You can change it a bit and do for floats as well.
>>> num=int(input("what is your number: "))
what is your number: 3
>>>
>>> total=int(input("how many times do you want this number to appear: "))
how many times do you want this number to appear: 3
>>>
>>> int(f'{num}' * total)
333
>>>
Thanks.
Im trying to solve one of the a2oj problems "given three numbers a , b and c. print the total sum of the three numbers added to itself."
I came with this
import sys
numbers = [int(x) for x in sys.stdin.read().split()]
print(numbers[0] + numbers[1] + numbers[2])
I saw many topics but I cant figure out how to read just 3 values from input. I know I can stop this procces by typing CTRL+D, but is there any possibility to make it automatic (after reaching third value)?
Thanks
// Thanks for very quick answers, I made mistake and posted only Problem Statement without Input Format: "three numbers separated by bunch of spaces and/or new lines"
So for example input should look like this:
2
1 4
// Ok thanks to you guys finally I made this:
n = []
while len(n) < 3:
s=input()
i = s.split()
[n.append(int(j)) for j in i]
print(2 * sum(n))
It's working but when I sent my results I got Runtime Error. I have no idea why:
Link: https://a2oj.com/p?ID=346
You could just use:
sys.argv
import sys
numbers = [int(x) for x in sys.argv[1:4]]
print(numbers)
print(sum(numbers))
When inputs are given line by line.
from sys import stdin
sum = 0
for num in stdin.readline(4):
sum = sum + int(num)
print(sum)
When inputs are given on CLI.
from sys import argv
sum = 0
for num in argv[1:4]:
sum = sum + int(num)
print(sum)
Use Python strip() and split() functions as per your usecases
I am not sure what you are looking for, but it seems that you are looking for is the input function, from python's builtins:
x=input()
This reads any input from the user, as a string. You have then to convert it to a number if needed.
You can read three values:
x=input("First value:")
y=input("Second value:")
z=input("Third value:")
As you have now specified more precisely the problem statement, I edit my answer:
In your case, this is not very complicated. I am not going to give you the answer straight away, as it would defeat the point, but the idea is to wrap the input inside a while loop. Something like:
numbers=[]
while (you have less than 3 numbers):
(input one line and add the numbers to your list)
(print the sum of your numbers)
That way you are waiting for as many inputs as you need until you reach 3 numbers. By the way, depending on your input, you might have to check whether you do not get more than 3 numbers.
After seeing the update from the question author and linked the online judge question description, the tweak to his code needed is below. It's worth noting that the expected output is in float and has precision set to 6 and the output is 2 * sum of all inputs, not just sum. There is no description on this in the online judge question and you've to understand from the input vs output.
n = []
while len(n) < 3:
s = input()
i = s.split()
n.extend(float(j) for j in i)
print(format(2 * sum(n), '.6f'))
Screenshot below
But the first version of this answer is still valid to the first version of this question. Keeping them if anyone else is looking for the following scenarios.
To separate inputs by enter aka New lines:
numbers_List = []
for i in range(3):
number = int(input())
numbers_List.append(number)
print("Sum of all numbers: ", sum(numbers_List))
Screenshot:
To separate inputs by space aka Bunch of spaces:
Use map before taking input. I'd suggest using input as well instead of sys.stdin.read() to get input from users, separated by space, and ended by pressing Enter key.
Very easy implementation below for any number of inputs and to add using sum function on a list:
numbers = list(map(int, input("Numbers: ").split()))
print("Sum of all numbers: ", sum(numbers))
The screenshot below and link to the program is here
Read Python's Built-in Functions documentation to know more about all the functions I used above.
I’m taking an online basic programming class and I’m completely lost on this assignment. Our book went over basic loops, but not how to find max, min, or average in a loop with values input by a user. Here is my assignment:
Write a loop control program that will provide important statistics for the grades in a class. The program will utilize a loop to read five floating-point grades from user input. Ask the user to enter the values, then print the following data: Average Maximum Minimum
My textbook and instructor have really given me no guidance on how to use floating numbers in a loop. Here is what I have come up with so far:
for grade in range(5):
int(input("Enter Grade (percentage): "))
if max:
print('Max:')
if min:
print('Min:')
else:
print('Average:')
This allows me to get the loop to run 5 times but how do I actually calculate the min, max, and average for unknown variables?
I don't do python, but I'd know how to approach this problem.
For the average, declare a variable called sum or something and set it to 0. Then, every time you get an input, add that value to the sum. After 5 inputs, print that sum divided by 5. That'll be the average.
To get the max, initiate a variable to 0. On input, check if that input is greater than the currently stored maximum. If so, set the variable to that input. After 5 inputs that variable will contain the max.
Similarly for the min. But make sure to set that variable to something big at the start (like 100000), and then check if the new input is smaller than that variable.
Also, if you're supposed to use floats, don't cast your user input to an int. Use float instead.
You use floating numbers in a loop the same way you use them outside the loop.
The loop does not change anything.
But, it seems you are misunderstanding the task wording:
You are not suppose to print the min, max, and average calculation inside the loop.
That would be impossible, since you can not know them, until the user inputs all 5 grades.
What you are suppose to do inside the loop, are 4 steps:
Read a float from the user. Currently, you are trying to read an int for some reason. Do you know how to read a float in Python?
Add it to the sum you will use after the loop to calculate average.
See if it is the max of all numbers the user inputted so far.
See if it is the min of all the numbers the user inputted so far.
Once you exit the loop, all you have to do is print 3 numbers:
The max and min you found and the average calculation.
You'll want to make a list first,
Then create a for loop that will run 5 times, range(5) should work.
Then exit the loop and run an average, min and max
You can create a simple function for this task. You can do the following:
def take_what(statistic = None):
f = []
for grade in range(5):
f.append(int(input("Enter Grade (percentage): ")))
if statistic == "max":
print('Max: {}'.format(max(f)))
elif statistic == "min":
print('Min: {}'.format(min(f)))
else:
print('Average: {}'.format(sum(f)/len(f)))
print(take_what('max'))
print(take_what('min'))
print(take_what())
I am in intro programming class and I just started learning the loops. My question asks about the average value of the inputs and it supposed to be done with while-loops. When the user inputs end instead of a number, that signifies the end of the loop and calculates the average value. The program should print the average value and return it. Also, if the user does not input any number and directly inputs end, the program should print "No numbers were entered". I tried creating the loop, but I do not know what I am missing for my loop to be running.
Also, I am not allowed to use any inbuilt functions like sum, ave, etc.
Here is the code I've written so far
def avgOfTheSum():
total = 0
avg = 0
count = 0
while True:
number = input("Enter next number:")
if number != 'end':
num = float(number)
total = total + num
count = count + 1
average = total/count
else:
print("The Average is:",average)
break
return average
a few tips from my not-so-experienced point of view :
when you increment a variable, eg. 'total = total + num', you can do so with a more compact way : use 'total += num' which does exactly the same thing and lightens your code. Some people find it ugly though, so use it if you will.
You first declared a variable named 'avg' but you then later use 'average', which leads to an error when trying to print 'average' which was not defined because the first 'if' statement was bypassed.
You should use one naming for the average. Either 'avg' or 'average' is okay but remember your code must be easy to understand so try not to squeeze things too much, especially if someone is reviewing it when you are finished.
Use one name and stick to it. That way you don't have an error when the user inputs something that isnt handled by your code.
You could add safe nets to ensure the user passes a number but the most simple ways need to use python built-ins.
You could add something like (not python do not write it like so)
if count = 0
then print 'no numbers entered'
then either :
break if you want to quit the application
or pass if you want to force the user to enter a number (enforcing a new loop)
Hope it helped you a little bit !
I'm quite new to the for loops in Python. So, I want to write a program that asks the user to enter to enter 20 different scores and then I want the program to calculate the total and display it on the screen. How could I use a for loop to do this?
edit: I can ask the user to for the different numbers but I don't know how to then add them.
Without giving you the full code here is the pseudocode for what your code should look like
x = ask user for input
loop up till x //Or you could hard code 20 instead of x
add user input to a list
end
total = sum values in list
print total
Here are all the things you need to implement the logic
User input/output:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html
Loops:
https://wiki.python.org/moin/ForLoop
Summing a list:
https://docs.python.org/2/library/functions.html
Try something like this:
total = 0; # create the variable
for i in range(1,20): # iterate over values 1 to 20 as a list
total += int(input('Please enter number {0}: '.format(i)));
print("Sum of the numbers is '{0}'".format(total))
I'd suggest you go through the tutorials on the python site:
Python 3 is here https://docs.python.org/3/tutorial/index.html
Python 2 is here https://docs.python.org/2/tutorial/index.html
I could go into a lot of detail here and explain everything, however I'd only be duplicating the resources already available. Written far better than I could write them. It would be far more beneficial for you (and anyone else reading this who has a similar issue) to go through these tutorials and get familiar with the python documentation. These will give you a good foundation in the basics, and show you what the language is capable of.
Input
To read a value from the commandline you can use the input function, e.g. valueString = input("prompt text"). Notice the value stored is of type string, which is effectively an array of ASCI/Unicode characters.
So in order to perform math on the input, you first need to convert it to its numerical value - number = int(valueString) does this. So you can now add numbers together.
Adding numbers
Say you had two numbers, num1 and num2, you can just use the addition operator. For example num3 = num1 + num2. Now suppose you have a for loop and want to add a new number each time the loop executes, you can use the total += newNum operator.
total = 0
for _ in range(1,20):
num = input('> ')
total += int(num)
print(total)
I hope this helps.