0% found this document useful (0 votes)
14 views

CC-02-Python

Uploaded by

gouthamrathod01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

CC-02-Python

Uploaded by

gouthamrathod01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

From Python to C

Dr. Charles R. Severance


www.cc4e.com
code.cc4e.com (sample code)
online.dr-chuck.com
Science Calculations
Evolution of Computer Languages
System

System

bash (79)
C uses curly braces
{ } for code blocks.

Scripting/
Interpreted

http://en.wikipedia.org/wiki/History_of_programming_languages
Learning Path: online.dr-chuck.com
• History – ihts.dr-chuck.com
• Python – www.py4e.com
• Django (Python, HTML, CSS, SQL, JavaScript) – www.dj4e.com
• Web Applications (PHP, HTML, CSS, SQL, JavaScript) – www.wa4e.com
• PostgreSQL (SQL) – www.pg4e.com
• C Programming – www.cc4e.com ← We are here 
• Computer Architecture
• Java Enterprise Application Development
Python and C
• White space is essential • Whitespace ignored
• Very object oriented • Not object oriented at all
• Convenient data structures • Fast efficient powerful
• list • struct
• dict • Pointers
• Auto memory management • Manual memory management
• 1980's • 1970's
In many ways, Python is a convenience layer built on top of C to make it
so users could write code without worrying about the complex details.
C Through A Python Lens
Learning by example
Rosetta Stone
This file is licensed under the Creative Commons Attribution-Share Alike 4.0
International license. Attribution: © Hans Hillewaert
https://en.wikipedia.org/wiki/Rosetta_Stone#/media/File:Rosetta_Stone.JPG
These code examples
• Most of these examples are also programming exercises
• It is my intention that you watch these lectures and work on the
exercises at the same time
• These exercises are not trying to assess what you learned
• Watching and listening to the lecture and then typing this code in to
make it work is the learning objective of this lecture
• After this section – you should do the assignments yourself (i.e. don’t
search) to gain maximum benefit
Similarities
• Arithmetic Operators: + - * / %
• Comparison Operators: == != < > <= the same
• Variable naming rules – letter/underscore +
numbers/letters/underscores – also case matters
• While loops – also break and continue in loops
• Constants similar except for strings and characters and booleans
• Both have int / float, and char / byte
• C has no str, list, or dict
• Python has no struct or double
Differences
• Boolean operators
• and / not / or versus && ! ||
• C for loops are indeterminant (i.e. no for ... in in C)
• C has no pre-defined True or False
• None and NULL are similar concepts but quite different
• Strings and character arrays are similar concepts but *very* different
• C has no list, or dict
• Python has no struct - float in Python is a C double
Output #include <stdio.h>
/* I am a comment */
# I am a comment int main() {
print('Hello world') printf("Hello world\n");
print('Answer', 42) printf("Answer %d\n", 42);
print('Name', 'Sarah') printf("Name %s\n", "Sarah");
print('x',3.5,'i',100) printf("x %.1f i %d\n", 3.5, 100);
}

Hello world
Answer 42
Name Sarah
x 3.5 i 100

cc_02_01.c
Number Input #include <stdio.h>
int main() {
print('Enter US Floor') int usf, euf;
usf = int(input()) printf("Enter US Floor\n");
euf = usf - 1 scanf("%d", &usf);
print('EU Floor', euf) euf = usf – 1;
printf("EU Floor %d\n", euf);
}

Enter US Floor
2 For those of us who learned Python 2, recall the difference
EU Floor 1 between input() and raw_input(). In Python 3 there is only
input() which is the same as Python 2's raw_input(). In C,
scanf("%d", ...) is more like Python 2's input().

cc_02_02.c
for string input we dont need an & to store it.

String Input #include <stdio.h>


int main() {
print('Enter name') char name[100];
name = input() printf("Enter name\n");
print('Hello', name) scanf("%100s", name);
printf("Hello %s\n", name);
}

Enter name
Sarah
Hello Sarah

cc_02_03.c
[^\n] this comes from regular expressions, which means scan

Line Input until you get a new line.


#include <stdio.h>
int main() {
print('Enter line') char line[1001];
line = input() printf("Enter line\n");
print('Line:', line) scanf("%1000[^\n]s", line);
printf("Line: %s\n", line);
}

