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.
The while statement
In this section you will learn about
Loops (repeat code) with while
What continue is
What break does
Simple loops with while
Another extremely important part of programming is being able to run the same code over and over again. A loop is code that is repeated until the condition for the loop to continue is no longer met.
Most programming languages have the so-called while statement. In Python, we write while condition:, which repeats a piece of code while (English: while) the condition is true.
Example
A while statement is used to print the numbers one to ten.
x = 1
while x <= 10:
print(x)
x = x + 1
x = 1
while x <= 10:
print(x)
x = x + 1
In the example above, x starts with the value one. On line 2, the program reaches the while loop and checks if x <= 10, which is true.
Then we go down into the code block under while, print 1 and then x + 1 is assigned to x. We simply add one to x (increment x by 1) and x is now equal to two.
Since we are in a while loop, we return to line 2 and check if x still less than or equal to 10. This is true (x = 2), so we run the code inside the while statement again.
The program continues in this way until 10 is printed and the value 11 is stored in x.
Then, when the program returns to line 2, it is no longer true that x <= 10, so we are done with the while statement.
It is understandable if you find x = x + 1 strange. In mathematics, it means something completely different.
Therefore, it is important to remember here that = means assignment in Python (and most programming languages).
It is very important that you understand the example and the text above, so please read it again until you understand it. Also, don't be afraid to experiment with the code.
Consider: what happens if we forget to increment x by one in each loop?
Change the while loop so that only odd numbers between 1 and 10 are printed (the number 1 should be included).
-- Output from your program will be here --
Did you figure out what happens if we forget to increment x by one for each loop or for each iteration as it is also called?
Then the loop will never end and we will get an infinite loop. All programmers sooner or later encounter an infinite loop, it is a fairly common bug.
Example
An infinite loop. If you run the code below, it might eventually crash your browser. That's why there's a stop button! It's good to have when the program has accidentally entered an infinite loop.
Can you change the code so that the program stops?
x = 0
while x < 5:
print(x)
x = 0
while x < 5:
print(x)
Example - ett enkelt "spel"
In this simple game, you have to guess what the result of a calculation is. If you guess smartly, you can find the answer quite quickly! Reminder: the % operator means remainder in division.
x = -1
facit = 124861357 % 107
while x != facit:
x = int( input('What do you think 124861357 % 107 is?') )
if x < facit:
print('You guessed too low.')
elif x > facit:
print('You guessed too high.')
print('You guessed ' + str(x) + ' and that\'s correct!')
x = -1
facit = 124861357 % 107
while x != facit:
x = int( input('What do you think 124861357 % 107 is?') )
if x < facit:
print('You guessed too low.')
elif x > facit:
print('You guessed too high.')
print('You guessed ' + str(x) + ' and that\'s correct!')
Here's how the program works in broad terms: The loop runs while the guess is not equal to the correct answer. Once inside the loop, x gets the value of the new guess. We test if x is greater than or less than the correct answer
and print something appropriate. When the while loop finally sees that x != correct answer is false (we have a correct answer), the loop is terminated, and we print that the user guessed correctly.
break and continue
To break a loop during execution, break is used. To continue with the next iteration without running more code in the current iteration, continue is used.
As we see in the example below, break can, for example, be used if you always want to run the code in the loop at least once.
Example
The code in the while loop always runs at least once. The condition to break the while statement is at the end instead. With while True: the loop runs until it is broken.
while True:
answer = input('What year did Gustav Vasa become king?')
if answer == '1523':
break
while True:
answer = input('What year did Gustav Vasa become king?')
if answer == '1523':
break
print('Congratulations! You escaped the loop!')
Example
A program that prints the square root (which is the same as raising to the power of one half) of the input. If the user provides a negative number, continue is used to avoid calculating the square root of a negative number. Zero is used to exit.
while True:
number = float( input('What do you want to take the square root of? (Exit with 0)') )
if number < 0:
continue
elif number == 0:
break
print(number**0.5)
while True:
number = float( input('What do you want to take the square root of? (Exit with 0)') )
if number < 0:
continue
elif number == 0:
break
print(number**0.5)
Example - is the number prime?
Now we will do a simple test of an integer to see if it is a prime number.
A prime number is only divisible by itself and one.
We simply test if there is any number that contradicts it.
We do not need to test dividing numbers larger than the square root of the number. Why?
If you try some large random numbers, you will see that it is quite difficult to find a large prime number.
number = int( input('Which number do you want to test?') )
x = 2
is_prime = True
while x <= number ** 0.5:
if number % x == 0:
is_prime = False
break
x = x + 1
if is_prime:
print(str(number) + ' is a prime number.')
else:
print(str(number) + ' is NOT a prime number.')
number = int( input('Which number do you want to test?') )
x = 2
is_prime = True
while x <= number ** 0.5:
if number % x == 0:
is_prime = False
break
x = x + 1
if is_prime:
print(str(number) + ' is a prime number.')
else:
print(str(number) + ' is NOT a prime number.')
print('It is divisible by ' + str(x) + '.')