Several questions have the same error, but I'm just starting Python and don't understand it.
I'm trying to create a program which generates two random numbers, nicknames these numbers, asks the user what the answer is, multiplies the two numbers and gives a nickname to THAT number, then it reads the user's answer and sees if the user's answer is the same as the one it got. I started with a simpler program that asks the same question three times.
My program is the following:
def math ():
for f in range (3):
x=10
c=5
x*c=p
print x,'times',c,'.'
v=read_number('What is the answer?')
if p==v:
print 'You got it right!'
else:
print 'You got it wrong.'
And now that I look at it line 6 it is unnecessary. But when I finish it Python says 'SyntaxError: can't assign to operator.'
It also highlights after c=5. Why does this happen and how can I fix it?
The
x*c=p
should read
p=x*c
This multiplies x by c and assigns the result to p.
you use randint() from the random module to generate random numbers, for example:
from random import randint
x = randint(0,10) # random between 0 and 10
c = randint(0,10)
p = x * c
print p
Related
I'm having great difficulty on a seemingly simple task... I created this one UDF to calculate the factorial of a given variable, then I need to reference this UDF from a different file which calculates Euler's number. I've tried everything I can think of, but nothing works, except displaying my 'error' message... Here's the two codes if it would help...
(fact_sub.py file)
'''
def MyFactorial(x):
q=1 # define q for future 'for' loop
if x<0: #test whether value is + or -
from colorama import Back, Style #import colorama, allowing for special effects
print(Back.RED + '\n\nError: negative integer') #print error message with red background
print(Style.RESET_ALL) #undoes colour change
else:
for a in range(1,x+1): #initiate for loop
q = a*q #set new q to old q *a (sequential values from list)
return q
'''
(Euler's.py file)
'''
from fact_sub import MyFactorial
def main():
lst_=([])
print("Enter positive integer value 'k' to calculate Euler's number and see percent accuracy.")
k=int(input('\nEnter value for k: '))
if k < 0:
MyFactorial(k)
else:
for x in range(1,k+1):
a=1/(MyFactorial(x))
lst_.append(a)
euler_lst=sum(lst_)
print(euler_lst)
'''
I hope that all makes sense... I've been looking at this problem too long, so if the logic is flawed, please tell me! Any help appreciated, TIA!
Mitchell
Please mention the logical error in the below code as I am not getting a correct output. Also, do share the correct one to get an output of the indices only.
def find2Sum(A,X):
n=len(A)
for i in range(0,n):
l=[]
if X-A[i] in A:
l.append(i)
return l
nums = [1,4,6,44, 9,8]
target = 14
find2Sum(nums,target)
#Pradeepta Sahu
When you have target=8 the answer for nums=[1,4,6,44, 9,8] should be none because there are no such numbers. But with your code logic X-A[i] in A this for i = 1 will result into 8-4==4 and it will append index to L. This is the main logical bug in the code that you have written. Any number that is target/2 will be passed by your condition.
Aside this you also declared your list var inside the for loop but you are returning it outside the for loop.
This is wrong
for i in range(0,n):
l=[]
This is right
l=[]
for i in range(0,n):
I have to make an assignment wherein I have to implement the Roman Numerals along with the rules that are followed while doing calculations on them, contained in this link
http://www.periodni.com/roman_numerals_converter.html
I don't want the code, just help. I have gone with two approaches till now:
Using constants, I have declared the roman numerals as constants, and then after getting the input, I am left with the choice to decode the string input, which I later dropped.
Using hash. I have declared a hash with the numerals, then after getting the input, I am converting the string using to_sym method into there corresponding value. After this, I have taken an array containing the decimals of the roman numerals, and I intend to compare those with the input.
I am stuck at this part. I don't know how to compare here. Also, I don't want to sort the input array, because then calculations would go wrong.
Can anyone help me with how to proceed? Not the code, just steps.
This is what I have done so far:
class Conversion
hash ={ :I => 1, :V => 5, :X => 10, :L => 50, :C => 100, :D => 500, :M => 1000}
result = 0
value = []
hash_values = hash.values
puts "enter input string"
input = gets.chomp.upcase.split(//)
input.each do |i|
value << hash[i.to_sym]
end
for i in value do
if value[i] > value[i+1]
result = result + value[i]
else
result = result + (value[i+1] - value[i])
end
end
puts result
end
If u run the code, you'll see that while I try to compare in the last loop it is taking the index for calculations. Same happened when I tried doing the same using two hashes. I can't use any gem or external libraries cause that is the requirement.
The idea is to create a tree where every node have two childrens: the left one is what to substract and the right one is what to add.
Once you get a string, you find the most valued letter and make it the first node like this:
XLIX
L
/ \
X IX
Then you run this function recursively on the children nodes until the node is trivial (like XX or III).
The final step is to recursively calculate the result.
How does Python know what "i" is when it is not defined, shouldn't there be an error? Probably a simple explanation, but I am new to learning Python.
def doubles (sum):
return sum * 2
myNum = 2
for i in range (0,3):
myNum = doubles(myNum)
print (myNum)
Haha :-) People are marking down your question, but I know that is one question must have came in every person's mind. Specially those who learned Python through Online courses and not through a teacher in person.
Well let me explain that in layman's term,
The method that you used is specially used for 1) lists and 2) lists within lists.
For eg,
example1= ['a','b','c'] # This is a simple list
example2 = [['a','b','c'],['a','b','c'],['a','b','c']] # This is list within lists.
Now, 'a','b' & 'c' are items in list.
So by saying,
for i in example1:
print i
we are actually saying,
for item in the list(example1):
print item
-------------------------
People use 'i', probably taken as abbreviation to item, or something else.
I don't know the history.
But, the fact is that, we can use anything instead or 'i' and Python will still consider it as an item in list.
Let me give you examples again.
example1= ['a','b','c'] # This is a simple list
example2 = [['a','b','c'],['a','b','c'],['a','b','c']] # This is list within lists.
for i in example1:
print i
[out]: a
b
c
now in example2, items are lists within lists. --- also, now i will use the word 'item' instead of 'i' --- the results regardless would be the same for both.
for item in example2:
print item
[out]: ['a','b','c']
['a','b','c']
['a','b','c']
people also use singulars and plurals to remember things,
so lets we have a list of alphabet.
letters=['a','b','c','d']
for letter in letters:
print letter
[out]: a
b
c
d
Hope that helps. There is much more to explain.
Keep researching and keep learning.
Regards,
Md. Mohsin
Using a variable as a loop control variable does assign to it each time through the loop.
As to "what it is"... Python is dynamically typed. The only thing it "is" is a name, just like any other variable.
i is assigned the value in the loop itself, it has no value (it is not defined) before the Python interpreter reaches the for line.
Its similar to how other for loops define variables. In C++ for example:
for(int i=0; i<5; i++){
cout << i << endl;
}
Here the variable i is only exists once the for loop is called.
i is assigned a value when the for loop runs, so the Python interpreter will not raise an error when the loop is run
long story short it creates a new variable without having to be defined and its value is whatever number your loop is on, for example if you had written:
num = 0
for i in range(3):
print(num)
num = num + 1
so for the first time this loop ran 'i' would equal 0 (because python lists/loops etc always start on 0 not 1), the second time it would equal 1, etc. and the 'num' you can ignore it's just an example of code you could have in a loop which would print out numbers in ascending order.
Levin
I am trying to take my array of numbers based on a variable that determines its size and sort it.
The array is created using the random numbers seed on Fortran 95. However when I try to sort it I run into big trouble. It compiles fine, but the array is printed with a lot of asterisks in it.
In addition I wanted to print my array sideways, (for instance something like this: 1 2 3 4 etc.) but I even failed at doing that. I realize that it must be done using the Advance="no" within a DO loop, but apparently that is erroneous as well.
Below is the code that I am using. If anyone is willing to let me know where I may be wrong I would be very grateful. Thanks for your time.
SUBROUTINE Sorter(num, numinteger)
INTEGER, INTENT(OUT):: num(100)
INTEGER, INTENT(IN):: numinteger
DO i=1, (numinteger-1)
min=num(i)
pos=i
DO j=i,numinteger
IF (num(j)<min)THEN
min=num(j)
pos=j
END IF
END DO
temp=num(i)
num(i)=min
num(pos)=temp
END DO
PRINT*, " "
PRINT*, "Sorted Numbers"
DO i=1, numinteger
WRITE(*,23,ADVANCE="NO") num
23 FORMAT (I2)
END DO
END SUBROUTINE
Thanks!
You don't have any spaces between your numbers, but you are also looping over the array, but not incrementing an index... you are asking the computer to print the entire array on each interation.
I think this should be: WRITE(*,23,ADVANCE="NO") num(i)