Why am I not getting 333 in Python - python

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.

Related

Python input multiple lines and spaces

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 have to write a program that calculates and displays the total score using a for loop?

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.

getting incorrect answer. what is wrong with this code?

x=raw_input('what is your favorite number? ')
n=x*10
print n
If I plug in 5, I don't get 50. I get 5555555
I have tried declaring float(n) and tooling around with it. nothing helped. I realize this is minor league, but I am just starting to teach myself python.
Thanks, Todd
You are taking in your number as raw_input, meaning, it is returned to the program as a string. When you multiply a string by an integer and print the result, it just prints the string x times, in your case 10 because you attempted to multiply by 10. To prove this, change, the 10 to 20 and watch what happens.
There are two ways to fix this. The first would be to use input() instead of raw_input(), so that it returns a number as a result.
x=input("Please enter a number here.\n")
The second way would be to reassign x to the integer equivalent of the string, using the function int().
x=int(x) # Will turn "10", which is what you have, into 10
This should solve your problem.
Best of luck, and happy coding!
This is because the default data type of raw_input() is string. You have to cast the string input to an integer for achieving the desired result.
When you read a value in from user input like this it is as a string. So x actually equals the string '5' but what you actually want is the number 5.
int(x) * 10

writing an improved version of the Chaos Help

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.

an error in taking an input in python

111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number
It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:
a=(0.5 + 2.5*(k %2))*k + k % 2
This implicitly results in a floating point number for the value of (0.5 + 2.5*(k %2))*k. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:
a=(1 + 5*(k %2))*k//2 + k % 2
It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using repr (or something that invokes repr, like printing a list) that it gets the 'L'.
What exactly is going wrong?
Edit: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.
As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following page.
When I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:
>>> a = 111111111111111111111111111111111111111
>>> a + 1
111111111111111111111111111111111111112L
>>> str(a)
'111111111111111111111111111111111111111'
>>> int(a)
111111111111111111111111111111111111111L
I did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have unlimited precision. So cool!
Another way to avoid numerical errors in python is to use Decimal type instead of standard float.
Please refer to official docs
Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.

Categories