Beginning Equations in Code not being Shown in Output - python

Relatively new to Python. Equations I've written work alone, but I can't seem to figure out why only the last bit of the code is being shown in output.
I've tried using concatenation to no avail.
X = input('Enter X:')
Y = input('Enter Y:')
X1=int(X)
Y1=int(Y)
(X1+Y1)/(X1-Y1), (X1-Y1)**3,
Answer = X1+Y1
print ('The last digit of X+Y is ' + str(Answer)[1])
I know the answer is most likely going to be quite simple, but any bit of advice helps!

In jupyter notebook by default give output at the end of the line code in single code cell unless you explicitly define print statement
Eg:
X=10
X*3
X*45
#op
450
In above code it will give only last line output
If you had print statement every line then you will get all the line output
X=10
print(X*3)
print(X*45)
#op
30
450

Only the last statement was being printed because that was the only one with a print statement. Just adding print to (X1+Y1)/(X1-Y1), (X1-Y1)**3, will fix the problem. So like this: print((X1+Y1)/(X1-Y1), (X1-Y1)**3)

Related

Unwanted blank lines in my Python function output

I'm working on a data science project to make some prediction, and I need to calculate a new column based on other column values.
All is working fine, except that my Jupyter-lab is printing me blank lines in my output and I don't know why.
Here's the code :
# Calcul A :
pas = 1500
TailleTotal = len(df)
limite=TailleTotal-pas
df['A'] = np.empty(TailleTotal, dtype = float)
index=0
while index < limite :
A_temp = 0
A_temp = np.sqrt((df['X'][index]**2)+(df['Y'][index]**2)+(df['Z'][index]**2))
df['A'][index]=A_temp
index = index+1
And when I run it, I have a blank line for every iteration.. My files is making more than 1M lines, I have to scroll all over in my code it's very annoying.
But it's more that I really don't understand why it does this, I have no print function or anything that is supposed to show me something.. So why Python have this need to show me empty lines ? It's because I have no "return" in my loop ?
Edit : It appears to be a "output memory" problem from Jupyter-lab. Right clicking and "clear all output" is resolving my issue
You have an infinite loop, first change the while and try to do maybe 1 or 2 iterations and check if the problem is the same. I'm prety sure that dissapears. The kernel should be consuming resources for your loop.

What is wrong with the syntax with line 7 in my code? It says my print statement has invalid syntax and I can't figure it out?