Enter line
Hello world - have a nice day
Line: Hello world - have a nice day

cc_02_04.c
Line Input (safe) #include <stdio.h>
int main() {
print('Enter line') char line[1000];
line = input() printf("Enter line\n");
print('Line:', line) fgets(line, 1000, stdin);
printf("Line: %s\n", line);
}

Enter line
Hello world - have a nice day
Line: Hello world - have a nice day

cc_02_09.c
Read A File #include <stdio.h>
int main() {
hand = open('romeo.txt') char line[1000];
for line in hand: FILE *hand;
print(line.strip()) hand = fopen("romeo.txt", "r");
while( fgets(line, 1000, hand) != NULL ) {
printf("%s", line);
}
}

But soft what light through yonder window breaks


It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

cc_02_06.c
Counted Loop #include <stdio.h>
int main() {
for i in range(5) : int i;
print(i) for(i=0; i<5; i++) {
printf("%d\n",i);
}
}

0
1
2
3
4

cc_02_07.c
Max / Min Python
maxval = None
minval = None
while True:
line = input()
line = line.strip()
if line == "done" : break 5
ival = int(line) 2
if ( maxval is None or ival > maxval) : 9
maxval = ival done
if ( minval is None or ival < minval) : Maximum 9
minval = ival Minimum 2
print('Maximum', maxval)
print('Minimum', minval)

cc_02_08.py
Max / Min C
#include <stdio.h>
5
int main() {
2
int first = 1;
9
int val, maxval, minval;
(EOF)
Maximum 9
while(scanf("%d",&val) != EOF ) {
Minimum 2
if ( first || val > maxval ) maxval = val;
if ( first || val < minval ) minval = val;
first = 0;
}
529
(EOF)
printf("Maximum %d\n", maxval);
Maximum 9
printf("Minimum %d\n", minval);
Minimum 2
}

cc_02_08.c
Guessing #include <stdio.h>
int main() {
int guess;
while(scanf("%d",&guess) != EOF ) {
while True: if ( guess == 42 ) {
try: printf("Nice work!\n");
line = input() break;
except: # If we get EOF }
break else if ( guess < 42 )
line = line.strip() printf("Too low - guess again\n");
guess = int(line) else
if guess == 42: printf("Too high - guess again\n");
print('Nice work!') }
break }
elif guess < 42 :
print('Too low - guess again') 5
else : Too low - guess again
print('Too high - guess again') 50
Too high - guess again
42
Nice work!
cc_02_09.c
Functions (call by value)
#include <stdio.h>
def mymult(a,b): int main() {
c = a * b int mymult();
return c int retval;

retval = mymult(6, 7) retval = mymult(6,7);


print('Answer:', retval) printf("Answer: %d\n",retval);
}

int mymult(a, b)
int a,b;
Answer: 42 {
int c = a * b;
return c;
}

cc_02_10.c
Shouting #include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
hand = open('romeo.txt') char line[1000];
for line in hand: FILE *hand;
print(line.strip().upper()) int i;
hand = fopen("romeo.txt", "r");
while( fgets(line, 1000, hand) != NULL )
for(i=0; i<strlen(line); i++)
putchar(toupper(line[i]));
}

BUT SOFT WHAT LIGHT THROUGH YONDER WINDOW BREAKS


IT IS THE EAST AND JULIET IS THE SUN
ARISE FAIR SUN AND KILL THE ENVIOUS MOON
WHO IS ALREADY SICK AND PALE WITH GRIEF

cc_02_11.c
Summary
• Input/Output • Way too complex to implement
• Looping in C (for now)
• Python str()
• Reading a file • Python list()
• Strings • Python dict()
• Float • We will revisit these as the end
of the course
Acknowledgements / Contributions
These slides are Copyright 2020- Charles R. Severance (online.dr-chuck.com) Continue new Contributors and Translators here
as part of www.cc4e.com and made available under a Creative Commons
Attribution 4.0 License. Please maintain this last slide in all copies of the
document to comply with the attribution requirements of the license. If you
make a change, feel free to add your name and organization to the list of
contributors on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan School of


Information

Insert new Contributors and Translators here including names and dates

You might also like