0% found this document useful (0 votes)
27 views23 pages

CC 02 Python

Uploaded by

ayoub
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views23 pages

CC 02 Python

Uploaded by

ayoub
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

From Python to C

Dr. Charles R. Severance


[Link]
Evolution of Computer Languages
Science Calculations

System

System

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

Scripting/
Interpreted

[Link]
Learning Path: [Link]
• History – [Link]
• Python – [Link]
• Django (Python, HTML, CSS, SQL, JavaScript) – [Link]
• Web Applications (PHP, HTML, CSS, SQL, JavaScript) – [Link]
• PostgreSQL (SQL) – [Link]
• C Programming – [Link] ← 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
[Link]
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',10) 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
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
Line Input #include <stdio.h>
int main() {
print('Enter line') char line[1000];
line = input() printf("Enter line\n");
print('Line:', line) scanf("%[^\n]1000s", 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('[Link]') char line[1000];
for line in hand: FILE *hand;
print([Link]()) hand = fopen("[Link]", "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 = [Link]()
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 = [Link]() 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('[Link]') char line[1000];
for line in hand: FILE *hand;
print([Link]().upper()) int i;
hand = fopen("[Link]", "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 ([Link]) Continue new Contributors and Translators here
as part of [Link] 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

Common questions

Powered by AI

Python's input/output operations, encapsulated in simple functions like 'input()' and 'print()', exemplify its design for ease and efficiency. C's use of 'scanf' and 'printf' demands more control over data types and formats, reflecting its emphasis on flexibility and performance. This showcases Python's abstraction for user-friendliness versus C's power for detailed processes .

Python manages memory automatically through a garbage collector, which cleans up unused objects, allowing programmers to focus on logic rather than memory allocation. C, however, requires manual memory management using functions like malloc and free, which can be error-prone and lead to memory leaks if not handled correctly. These differences shift the complexity from programmers in Python while providing greater control but potential pitfalls in C .

Python simplifies string input handling by using the 'input()' function, which reads a line from the standard input and returns it as a string. C, however, requires explicit memory management and buffer size specification, using functions like 'scanf' and 'fgets' to handle string input. This difference highlights Python's abstraction efficiency compared to C's need for more detailed manual handling .

Python uses exceptions to handle errors, such as 'try-except' blocks, providing a controlled way to catch and manage runtime errors, including user input mishaps. C relies on return values and manual error checks, which entail more boilerplate code and less automatic handling. Python's approach offers simplicity and reliability, whereas C demands explicit error-checking logic .

Python and C implement boolean operators differently. Python uses 'and', 'not', and 'or' for boolean operations, which are more intuitive and readable, while C uses symbols like &&, !, and ||. This difference illustrates Python's design focus on readability and ease of use .

Python simplifies programming compared to C by providing higher-level features such as automatic memory management, more convenient data structures like lists and dictionaries, and being very object-oriented. Additionally, Python's syntax is more user-friendly with its use of whitespace to denote code blocks, unlike C, which requires manual memory management and uses curly braces for code blocks .

Python lacks built-in structs and character arrays, common in C, but compensates with versatile data structures like lists and dictionaries, and dynamic typing. C's structs and arrays offer direct memory layout control, beneficial for low-level programming. Python's flexibility and abstraction lead to easier handling of complex data structures without the need for predefined layouts .

'Call by value' means that a function receives copies of the arguments passed to it, rather than direct references. In both Python and C, changes to parameters within the function do not affect the original arguments. For example, in the function 'mymult', both Python and C receive copies of a and b. Any operations within affect only the local copies, and modifications do not alter the original values .

Python does have 'True' and 'False' as built-in keywords representing boolean values, providing a clear approach to logical operations. On the contrary, C uses integers 1 and 0, which can lead to potential misinterpretations in code logic and less intuitive readability. Python's dedicated boolean keywords enhance clarity and intent in logical expressions .

Python uses significant whitespace to enhance code readability and reduce visual clutter, aligning with its philosophy of clear and readable code. Unlike C, which uses curly braces to define code blocks, Python treats indentation levels as code structure markers, which can help prevent errors from misaligned braces .

You might also like