0% found this document useful (0 votes)
2 views8 pages

Python Notes

The document explains the differences between machine language and high-level programming languages, emphasizing the need for a common language for humans and computers. It covers basic programming concepts, including syntax, variables, and functions in Python, along with examples of using the print() function and performing arithmetic operations. Additionally, it discusses input handling, type conversions, and string manipulation in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Python Notes

The document explains the differences between machine language and high-level programming languages, emphasizing the need for a common language for humans and computers. It covers basic programming concepts, including syntax, variables, and functions in Python, along with examples of using the print() function and performing arithmetic operations. Additionally, it discusses input handling, type conversions, and string manipulation in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Machine language vs.

high-level language
The IL is, in fact, the alphabet of a machine language. This is the simplest and most primary
set of symbols we can use to give commands to a computer. It's the computer's mother tongue.
Unfortunately, this mother tongue is a far cry from a human mother tongue. We both (computers
and humans) need something else, a common language for computers and humans, or a bridge
between the two different worlds.
We need a language in which humans can write their programs and a language that computers
may use to execute the programs, one that is far more complex than machine language and yet
far simpler than natural language.
Such languages are often called high-level programming languages. They are at least somewhat
similar to natural ones in that they use symbols, words and conventions readable to humans.
These languages enable humans to express commands to computers that are much more complex
than those offered by ILs.
A program written in a high-level programming language is called a source code (in contrast to
the machine code executed by computers). Similarly, the file containing the source code is called
the source file.

Compilation vs. Interpretation


Computer programming is the act of composing the selected programming language's elements
in the order that will cause the desired effect. The effect could be different in every specific case
– it's up to the programmer's imagination, knowledge and experience.

Of course, such a composition has to be correct in many senses:

 alphabetically – a program needs to be written in a recognizable script, such as Roman,


Cyrillic, etc.
 lexically – each programming language has its dictionary and you need to master it;
thankfully, it's much simpler and smaller than the dictionary of any natural language;
 syntactically – each language has its rules and they must be obeyed;
 semantically – the program has to make sense.

Your very first program


print("Hello, world!")

As you can see, this first program consists of the following parts:

 the word print;


 an opening parenthesis;
 a quotation mark;
 a line of text: Hello, World!;
 another quotation mark;
 a closing parenthesis.

Each of the above plays a very important role in the code.

Working with the print () function

Scenario

The print() command, which is one of the easiest directives in Python, simply prints out a line to
the screen.

In your first lab:

 Use the print() function to print the line Hello, Python! to the screen. Use double quotes
around the string.
 Having done that, use the print() function again, but this time print your first name.
 Remove the double quotes and run your code. Watch Python's reaction. What kind of
error is thrown?
 Then, remove the parentheses, put back the double quotes, and run your code again. What
kind of error is thrown this time?
 Experiment as much as you can. Change double quotes to single quotes, use
multiple print() functions on the same line, and then on different lines. See what
happens.

Python escape and newline characters

print("The itsy bitsy spider\nclimbed up the waterspout.")

print()

print("Down came the rain\nand washed the spider out.")

Using multiple arguments


print("The itsy bitsy spider" , "climbed up" , "the waterspout.")

Positional arguments
print("My name is", "Python.")
print("Monty Python.")

Keyword arguments
print("My name is", "Python.", end=" ")
print("Monty Python.")
print("My", "name", "is", "Monty", "Python.", sep="*")
print("My", "name", "is", sep="_", end="*")
print("Monty", "Python.", sep="*", end="*\n")
Literals – the data in itself
A literal is data whose values are determined by the literal itself.

Integer division (floor division)

A // (double slash) sign is an integer division operator. It differs from the standard / operator in
two details:

 its result lacks the fractional part ‒ it's absent (for integers), or is always equal to zero (for
floats); this means that the results are always rounded;
 it conforms to the integer vs. float rule.