total_cost_of_food = float(input('How much did the food cost? '))
sales_tax = 8.25
tax_plus_total = total_cost_of_food * sales_tax / 100
print("Your tax for this meal was:", tax_plus_total)
x = bool(input("Would you like to add a tip? ")
if x is False
print("Thanks, your total for today is:", tax_plus_total)
else
print("That is", x, "I would like to add a tip")
I keep getting this error for my print statement that is under the if statement, it says it's a syntax error but I don't see anything wrong with the syntax... I have only been coding for about a week though so I am likely missing something.
The : is missing, at the end of the if line and the else line
Instead of if x is False, you should use if not x:
Also, you should reduce the indenting of all four lines in your if-else construct, by one level.
bool(input("Would you like to add a tip? ") lacks the second closing parenthesis.
Python very often prints a syntax error for the next line or even a subsequent line after that when you have a missing closing parenthesis. It tries to make sense of what you wrote and it takes a while for it to figure out that it really can't.
This also masks the indentation error on the following line, and the lack of a colon at the end of the if and else lines.

Python error while finding greatest number

I am trying techgig problem of finding greatest of 3 numbers. problem as follows
You just need to take three number as input from stdin and you need to
find greatest of them.
Input Format
You will be taking three numbers as an input from stdin one on each line respectively.
Constraints
-100000 <= N <= 100000
Output Format
You need to print the greatest of the three numbers to the stdout.
Sample TestCase 1
Input
902
100
666
I done this
''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
import sys
def main():
s=sys.stdin.read()
s=s.split("\n")
a=int(s[0])
b=int(s[1])
c=int(s[2])
temp=0
e=[a,b,c]
for i in e:
if i > temp:
temp=i
print(temp)
'''if (a>b) and (a>c):
temp = a
elif (b>a) and (b>c):
temp = b
else:
temp = c
print(temp)'''
main()
It has predefined input 902, 100, 666. My code shows 902 output and expected also shows 902, but its showing failed, Why? In above code commented or non commented thing both showing failed.
I might be wrong but the output says to print using the stdout: You need to print the greatest of the three numbers to the stdout. The print in python is the same as sys.stdout.write(str(99) + '\n'). Try using stdout to print the result.
sys.stdout.write(str(temp))
temp is being initialized as 0, but the input allows for negative numbers. 0 will considered larger than any negative input though. This means your algorithm will fail for test cases that have negative input.
Initialize temp to a value smaller than the minimum allowed input:
temp = -100001 # One less than the minimum
Actually they are looking for the output as mentioned and though the logic of your code is right but the output will give a new line which will be considered wrong. To fix this we use within print statement (end = "")
so the right code becomes
Hope it helps, keep coding.

Reading from a CSV file and using the data to talk to pygame

Having a lot of problems with everything today it seems, first time asking a question and I can't even get my code on here correctly!
Essentially what I'm hoping to do, is to import data from a csv file and use it to select and display images using pygame e.g.
screen.blit(row[0],(0,0))
Where row[0] is Rat1 in the csv file, which has been defined in my code as:
Rat1 = pygame.image.load('Rat1.jpg').convert()
However this throws up "argument 1 must be pygame.Surface, not str", which is fair enough, but I'm really struggling to find a way around this and have found some rather bizarre goings on, bizarre to me at least.
I'm new to this, so the best way I can think to get around this, is to change the row[0] in the csv file to 1, and then to import that to my program and create an integer variable from it, e.g.
x = row[0]
int(x)
if x == 1:
x = Rat1
and then plug x in to pygame, e.g.
screen.blit(x,(0,0))
This works if I just have x = Rat1 as a global variable, however doing it as above doesn't change x to = 1, it stays as row[x] so it just doesn't like it.
It boils down to this happening when I tried to test it a bit...
import csv
out = open("CSVTest.csv","rb")
data = csv.reader(out)
data = [row for row in data]
out.close()
print row[0] #this causes it to print a 1, so I know
#it's working and reading as it should
x = row[0] #make a variable
int(x) #doesn't throw up an error, so I assume it
#has changed the csv string to an integer
print x #prints a 1 again
if x == 1:
print "hello?" #doesn't print, so clearly doesn't
#recognise x as an integer
if x == 49: #I'm getting desperate now, ASCII 1?!
print "hello?!" #No joy
So what on earth is it, it doesn't seem to be your standard string, as won't convert obviously in to an integer.
I've tried pygame.image.fromstring(), where the answer probably lies, but I can't get it to work.
Can anyone point out what is wrong with it all and how I can easily call data from a csv file and at least get it recognised as an integer or even better, inserted in to a bit of pygame code and displayed?
I've read things from csv files and displayed images with pygame without a hitch, but getting the two to mate seems tough, beyond me certainly.
Any help is much appreciated!
int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer:
print int("1") + 1
The above prints 2.
If you know the structure of your list (that it simply contains lists, only one level), you could do this:
T2 = [map(int, x) for x in T1]
Or...
Try this.
x = "1"
x is a string because it has quotes around it, but it has a number in it.
x = int(x)
Since x has the number 1 in it, I can turn it in to a integer.
To see if a string is a number, you can do this.
def is_number(var):
try:
if var == int(var):
return True
except Exception:
return False
x = "1"
y = "test"
x_test = is_number(x)
print(x_test)
It should print to IDLE True because x is a number.
y_test = is_number(y)
print(y_test)
It should print to IDLE False because y in not a number.

How do I calculate something inside a 'for' loop?

I'm doing an assignment in which I have to move a simulated robot across the screen in a loop - I've got that part down, however, between loops, I also have to print the percentage of area covered with each movement - that's my issue.
I googled a bit and even found someone with the same problem, however, I'm not sure if I'm doing it properly.
This code was offered:
percent_complete = 0
for i in range(5):
percent_complete += 20
print('{}% complete'.format(percent_complete))
However, after an error, further googling revealed that only worked with certain versions
so I used this code:
percent_complete = 0
for i in range(5):
percent_complete += 20
print '% complete' % (percent_complete)
And, at the very least, it now executes the code, however, the output when printing is the following:
Here we go!
hello
omplete
hello
(omplete
hello
<omplete
hello
Pomplete
hello
domplete
What is the cause of this? I assume because one of the codes had to be edited, the other parts do as well, but I'm not sure what needs to be done.
for i in range(5):
percent_complete += 20
print '%d complete' % (percent_complete)
You were missing the d specifier.
The first version only works in Python 3 because it uses print as a function. You're probably looking for the following:
percent_complete = 0
for i in xrange(5):
percent_complete += 20
print '{0} complete'.format(percent_complete)
Your other code doesn't do what you intend to do because it now display the number as a string. What you want is that the number is properly converted to a string first and then displayed in the string. The function format does that for you.
You can also use Ansari's approach which explicitly specifies that percent_complete is a number (with the d specifier).
To add to/correct above answers:
The reason your first example didn't work isn't because print isn't a function, but because you left out the argument specifier. Try print('{0}% complete'.format(percent_complete)). The 0 inside the brackets is the crucial factor there.

Categories

Resources