This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Hi

Can anybody tell me how to convert the following c++ code to python:

for (int x =0; x < 100; ++x){

y[x] = sin( i * 20 );

}

Can anybody tell me how to convert the following c++ code to python:

for (int x =0; x < 100; ++x){

y[x] = sin( i * 20 );

}

As you can gather I'm learning Python so please forgive the novice questions.

I note you use xrange(100). What if I was using

for (int x=5; x<100; ++x)

I'm slightly surprised that the Python code is so different to C++. I was expecting more of an overlap e.g. Java, I believe, is more like C++.

As a matter of interest, why was Python written so differently?

Issac

However, there is numpy package that is more optimized for working with arrays and matrices.

b.py

```
import math
import matplotlib.pyplot as plt
y = [0] * 100
for x in xrange(100):
y[x] = math.sin(x * 20)
plt.plot(y)
plt.ylabel('sin(x)')
plt.show()
```

I have no idea if it works and how. It is taken directly from the tutorial http://matplotlib.sourceforge.net/users/pyplot_tutorial.html (combined with the above sin).

The Python for-loop is more abstract. It was designed to simplify looping through anything that supports iteration. This way you can get elements of lists, elements of tuples, elements of strings, elements of sets, keys of dictionaries, lines of text files, and values of whatever containers that supports iteration.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.

a.py

Open in new window