Jill A. Brady
University of California, Riverside
Department of Computer Science and Engineering



Home

About Me

Teaching

Projects

Papers


Python Tutorial, for C++ Programmers

Basic Rules:
Semi-Colons: Aren't needed at the end of lines, except for after return statements in functions.
Indenting: Is important. Bodies of loops or functions are signified only by being indented.



C++ to Python:
C++ Python
Commenting:
 // This is a comment.
 # This is a comment.
Variables:
 int i = 10; 
    
 i = 10 
Notice that variables are not initalized with a type. They can be also be changed from one type to another.
 i = 10
 i = "Hello"
 
While Loops:
 
 int i = 0;
 while (i < 10)
 {
     .... code ....
     i++;
 } 
 i = 0
 while i < 10:
     .... code ....
     i +=1 
No parenthesis are needed around the clause.
Colon ":" ends clause statement.
Loop body indicated only by indentation.
For Loops:
 
 for (int i = 0; i < 10; i++)
 {
     .... code ....
 } 
 for i in range(10):
     .... code ....
range(10) produces [0,1,2,3,4,5,6,7,8,9]
For Loops through lists:
 
list myList = ["Jill","John","Jet"];
 for (int i = 0; i < 3; i++)
 {
     string name = myList[i];
 } 
 myList = ["Jill","John","Jet"]
 for i in myList:
     name = i
Notice that the iterator actually becomes the value in the list.
Screen Output:
 cout << "Hello world!" << endl;
 print "Hello world!"
Screen Output, multiple types:
 int myNum = 2;
 cout << "Hello world! Number " << myNum <<  endl;
 myNum = 2
 print "Hello world! Number " + str(myNum)
Notice that str( myNum ) typecasts an int into a string.

User Input:
 cout << "What is your name?" << endl; 
 string name;
 cin >> name;
 name = raw_input("What is your name?")

Read in from file:
 #include <fstream>
 #include <iostream>
 #include <string>

 int main( )
 {
     string lineFromFile;
     ifstream file;
     file.open("test.txt");
     getline(file,lineFromFile);
     file.close( );
     return 0;
} 
 import string

 file = open("test.txt", 'r')
 lineFromFile = f.readline( )
 file.close( )
 

Write to file:
 #include <fstream>
 #include <iostream>
 #include <string>

 int main( )
 {
     ifstream file;
     file.open("test.txt");
     file << "Write this to file\n"; 
     file.close( );
     return 0;
} 
 import string

 file = open("test.txt", 'w')
 file.write("Write this to file\n")
 file.close( )