OBS!
Fönstret är för smalt för att använda pythonlabbet.se. Använd en enhet med tangentbord!
Reference
Click on a function to read more.
Basics part 1
Syntax
Short description
break
break interrupts code that is repeated
Example
while True:
print('You are nice!')
answer = input('Should I stop saying that? Write yes in that case.')
if answer == 'yes':
break
Explanation
break interrupts code that is repeated. For example when while is used.
continue
continue interrupts a repetition and starts the next
Example
i = 0
while i < 100:
if i % 2 == 0: # continue with the next repetition if i is divisible by 2
continue
print(i,'is an odd number')
Explanation
continue interrupts the execution in the current repetition/iteration and continues with the next repetition. Used in while-statements and for-statements.
elif
elif is a combination of else and if
Example #1
temp = int(input('What is the temperature?'))
if temp > 20:
print('Warm and nice!')
elif temp > 0: #if temp <= 20 and temp > 0
print('Not very cold, but not so warm either.')
Example #2
number = int(input('Enter an integer'))
if number == 0:
print('You entered the number 0.')
elif number > 0:
print('You entered a positive number.')
else:
print('You entered a negative number.')
Explanation
elif is only used after if. It is a combination of else and if, meaning ELSE (if the above is false) and IF (if the new condition is true). The condition for elif is only tested if the condition for if is false.
Syntax
elif condition:
condition
Required. Something that is True or False.
else
else can be used last in an if-statement
Example
age = int(input('How old are you?'))
if age >= 18:
print('You are an adult!')
else:
print('You are not an adult.')
Explanation
else is only used at the end of a block that starts with if, and the code under else is only executed if the condition for if is false.
float()
Converts to type float (decimal number)
Example
float('0.01') #converts the string '0.01' to 0.01
float(10) #converts the integer 10 to 10.0
Explanation
The function float() converts the argument to type float (decimal number). Usually, the argument is a string or an integer.
Syntax
float(number)
Argument
number
A number in the form of a string or an integer.
if
if controls the code to do different things depending on a condition
Example #1
number = 10
if number == 10:
print('The number is equal to 10.') #this will be printed
Example #2
number = int(input('Enter an integer'))
if number == 0:
print('You entered the number 0.')
elif number > 0:
print('You entered a positive number.')
else:
print('You entered a negative number.')
Explanation
if is used to control what the program does depending on a condition. If the condition is true, the code in the if-block is executed. To control
what happens if the condition is not true, elif and else can be used.
Syntax
if condition:
condition
Required. Something that is True or False.
input()
Receives input from the user
Example
answer = input('What is your name?') #The user's answer is saved in the variable answer
Explanation
The function input() allows the user to enter input into the program. It is possible to include text that describes what should be entered.
Syntax
input(prompt)
Argument
prompt
An optional text the user sees.
int()
Converts to type int (integer)
Example
int(42) #converts the string '42' to 42
int(3.94) #converts the decimal number 3.94 to 3
Explanation
The function int() converts the argument to type int (integer). Usually, the argument is a string or a decimal number.
Syntax
int(number)
Argument
number
A number in the form of a string or a decimal number.
print()
Prints text or the content of a variable to the screen
Example #1
print('Hello World') #prints "Hello World"
print(1+1) #prints the number 2
print(x) #prints the content of variable x
Example #2
print('Hello World', end='') #prints "Hello World" without a new line
Example #3
print('Hej','på','dig') #Prints "Hello to you"
print('Hej','på','dig',sep=' | ',end='!') #prints "Hello | to | you!" without a new line at the end.
Explanation
The function print() prints a string to the screen. Automatically tries to convert what is to be printed to text.
Syntax
print(*object, sep=' ', end='\n')
Argument
*object
Required. One or more objects to be printed. Separate objects with commas.
sep
Character to separate the objects being printed. Default is space.
end
Character that ends the text being printed. Default is "\n" - which means new line.
randint()
Generates a random integer
Example
from random import randint
roll = randint(1,6) #a random number 1-6
Explanation
The function randint() generates a random integer between two integer values a and b such that a <= N <= b. randint is in the random module.
Syntax
randint(a,b)
Argument
a
The smallest random number that can be generated.
b
The largest random number that can be generated.
round()
Rounds a number
Example #1
round(7.89) #rounds to 8
round(1.23) #rounds to 1
Example #2
round(1.23456,2) #rounds 1.23
round(1.23456,4) #rounds to 1.2346
Explanation
The function round() rounds a decimal number. By default to an integer, it is possible to set round() to round to an arbitrary number of decimals.
Syntax
round(number, decimalplaces = 0)
Argument
number
Required. The number to be rounded.
decimalplaces
Number of decimals the number should be rounded to. Default is 0.
str()
Converts to type string
Example #1
str(2.71) #converts the decimal number 2.71 to the string '2.71'
str(10) #converts the integer 10 to '10'
Example #2
age = 15
print('You are ' + str(age) + ' years old.')
Explanation
The function str() converts the argument to a string. Often the argument is an integer or a decimal number. It can also be significantly more complex data types that can be converted to strings.
Syntax
str(object)
Argument
object
An object that can be converted to a string.
while
while is used to repeat code
Example
n = int(input('How many numbers do you want to print?'))
i = 1
while i <= n:
print(i)
i = i + 1
Explanation
while repeats the code in the block as long as the condition is true.
Syntax
while condition:
condition
Required. Something that is True or False. Must become false at some point for the while-block to be exited.
Variables and Data Types
In this section you will learn
What a variable is and how to create one
About different data types and conversions between them
Variables - storing data
A variable is for storing data and is used everywhere in programming.
Often strings or numbers are stored, but it can also be other more complicated data structures and objects.
A variable is for remembering something while the program is running, for example, the result of a calculation so that it can then be reused elsewhere in the program.
It is also common to use variables to store user input or data that has been read from a file.
Variables are used everywhere in programming.
The name variable comes from the fact that the program can change (vary) the content of a variable during the program's execution.
What is placed in a variable is stored in the computer's working memory and disappears when the program is no longer running.
To create a variable, = (equals sign) is used; to the left of the equals sign is the variable name and to the right of the equals sign is the value to be stored in the variable.
It is important here to understand the difference between = in mathematics (is equal to) and in Python (assign value to variable).
It is fine to use print(my_variable) to print the content of the variable.
Example
The string Hello World is stored in the variable named my_variable.
my_variable = 'Hello World'
my_variable = 'Hello World'
print(my_variable)
It is important to write good variable names. The name should describe the information stored in the variable.
With good variable names, the program is easier to understand and it becomes easier to do it right. It takes a long time to learn to write good variable names, so don't despair if you find it difficult!
In Python, the convention is to write variables with lowercase letters and with _ to separate words.
Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.
-- Output from your program will be here --
Question: What will the program print?
FirstSecond
First Second
Data Types
Computers must distinguish between different types of variables, such as strings (text) and numbers. This is because they are stored in different ways in the computer's memory.
For example, the number 1 and the string '1' are represented in different ways in memory.
We have already used three common variable types: strings (eng: string), integers (eng: integer) and floating-point numbers (eng: float).
Floating-point numbers (pronounced float-numbers) are the most common way for a computer to represent numbers with decimal points.
When you create a variable, Python figures out what type the variable is. In many programming languages, you have to tell what type a variable is when you create it, and then you cannot change what type the variable is. In Python, for example, you can first store a string in a variable and then later store a number in the same variable.
The built-in function type can be used to see what type a variable has, see the example below.
Example
First, three different variables are created with the types string, integer, and float. Then, three more variables are created that contain the type of the first three variables.
The helper functions str, int, and float are available to convert the three types above between each other. For example, int is used to convert a variable to the integer type.
Note that it does not always work; for example, the string 'hello' cannot be converted to either an integer or a float.
Example
Some common type conversions.
integer_number = int('42') #the string 42 becomes the integer 42
float_number = float(10) #the integer 10 becomes the float 10.0
text = str(3.14) #the float 3.14 becomes the string 3.14
The code below contains an error. Run the program and see what the error message is. Then fix the code and run the program again.
-- Output from your program will be here --
The built-in function print can receive different types in its argument (what is inside the parentheses of a function is called an argument).
The print function automatically converts the argument to a string. If you write, for example, print(5), the number 5 is automatically converted to a string.
Rounding
If a float is converted to an integer using int, the decimals are simply removed.
Example
Float to integer with int.
x = int(3.99) #x = 3
x = int(3.99)
print(x)
With the built-in function round, we can instead round a float to an integer.
Example
Float to integer with round.
x = round(3.99) #x = 4
x = round(3.99)
print(x)
With the help of round, it is also possible to round to any number of decimals. Inside the parenthesis, we first write the number to be rounded, followed by a comma, and then how many decimals we want to round to.
Example
Round to two and four decimals.
x = round(1.23456, 2) #x = 1.23
y = round(1.23456, 4) #y = 1.2346
x = round(1.23456, 2)
y = round(1.23456, 4)
print(x)
print(y)