print(6 // 3)
print(6 // 3.)
print(6. // 3)
print(6. // 3.)

Remainder (modulo)

The next operator is quite a peculiar one, because it has no equivalent among traditional
arithmetic operators.

Its graphical representation in Python is the % (percent) sign, which may look a bit confusing.

Try to think of it as a slash (division operator) accompanied by two funny little circles.

The result of the operator is a remainder left after the integer division.

In other words, it's the value left over after dividing one value by another to produce an integer
quotient.

Note: the operator is sometimes called modulo in other programming languages.

print(14 % 4)
Variables
A variable comes into existence as a result of assigning a value to it. Unlike in other
languages, you don't need to declare it in any special way.

If you assign any value to a nonexistent variable, the variable will be automatically created.
You don't need to do anything else.

The creation (in other words, its syntax) is extremely simple: just use the name of the desired
variable, then the equal sign (=) and the value you want to put into the variable.

var = 1

print(var)

How to use a variable

var = 1

account_balance = 1000.0

client_name = 'John Doe'

print(var, account_balance, client_name)

print(var)

Assign a new value to an already existing variable

var = 1

print(var)

var = var + 1

print(var)

Scenario
Here is a short story:

Once upon a time in Appleland, John had three apples, Mary had five apples, and Adam had six
apples. They were all very happy and lived for a long time. End of story.

Your task is to:


 create the variables: john, mary, and adam;
 assign values to the variables. The values must be equal to the numbers of fruit possessed
by John, Mary, and Adam respectively;
 having stored the numbers in the variables, print the variables on one line, and separate
each of them with a comma;
 now create a new variable named total_apples equal to the addition of the three previous
variables.
 print the value stored in total_apples to the console;
 experiment with your code: create new variables, assign different values to them, and
perform various arithmetic operations on them (e.g., +, -, *, /, //, etc.). Try to print a string
and an integer together on one line, e.g., "Total number of apples:" and total_apples.

Variables ‒ a simple converter

Scenario
Miles and kilometers are units of length or distance.

Bearing in mind that 1 mile is equal to approximately 1.61 kilometers, complete the program so
that it converts:

 miles to kilometers;
 kilometers to miles.

kilometers = 12.25

miles = 7.38

miles_to_kilometers = your code

kilometers_to_miles = your code

print(miles, "miles is", round(miles_to_kilometers, 2), "kilometers")

print(kilometers, "kilometers is", round(kilometers_to_miles, 2), "miles")

Scenario

Take a look at the code : it reads a float value, puts it into a variable named x, and prints the
value of a variable named y. Your task is to complete the code in order to evaluate the following
expression:
3x3 - 2x2 + 3x - 1
The result should be assigned to y.
x = # Hardcode your test data here.
x = float(x)
# Write your code here.
print("y =", y)

ct The input() functionion with the user


print("Tell me anything...")
anything = input()
print("Hmm...", anything, "... Really?")

The input() function with an argument


The input() function can do something else: it can prompt the user without any help from print().
anything = input("Tell me anything...")
print("Hmm...", anything, "...Really?")
The result of the input() function
The result of the input() function is a string
This means that you mustn't use it as an argument of any arithmetic operation, e.g., you
can't use this data to square it, divide it by anything, or divide anything by it.
anything = input("Enter a number: ")
something = anything ** 2.0
print(anything, "to the power of 2 is", something)
Type casting (type conversions)
Python offers two simple functions to specify a type of data and solve this problem ‒ here they
are: int() and float().
Their names are self-commenting:
 the int() function takes one argument (e.g., a string: int(string)) and tries to convert it
into an integer; if it fails, the whole program will fail too (there is a workaround for this
situation, but we'll show you this a little later);
 the float() function takes one argument (e.g., a string: float(string)) and tries to convert it
into a float (the rest is the same).
This is very simple and very effective. Moreover, you can invoke any of the functions by passing
the input() results directly to them. There's no need to use any variable as an intermediate
storage.
We've implemented the idea in the editor ‒ take a look at the code.
Can you imagine how the string entered by the user flows from input() into print()?
Try to run the modified code. Don't forget to enter a valid number
anything = float(input("Enter a number: "))
something = anything ** 2.0
print(anything, "to the power of 2 is", something)

leg_a = float(input("Input first leg length: "))


leg_b = float(input("Input second leg length: "))
hypo = (leg_a**2 + leg_b**2) ** .5
print("Hypotenuse length is", hypo)

String operators
fnam = input("May I have your first name, please? ")
lnam = input("May I have your last name, please? ")
print("Thank you.")
print("\nYour name is " + fnam + " " + lnam + ".")

Replication
The * (asterisk) sign, when applied to a string and number (or a number and string, as it remains
commutative in this position) becomes a replication operator:
string * number
number * string
print("+" + 10 * "-" + "+")
print(("|" + " " * 10 + "|\n") * 5, end="")
print("+" + 10 * "-" + "+")
Type conversions
str()

You already know how to use the int() and float() functions to convert a string into a
number.This type of conversion is not a one-way street. You can also convert a number into a
string, which is way easier and safer ‒ this kind of operation is always possible.
leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))

You might also like