Nov-20-2020, 10:13 AM
Please use the
The comparison of str is made via lexicographical order.
Here are some hexadecimal values:
Whitespace == 0x20
0 - 9 == 0x30 - 0x39
A - Z == 0x41 - 0x5a
a - z == 0x61 - 0x7a
If you compare this:
The interpreter compares char by char.
If you want to compare numbers, then convert the
[python][/python]tags to wrap your code. Otherwise the indentation is lost and syntax highlighting does not work.
print("hello world!") print("What is your name?") name = input() print("That is a nice name, " + name) print("How old are you, " + name + " p.s. put a zero infront of a single digit") age = input() if age >= "18": print("if you're " + age + ", that means it's beer o'clock!") diff = str(18 - (int(age))) if age < "18": print("That means you have to wait " + diff + " years to have a drink on me!")In Line 9 you're comparing two strings.
The comparison of str is made via lexicographical order.
Here are some hexadecimal values:
Whitespace == 0x20
0 - 9 == 0x30 - 0x39
A - Z == 0x41 - 0x5a
a - z == 0x61 - 0x7a
If you compare this:
"1" > "18"
The interpreter compares char by char.
(0x31,) > (0x31, 0x38)But if you compare
"4" > "18"
, you have this values:(0x34,) > (0x31, 0x38)So, the first one is bigger and this explains why
"4" > "18" == True
.If you want to compare numbers, then convert the
str
into int
.print("hello world!") print("What is your name?") name = input() print("That is a nice name, " + name) print("How old are you, " + name + " p.s. put a zero infront of a single digit") age = int(input()) if age >= 18: print("if you're " + str(age) + ", that means it's beer o'clock!") diff = 18 - age if age < 18: print("That means you have to wait " + str(diff) + " years to have a drink on me!")The concatenation of
str
should not be done with +
operator. If you work with int
, float
or other types, you've to convert them back to a str
. Instead, use string formatting. With modern Python, we have f-strings. A f
in front of the "
introduces a format-string. The names in the curly braces are replaced with their values. For example, {age} is replaced with the age, which is an int
.print("hello world!") print("What is your name?") name = input() print(f"That is a nice name {name}") print(f"How old are you {name}") age = int(input()) if age >= 18: print(f"if you're {age} that means it's beer o'clock!") diff = 18 - age if age < 18: print(f"That means you have to wait {diff} years to have a drink on me!")The benefit is, that you don't have to convert the
int
explicit back to a str
if you're using string formatting.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!